创建带初始流动性的池
首次存入决定价格。例如,存入 1,000 ALPH 和 50 USDT,价格即为 1 ALPH = 0.05 USDT。const exists = await powfi.cpmm.poolExists(alph, usdt)
if (!exists) {
// preview: LP minted = sqrt(a*b) - 1000
const preview = CpmmModule.computeLiquidityAmounts({
tokenAId: alph,
tokenBId: usdt,
amountA: 1_000n * 10n ** 18n,
amountB: 50n * 10n ** 6n
})
const { poolId, result } = await powfi.cpmm.createPool({
tokenAId: alph,
tokenBId: usdt,
sender: address,
initialLiquidity: { tokenAAmount: preview.amountA, tokenBAmount: preview.amountB }
})
}
向已有的池添加流动性
让用户输入一侧的数量,根据储备量推导另一侧:const pool = await powfi.cpmm.getPoolState(alph, usdt)
const q = CpmmModule.computeLiquidityAmounts({
poolState: pool,
tokenAId: alph,
tokenBId: usdt,
amountA: 200n * 10n ** 18n,
inputType: 'TokenA'
})
// q.amountB -> USDT needed
// q.shareAmount -> LP tokens you'll receive
// q.sharePercentage -> your % of the pool after deposit
await powfi.cpmm.addLiquidity({
poolState: pool,
tokenAId: alph,
tokenBId: usdt,
amountA: q.amountA,
amountB: q.amountB,
slippageBps: 50n,
sender: address
})
读取头寸
LP 代币是普通的同质化代币,其 ID 就是池 ID:const lpTokenId = powfi.cpmm.getPoolId(alph, usdt)
const bal = await powfi.nodeProvider.addresses.getAddressesAddressBalance(address)
const lpBalance = BigInt(bal.tokenBalances?.find((t) => t.id === lpTokenId)?.amount ?? '0')
const { token0, amount0, token1, amount1 } = await powfi.cpmm.computeClaimableAmounts(alph, usdt, lpBalance)
移除流动性
const pool = await powfi.cpmm.getPoolState(alph, usdt)
const burn = lpBalance / 2n // withdraw 50%
const preview = CpmmModule.computeRemoveLiquidityAmounts(pool, lpBalance, burn)
// preview.amount0 / amount1 -> tokens you receive
// preview.remainSharePercentage
await powfi.cpmm.removeLiquidity({
poolState: pool,
liquidity: burn,
totalLiquidityAmount: lpBalance,
slippageBps: 50n,
sender: address
})