A Javascript library for interacting with the HumbleSwap DEx.
Methods are listed below, along with usage examples where possible.
Home Page
Liquidity Pools
Functions for managing liquidity pools (creating; adding/removing liquidity).
Swapping is in a separate document.
- Liquidity Pools
- All Sections
createLiquidityPool
async function createLiquidityPool(
acc: ReachAccount,
opts: CreatePoolTxnOpts
): Promise<TransactionResult<PoolInfo>>
Create a liquidity pool for a pair of tokens.
Transaction Options
type CreatePoolTxnOpts = {
tokenIds: [string | number, string | number];
tokenAmounts: [a: number, b: number];
} & ReachTxnOpts;
createLiquidityPool Example
import { createLiquidityPool } from "@reach-sh/humble-sdk";
// Options for calling "createLiquidity"
const createOpts = {
tokenAmounts: [100, 200] as [number, number],
tokenIds: [112233, 446688] as [any, any],
// progress bar updated
onProgress(msg: string) {
if (msg === 'SIGNING_EVENT') {
// This is emitted when the connected account will be asked to sign a transaction.
// You can ignore or use it to show a "Sign transaction in your wallet" message
} else {
// otherwise the message tells what the SDK is currently doing for this transaction
}
},
}
const acc = /* connected account */;
const result = await createLiquidityPool(acc, createOpts)
const { data, succeeded, message } = result
if (!succeeded || !data?.poolTokenId) {
// Pool creation failed; handle error
// or check 'message' for an explanation
}
// If here, Pool creation and funding was successful
const { poolAddress, tokenAId, tokenBId, poolTokenId } = data;
// do something with 'data'
createLiquidityPool Returns
PoolInfo about the new pool.
type PoolInfo = {
/** `Token A` id. Use '0' for network token */
tokenAId: string | number;
/** `Token B` id */
tokenBId: string | number;
/** Pool contract address (or Algorand application ID) */
poolAddress: string | number;
/** Number of decimal places for `Token A`. Defaults to `6` */
tokenADecimals?: number;
/** Number of decimal places for `Token B`. Defaults to `6` */
tokenBDecimals?: number;
/** When true, indicates this pool uses a network token (e.g. ALGO or ETH) */
n2nn?: boolean;
/** ID for pool liquidity token */
poolTokenId?: ResourceIdentifier;
}
calculateOtherAmount
function calculateOtherAmount(amountIn: number, tokenIn: string | number, pool: PoolDetails): string;
Use to calculate the other half of a liquidity deposit amount based on the pool. This will be relevant only for adding liquidity.
đź’ˇ If you are adding liquidity (depositing) into
A/Bpool, but only know how muchBtoken you want to deposit, usecalculateOtherAmount( ... )to calculate how muchAyou will pay based on that (B) amount.
calculateOtherAmount Example
See addLiquidity for example usage.
calculateOtherAmount Parameters
All input params are required.
amountIn: numberUser’s input amounttokenIn: string | numberThe token associated with the input amountpool: PoolDetailsThe Liquidity pool targettype PoolDetails = PoolInfo & { // Balance of user pool LP tokens (amount of user Liquidity in the pool) userLiquidity?: any; // LP Tokens minted for this pool mintedLiquidityTokens?: any; // Balance of Pool `Token A` tokenABalance?: string | number; // Fees accrued from `Token A` tokenAFees?: string | number; // Balance of Pool `Token B` tokenBBalance?: string | number; // Fees accrued from `Token B` tokenBFees?: string | number; }
calculateOtherAmount Returns
Amount of opposite token that will be required for the deposit as a string.
calculatePairOpposite
Renamed to calculateOtherAmount
addLiquidity
function addLiquidity(acc: ReachAccount, opts: DepositTxnOpts): Promise<TransactionResult>
Adds liquidity to a Pool.
addLiquidity Example
See fetchLiquidityPool or subscribeToPoolStream for pool sources.
import { addLiquidity } from "@reach-sh/humble-sdk";
const pool = /* pool source */
const { tokenAId } = pool;
// Order of inputs is important
const amountA = 100;
const amountB = calculateOtherAmount(amountA, tokenAId, pool);
// Create options for adding liquidity
const opts = {
pool,
amounts: [amountA, amountB],
optInToLPToken: true,
};
// Put it all together. If successful, `data` will contain the new total
// of LP tokens in the pool
const { succeeded, message, data } = await addLiquidity(acc, opts);
addLiquidity Parameters
acc: ReachAccount: reach account abstractionopts?: DepositTxnOptsAdditional options (see below).
For additional options, seeReachTxnOpts.DepositTxnOpts
type DepositTxnOpts = { // Deposit Amounts (for Pool tokens `A` and `B` respectively). Order of // amounts is important, or the transaction may fail. amounts: [amountA: number | string, amountB: number | string]; // Data about target pool to deposit pool: PoolInfo; // When true, will opt user account into pool liquidity token. If false and // user hasn't opted-in, the transaction may fail. Defaults to `false`. optInToLPToken?: boolean; } & ReachTxnOpts
addLiquidity Returns
TransactionResult
whereTransactionResult.datacontains minted pool LP tokens after deposit.
fetchLiquidityPool
function fetchLiquidityPool(acc: ReachAccount, opts?: FetchPoolOpts): Promise<FetchPoolTxnResult>;
Fetch data about a single liquidity pool.
fetchLiquidityPool Example
Get a pool ID or reference to one (see subscribeToPoolStream). The SDK now allows you to provide tokens along with your request, so that it doesn’t have to re-fetch them.
The following examples do not use a real pool id.
1. With Tokens
import { fetchLiquidityPool } from "@reach-sh/humble-sdk";
const acc = /* account source */;
const [tokenA, tokenB] = await Promise.all([ /* tokens source */ ])
const { succeeded, data, message } = await fetchLiquidityPool(acc, {
poolAddress: 1122334455,
n2nn: true,
includeTokens: false,
tokens: [ tokenA, tokenB ]
});
2. Without Tokens
import { fetchLiquidityPool } from "@reach-sh/humble-sdk";
// Get a pool ID or reference to one (see 'subscribeToPoolStream')
// The following is only an example, and is not a real pool id
const acc = /* account source */;
const { succeeded, data, message } = await fetchLiquidityPool(acc, {
poolAddress: 1122334455,
n2nn: true,
includeTokens: true
});
Handle the result
if (succeeded) {
// See 'FetchPoolTxnResult' for everything in 'data'
const { pool, tokens } = data;
console.log(pool); /* outputs ->
{
"poolAddress": "1122334455",
"poolTokenId": 76797026,
"mintedLiquidityTokens": 11858542,
"n2nn": true,
"tokenABalance": "1221314151617.88889",
"tokenAFees": "0",
"tokenAId": "0",
"tokenADecimals": 6,
"tokenBBalance": "1211314151617.3897",
"tokenBFees": "0",
"tokenBId": 10458941,
"tokenBDecimals": 6
}
*/
} else console.log(message)
fetchLiquidityPool Parameters
acc: ReachAccount: reach account abstractionpoolAddress: string | numberThe application ID (or contract address) of thePoolyou want to fetch.opts?: FetchPoolOptstype FetchPoolOpts = ReachTxnOpts & { n2nn: boolean; poolAddress: string | number includeTokens?: boolean tokens?: [Token, Token] };opts.n2nn: When set to true, this means one of the pool tokens is a network token (e.g. “ALGO” or “ETH”). The correct value is required for fetching the pool data.opts.poolAddress: Address of the pool you want to fetchopts.includeTokens: (optional) Whether to fetch pool tokens as well. If set to false, you MUST provide a pair of token objects to the function using the param belowopts.tokens: (optional) PoolTokens. Required whenincludeTokensis “true”
For additional options, see ReachTxnOpts.
fetchLiquidityPool Returns
For pool data properties, see PoolDetails
type FetchPoolTxnResult = {
// Whether the transaction succeeded or failed
succeeded: boolean;
// The pool address targeted for the txn
poolAddress?: string | number;
// Any useful data associated about the txn (or any error encountered)
data: {
/** Pool data */
pool: PoolDetails | null;
/** Pool token data */
tokens: [tokA: any, tokB: any];
/** Whether pool has liquidity and is tradeable */
tradeable: boolean;
};
// Optional success or failure message
message: string;
// Contract instance used for the transaction. Can be reused in subsequent calls.
contract?: ReachContract<typeof poolBackend | typeof poolBackendN2NN>;
};
withdrawLiquidity
export async function withdrawLiquidity(
acc: ReachAccount,
opts: WithdrawOpts
): Promise<TransactionResult>
Withdraw a percentage of the user’s liquidity from a Pool.
withdrawLiquidity Example
See fetchLiquidityPool or subscribeToPoolStream for pool sources.
const percentToWithdraw = 15; // Withdraw 15% of liquidity
const pool = /* pool source */;
const { succeeded, message, data } = await withdrawLiquidity(acc, {
percentToWithdraw,
n2nn: pool.n2nn,
poolAddress: pool.poolAddress,
poolTokenId: pool.poolTokenId,
});
withdrawLiquidity Parameters
acc: ReachAccount: reach account abstractionopts: WithdrawOpts: Withdrawal parameters.
For additional options, seeReachTxnOpts.type WithdrawOpts = ReachTxnOpts & { /** Percentage of liquidity to withdraw as a number. (e.g. 5 = `5%`) */ percentToWithdraw: number; poolTokenId: string | number; n2nn: boolean; }
withdrawLiquidity Returns
TransactionResult
If successful, thedatakey will contain{ poolLPTokens: number }wherepoolLPTokensis the total number of minted LP Tokens in the pool.