diff --git a/scripts/src/index.ts b/scripts/src/index.ts index b46832a..713827c 100644 --- a/scripts/src/index.ts +++ b/scripts/src/index.ts @@ -18,6 +18,7 @@ import { priceToSqrtPrice, simulateInvariantSwap, Tick, + TokenAmount, toPercentage, toPrice, toTokenAmount @@ -32,8 +33,9 @@ let TOKEN1_ID: string async function setupEssentials() { account = await getSigner(1000n * ONE_ALPH) INVARIANT_ADDRESS = (await Invariant.deploy(account, Network.Local)).address - TOKEN0_ID = await FungibleToken.deploy(account, 10n ** 30n, 'Coin', 'COIN', 12n) - TOKEN1_ID = await FungibleToken.deploy(account, 10n ** 30n, 'Coin', 'COIN', 12n) + const initMint = (10n ** 30n) as TokenAmount + TOKEN0_ID = await FungibleToken.deploy(account, initMint, 'Coin', 'COIN', 12n) + TOKEN1_ID = await FungibleToken.deploy(account, initMint, 'Coin', 'COIN', 12n) } const main = async () => { @@ -290,8 +292,9 @@ const usingAlphAsToken = async () => { const usingFungibleToken = async () => { // deploy token, it will return token ids - const TOKEN0_ID = await FungibleToken.deploy(account, 500n, 'CoinA', 'ACOIN', 12n) - const TOKEN1_ID = await FungibleToken.deploy(account, 500n, 'CoinB', 'BCOIN', 12n) + const initMint = 500n as TokenAmount + const TOKEN0_ID = await FungibleToken.deploy(account, initMint, 'CoinA', 'ACOIN', 12n) + const TOKEN1_ID = await FungibleToken.deploy(account, initMint, 'CoinB', 'BCOIN', 12n) // load token by passing its address (you can use existing one), it allows you to interact with it const token = await FungibleToken.load(Network.Local) diff --git a/src/consts.ts b/src/consts.ts index cd71de0..5e2e1a2 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -1,8 +1,36 @@ import { CLAMM, Invariant } from '../artifacts/ts' -import { SQRT_PRICE_DENOMINATOR, SQRT_PRICE_SCALE } from '../artifacts/ts/constants' +import { + MIN_SQRT_PRICE as _MIN_SQRT_PRICE, + MAX_SQRT_PRICE as _MAX_SQRT_PRICE, + SQRT_PRICE_DENOMINATOR as _SQRT_PRICE_DENOMINATOR, + FEE_GROWTH_DENOMINATOR as _FEE_GROWTH_DENOMINATOR, + LIQUIDITY_DENOMINATOR as _LIQUIDITY_DENOMINATOR, + TOKEN_AMOUNT_DENOMINATOR as _TOKEN_AMOUNT_DENOMINATOR, + PERCENTAGE_DENOMINATOR as _PERCENTAGE_DENOMINATOR, + FIXED_POINT_DENOMINATOR as _FIXED_POINT_DENOMINATOR, + SQRT_PRICE_SCALE +} from '../artifacts/ts/constants' +import { + FeeGrowth, + FixedPoint, + Liquidity, + Percentage, + Price, + SqrtPrice, + TokenAmount +} from './types' export * from '../artifacts/ts/constants' +export const MIN_SQRT_PRICE = _MIN_SQRT_PRICE as SqrtPrice +export const MAX_SQRT_PRICE = _MAX_SQRT_PRICE as SqrtPrice +export const SQRT_PRICE_DENOMINATOR = _SQRT_PRICE_DENOMINATOR as SqrtPrice +export const FEE_GROWTH_DENOMINATOR = _FEE_GROWTH_DENOMINATOR as FeeGrowth +export const LIQUIDITY_DENOMINATOR = _LIQUIDITY_DENOMINATOR as Liquidity +export const TOKEN_AMOUNT_DENOMINATOR = _TOKEN_AMOUNT_DENOMINATOR as TokenAmount +export const PERCENTAGE_DENOMINATOR = _PERCENTAGE_DENOMINATOR as Percentage +export const FIXED_POINT_DENOMINATOR = _FIXED_POINT_DENOMINATOR as FixedPoint + export const { SEARCH_RANGE, CHUNKS_PER_BATCH, HALF_CHUNK_SIZE, CHUNK_SIZE } = Invariant.consts export const { @@ -18,7 +46,7 @@ export const { } = CLAMM.consts export const PRICE_SCALE = SQRT_PRICE_SCALE -export const PRICE_DENOMINATOR = SQRT_PRICE_DENOMINATOR +export const PRICE_DENOMINATOR = _SQRT_PRICE_DENOMINATOR as Price export const MAX_BATCHES_QUERIED = 18n export const MAX_POOL_KEYS_QUERIED = 117n diff --git a/src/fungible-token.ts b/src/fungible-token.ts index e4780fd..731f52a 100644 --- a/src/fungible-token.ts +++ b/src/fungible-token.ts @@ -10,12 +10,13 @@ import { Network } from './network' import { TokenFaucet, Withdraw } from '../artifacts/ts' import { balanceOf, getNodeUrl, signAndSend, waitTxConfirmed } from './utils' import { MAX_U256 } from './consts' +import { TokenAmount } from './types' export type TokenMetaData = { symbol: string name: string decimals: bigint - totalSupply: bigint + totalSupply: TokenAmount } export class FungibleToken { @@ -32,7 +33,7 @@ export class FungibleToken { static async deploy( signer: SignerProvider, - supply: bigint = 0n, + supply = 0n as TokenAmount, name: string = '', symbol: string = '', decimals: bigint = 0n @@ -65,7 +66,7 @@ export class FungibleToken { return new FungibleToken(network) } - async mintTx(signer: SignerProvider, value: bigint, tokenId: string) { + async mintTx(signer: SignerProvider, value: TokenAmount, tokenId: string) { const tokenAddress = addressFromContractId(tokenId) const tokenFaucet = TokenFaucet.at(tokenAddress) const bytecode = Withdraw.script.buildByteCodeToDeploy({ @@ -82,7 +83,7 @@ export class FungibleToken { return unsignedTxBuild } - async mint(signer: SignerProvider, value: bigint, tokenId: string) { + async mint(signer: SignerProvider, value: TokenAmount, tokenId: string) { const tx = await this.mintTx(signer, value, tokenId) return await signAndSend(signer, tx) } @@ -109,7 +110,7 @@ export class FungibleToken { symbol: hexToString(metadata.symbol), name: hexToString(metadata.name), decimals: BigInt(metadata.decimals), - totalSupply: BigInt(metadata.totalSupply) + totalSupply: BigInt(metadata.totalSupply) as TokenAmount } } diff --git a/src/index.ts b/src/index.ts index 87e61c2..f92df85 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,6 +29,13 @@ export { } from './math' export type { + SqrtPrice, + Price, + FeeGrowth, + Liquidity, + TokenAmount, + Percentage, + FixedPoint, Pool, Position, FeeTier, diff --git a/src/invariant.ts b/src/invariant.ts index de3977d..70af5f9 100644 --- a/src/invariant.ts +++ b/src/invariant.ts @@ -21,13 +21,17 @@ import { decodePosition, decodeTick, FeeTier, + Liquidity, LiquidityTick, + Percentage, Pool, PoolKey, Position, QuoteResult, + SqrtPrice, Tick, Tickmap, + TokenAmount, unwrapFeeTier, unwrapPool, unwrapPoolKey, @@ -86,7 +90,7 @@ export class Invariant { static async deploy( signer: SignerProvider, network: Network, - protocolFee: bigint = 0n + protocolFee: Percentage = 0n as Percentage ): Promise { const account = await signer.getSelectedAccount() const clamm = await deployCLAMM(signer) @@ -153,7 +157,7 @@ export class Invariant { token0Id: string, token1Id: string, feeTier: FeeTier, - initSqrtPrice: bigint + initSqrtPrice: SqrtPrice ) { const initTick = await calculateTick(initSqrtPrice, feeTier.tickSpacing) const txBytecode = CreatePool.script.buildByteCodeToDeploy({ @@ -177,7 +181,7 @@ export class Invariant { token0Id: string, token1Id: string, feeTier: FeeTier, - initSqrtPrice: bigint + initSqrtPrice: SqrtPrice ): Promise { const tx = await this.createPoolTx(signer, token0Id, token1Id, feeTier, initSqrtPrice) return await signAndSend(signer, tx) @@ -246,11 +250,11 @@ export class Invariant { poolKey: PoolKey, lowerTick: bigint, upperTick: bigint, - liquidityDelta: bigint, - approvedTokensX: bigint, - approvedTokensY: bigint, - slippageLimitLower: bigint, - slippageLimitUpper: bigint + liquidityDelta: Liquidity, + approvedTokensX: TokenAmount, + approvedTokensY: TokenAmount, + slippageLimitLower: SqrtPrice, + slippageLimitUpper: SqrtPrice ) { const txBytecode = CreatePosition.script.buildByteCodeToDeploy({ invariant: this.instance.contractId, @@ -289,11 +293,11 @@ export class Invariant { poolKey: PoolKey, lowerTick: bigint, upperTick: bigint, - liquidityDelta: bigint, - approvedTokensX: bigint, - approvedTokensY: bigint, - slippageLimitLower: bigint, - slippageLimitUpper: bigint + liquidityDelta: Liquidity, + approvedTokensX: TokenAmount, + approvedTokensY: TokenAmount, + slippageLimitLower: SqrtPrice, + slippageLimitUpper: SqrtPrice ): Promise { const tx = await this.createPositionTx( signer, @@ -371,9 +375,9 @@ export class Invariant { signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint, + sqrtPriceLimit: SqrtPrice, approvedAmount = amount ) { const tokenId = xToY ? poolKey.tokenX : poolKey.tokenY @@ -402,9 +406,9 @@ export class Invariant { signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint, + sqrtPriceLimit: SqrtPrice, approvedAmount = amount ): Promise { const tx = await this.swapTx( @@ -423,10 +427,10 @@ export class Invariant { signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - estimatedSqrtPrice: bigint, - slippage: bigint + estimatedSqrtPrice: SqrtPrice, + slippage: Percentage ) { const sqrtPriceAfterSlippage = calculateSqrtPriceAfterSlippage( estimatedSqrtPrice, @@ -440,7 +444,7 @@ export class Invariant { xToY, amount, byAmountIn, - xToY ? sqrtPriceAfterSlippage - 1n : sqrtPriceAfterSlippage + 1n + (xToY ? sqrtPriceAfterSlippage - 1n : sqrtPriceAfterSlippage + 1n) as SqrtPrice ) } @@ -448,10 +452,10 @@ export class Invariant { signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - estimatedSqrtPrice: bigint, - slippage: bigint + estimatedSqrtPrice: SqrtPrice, + slippage: Percentage ): Promise { const tx = await this.swapWithSlippageTx( signer, diff --git a/src/math.ts b/src/math.ts index 18dbf0e..1bbd784 100644 --- a/src/math.ts +++ b/src/math.ts @@ -5,6 +5,7 @@ import { LIQUIDITY_SCALE, PERCENTAGE_DENOMINATOR, PERCENTAGE_SCALE, + PRICE_SCALE, SQRT_PRICE_DENOMINATOR, SQRT_PRICE_SCALE } from './consts' @@ -15,22 +16,29 @@ import { LiquidityResult, unwrapLiquidityResult, SingleTokenLiquidity, - unwrapSingleTokenLiquidity + unwrapSingleTokenLiquidity, + FixedPoint, + TokenAmount, + FeeGrowth, + Percentage, + SqrtPrice, + Liquidity, + Price } from './types' -export const calculateSqrtPrice = async (tickIndex: bigint): Promise => { +export const calculateSqrtPrice = async (tickIndex: bigint): Promise => { return ( await Utils.tests.calculateSqrtPrice({ testArgs: { tickIndex } }) - ).returns.v + ).returns.v as SqrtPrice } export const getLiquidityByX = async ( - x: bigint, + x: TokenAmount, lowerTick: bigint, upperTick: bigint, - currentSqrtPrice: bigint, + currentSqrtPrice: SqrtPrice, roundingUp: boolean ): Promise => { return unwrapSingleTokenLiquidity( @@ -49,10 +57,10 @@ export const getLiquidityByX = async ( } export const getLiquidityByY = async ( - y: bigint, + y: TokenAmount, lowerTick: bigint, upperTick: bigint, - currentSqrtPrice: bigint, + currentSqrtPrice: SqrtPrice, roundingUp: boolean ): Promise => { return unwrapSingleTokenLiquidity( @@ -71,11 +79,11 @@ export const getLiquidityByY = async ( } export const getLiquidity = async ( - x: bigint, - y: bigint, + x: TokenAmount, + y: TokenAmount, lowerTick: bigint, upperTick: bigint, - currentSqrtPrice: bigint, + currentSqrtPrice: SqrtPrice, roundingUp: boolean ): Promise => { return unwrapLiquidityResult( @@ -95,11 +103,11 @@ export const getLiquidity = async ( } export const getDeltaY = async ( - sqrtPriceA: bigint, - sqrtPriceB: bigint, - liquidity: bigint, + sqrtPriceA: SqrtPrice, + sqrtPriceB: SqrtPrice, + liquidity: Liquidity, roundingUp: boolean -): Promise => { +): Promise => { return ( await CLAMM.tests.getDeltaY({ testArgs: { @@ -109,7 +117,7 @@ export const getDeltaY = async ( roundingUp } }) - ).returns.v + ).returns.v as TokenAmount } export const getMaxTick = async (tickSpacing: bigint): Promise => { @@ -142,7 +150,7 @@ export const getMaxChunk = async (tickSpacing: bigint): Promise => { ).returns } -export const calculateTick = async (sqrtPrice: bigint, tickSpacing: bigint): Promise => { +export const calculateTick = async (sqrtPrice: SqrtPrice, tickSpacing: bigint): Promise => { return ( await Utils.tests.getTickAtSqrtPrice({ testArgs: { @@ -153,24 +161,24 @@ export const calculateTick = async (sqrtPrice: bigint, tickSpacing: bigint): Pro ).returns } -export const getMaxSqrtPrice = async (tickSpacing: bigint): Promise => { +export const getMaxSqrtPrice = async (tickSpacing: bigint): Promise => { return ( await Utils.tests.getMaxSqrtPrice({ testArgs: { tickSpacing } }) - ).returns.v + ).returns.v as SqrtPrice } -export const getMinSqrtPrice = async (tickSpacing: bigint): Promise => { +export const getMinSqrtPrice = async (tickSpacing: bigint): Promise => { return ( await Utils.tests.getMinSqrtPrice({ testArgs: { tickSpacing } }) - ).returns.v + ).returns.v as SqrtPrice } export const isTokenX = async (candidate: string, compareTo: string): Promise => { @@ -184,7 +192,10 @@ export const isTokenX = async (candidate: string, compareTo: string): Promise { +export async function getTickAtSqrtPrice( + sqrtPrice: SqrtPrice, + tickSpacing: bigint +): Promise { return ( await CLAMM.tests.getTickAtSqrtPrice({ testArgs: { sqrtPrice: { v: sqrtPrice }, tickSpacing } @@ -207,7 +218,7 @@ export const calculateFee = async ( position: Position, lowerTick: Tick, upperTick: Tick -): Promise<[bigint, bigint]> => { +): Promise<[TokenAmount, TokenAmount]> => { const [{ v: tokensOwedX }, { v: tokensOwedY }] = ( await Utils.tests.calculateFee({ testArgs: { @@ -227,13 +238,13 @@ export const calculateFee = async ( }) ).returns - return [tokensOwedX, tokensOwedY] + return [tokensOwedX as TokenAmount, tokensOwedY as TokenAmount] } export const calculateTokenAmounts = async ( pool: Pool, position: Position -): Promise<[bigint, bigint, boolean]> => { +): Promise<[TokenAmount, TokenAmount, boolean]> => { const [{ v: amountX }, { v: amountY }, updateLiquidity] = ( await CLAMM.tests.calculateAmountDelta({ testArgs: { @@ -246,7 +257,7 @@ export const calculateTokenAmounts = async ( } }) ).returns - return [amountX, amountY, updateLiquidity] + return [amountX as TokenAmount, amountY as TokenAmount, updateLiquidity] } export const bitPositionToTick = async ( @@ -284,35 +295,35 @@ const newtonIteration = (n: bigint, x0: bigint): bigint => { return newtonIteration(n, x1) } -export const sqrtPriceToPrice = (sqrtPrice: bigint): bigint => { - return (sqrtPrice * sqrtPrice) / SQRT_PRICE_DENOMINATOR +export const sqrtPriceToPrice = (sqrtPrice: SqrtPrice): Price => { + return ((sqrtPrice * sqrtPrice) / SQRT_PRICE_DENOMINATOR) as Price } -export const priceToSqrtPrice = (price: bigint): bigint => { - return sqrt(price * SQRT_PRICE_DENOMINATOR) +export const priceToSqrtPrice = (price: Price): SqrtPrice => { + return sqrt(price * SQRT_PRICE_DENOMINATOR) as SqrtPrice } export const calculateSqrtPriceAfterSlippage = ( - sqrtPrice: bigint, - slippage: bigint, + sqrtPrice: SqrtPrice, + slippage: Percentage, up: boolean -): bigint => { +): SqrtPrice => { if (slippage === 0n) { return sqrtPrice } const multiplier = PERCENTAGE_DENOMINATOR + (up ? slippage : -slippage) const price = sqrtPriceToPrice(sqrtPrice) - const priceWithSlippage = price * multiplier * PERCENTAGE_DENOMINATOR + const priceWithSlippage = (price * multiplier * PERCENTAGE_DENOMINATOR) as Price const sqrtPriceWithSlippage = priceToSqrtPrice(priceWithSlippage) / PERCENTAGE_DENOMINATOR - return sqrtPriceWithSlippage + return sqrtPriceWithSlippage as SqrtPrice } export const calculatePriceImpact = ( - startingSqrtPrice: bigint, - endingSqrtPrice: bigint -): bigint => { + startingSqrtPrice: SqrtPrice, + endingSqrtPrice: SqrtPrice +): Percentage => { const startingPrice = startingSqrtPrice * startingSqrtPrice const endingPrice = endingSqrtPrice * endingSqrtPrice const diff = startingPrice - endingPrice @@ -320,42 +331,45 @@ export const calculatePriceImpact = ( const nominator = diff > 0n ? diff : -diff const denominator = startingPrice > endingPrice ? startingPrice : endingPrice - return (nominator * PERCENTAGE_DENOMINATOR) / denominator + return ((nominator * PERCENTAGE_DENOMINATOR) / denominator) as Percentage } -export const toLiquidity = (value: bigint, offset = 0n) => { +export const toLiquidity = (value: bigint, offset = 0n): Liquidity => { if (offset > LIQUIDITY_SCALE) throw new Error(`offset must be less than or equal to ${LIQUIDITY_SCALE}`) - return value * 10n ** (LIQUIDITY_SCALE - offset) + return (value * 10n ** (LIQUIDITY_SCALE - offset)) as Liquidity } -export const toSqrtPrice = (value: bigint, offset = 0n): bigint => { +export const toSqrtPrice = (value: bigint, offset = 0n): SqrtPrice => { if (offset > SQRT_PRICE_SCALE) throw new Error(`offset must be less than or equal to ${SQRT_PRICE_SCALE}`) - return value * 10n ** (SQRT_PRICE_SCALE - offset) + return (value * 10n ** (SQRT_PRICE_SCALE - offset)) as SqrtPrice } -export const toPrice = toSqrtPrice +export const toPrice = (value: bigint, offset = 0n): Price => { + if (offset > PRICE_SCALE) throw new Error(`offset must be less than or equal to ${PRICE_SCALE}`) + return (value * 10n ** (PRICE_SCALE - offset)) as Price +} -export const toPercentage = (value: bigint, offset = 0n): bigint => { +export const toPercentage = (value: bigint, offset = 0n): Percentage => { if (offset > PERCENTAGE_SCALE) throw new Error(`offset must be less than or equal to ${PERCENTAGE_SCALE}`) - return value * 10n ** (PERCENTAGE_SCALE - offset) + return (value * 10n ** (PERCENTAGE_SCALE - offset)) as Percentage } -export const toFeeGrowth = (value: bigint, offset = 0n): bigint => { +export const toFeeGrowth = (value: bigint, offset = 0n): FeeGrowth => { if (offset > FEE_GROWTH_SCALE) throw new Error(`offset must be less than or equal to ${FEE_GROWTH_SCALE}`) - return value * 10n ** (FEE_GROWTH_SCALE - offset) + return (value * 10n ** (FEE_GROWTH_SCALE - offset)) as FeeGrowth } -export const toTokenAmount = (value: bigint, decimals: bigint, offset = 0n): bigint => { +export const toTokenAmount = (value: bigint, decimals: bigint, offset = 0n): TokenAmount => { if (offset > decimals) throw new Error(`offset must be less than or equal to ${decimals}`) - return value * 10n ** (decimals - offset) + return (value * 10n ** (decimals - offset)) as TokenAmount } -export const toFixedPoint = (value: bigint, offset = 0n): bigint => { +export const toFixedPoint = (value: bigint, offset = 0n): FixedPoint => { if (offset > FIXED_POINT_SCALE) throw new Error(`offset must be less than or equal to ${FIXED_POINT_SCALE}`) - return value * 10n ** (FIXED_POINT_SCALE - offset) + return (value * 10n ** (FIXED_POINT_SCALE - offset)) as FixedPoint } diff --git a/src/simulate-swap.ts b/src/simulate-swap.ts index aa427f5..096a256 100644 --- a/src/simulate-swap.ts +++ b/src/simulate-swap.ts @@ -29,16 +29,27 @@ import { TOKEN_AMOUNT_DENOMINATOR, TOKEN_AMOUNT_SCALE } from './consts' -import { Pool, SimulateSwapResult, SwapResult, Tickmap, TickVariant } from './types' +import { + FixedPoint, + Liquidity, + Percentage, + Pool, + SimulateSwapResult, + SqrtPrice, + SwapResult, + Tickmap, + TickVariant, + TokenAmount +} from './types' export const simulateSwap = ( tickmap: Tickmap, pool: Pool, ticks: TickVariant[], xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint + sqrtPriceLimit: SqrtPrice ): SimulateSwapResult => { const feeTier = pool.poolKey.feeTier @@ -67,10 +78,10 @@ export const simulateSwap = ( let ticksCrossed: Array = [] let swapSteps = 0 - let totalAmountIn = 0n - let totalAmountOut = 0n - let eventFeeAmount = 0n - let remainingAmount: bigint = amount + let totalAmountIn = 0n as TokenAmount + let totalAmountOut = 0n as TokenAmount + let eventFeeAmount = 0n as TokenAmount + let remainingAmount: TokenAmount = amount const eventStartSqrtPrice = sqrtPrice while (remainingAmount != 0n) { @@ -101,17 +112,18 @@ export const simulateSwap = ( swapSteps += 1 if (byAmountIn) { - remainingAmount -= swapResult.amountIn + swapResult.feeAmount + remainingAmount = (remainingAmount - + (swapResult.amountIn + swapResult.feeAmount)) as TokenAmount } else { - remainingAmount -= swapResult.amountOut + remainingAmount = (remainingAmount - swapResult.amountOut) as TokenAmount } // pool = await AddFee(pool, swapResult.feeAmount, xToY, protocolFee) pool.sqrtPrice = swapResult.nextSqrtPrice - totalAmountIn += swapResult.amountIn + swapResult.feeAmount - totalAmountOut += swapResult.amountOut - eventFeeAmount += swapResult.feeAmount + totalAmountIn = (totalAmountIn + swapResult.amountIn + swapResult.feeAmount) as TokenAmount + totalAmountOut = (totalAmountOut + swapResult.amountOut) as TokenAmount + eventFeeAmount = (eventFeeAmount + swapResult.feeAmount) as TokenAmount // fail if price would go over swap limit if (swapResult.nextSqrtPrice === sqrtPriceLimit && remainingAmount != 0n) { @@ -149,7 +161,7 @@ export const simulateSwap = ( } remainingAmount = poolUpdateTickResult.amountAfterTickUpdate - totalAmountIn += poolUpdateTickResult.amountToAdd + totalAmountIn = (totalAmountIn + poolUpdateTickResult.amountToAdd) as TokenAmount if (poolUpdateTickResult.hasCrossed && tick) { ticksCrossed.push(tick) @@ -188,7 +200,7 @@ export const simulateSwap = ( } type getCloserLimitResult = { - swapLimit: bigint + swapLimit: SqrtPrice hasLimitingTick: boolean limitingTickIndex: bigint isInitialized: boolean @@ -196,7 +208,7 @@ type getCloserLimitResult = { } const getCloserLimit = ( - sqrtPriceLimit: bigint, + sqrtPriceLimit: SqrtPrice, xToY: boolean, currentTickIndex: bigint, tickSpacing: bigint, @@ -412,30 +424,31 @@ const getSearchLimit = (tick: bigint, tickSpacing: bigint, up: boolean): bigint } const computeSwapStep = ( - currentSqrtPrice: bigint, - targetSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + currentSqrtPrice: SqrtPrice, + targetSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, byAmountIn: boolean, - fee: bigint + fee: Percentage ): SwapResult => { if (liquidity === 0n) { return { nextSqrtPrice: targetSqrtPrice, - amountIn: 0n, - amountOut: 0n, - feeAmount: 0n + amountIn: 0n as TokenAmount, + amountOut: 0n as TokenAmount, + feeAmount: 0n as TokenAmount } } const xToY = currentSqrtPrice >= targetSqrtPrice - let nextSqrtPrice: bigint - let amountIn = 0n - let amountOut = 0n + let nextSqrtPrice: SqrtPrice + let amountIn = 0n as TokenAmount + let amountOut = 0n as TokenAmount if (byAmountIn) { - const amountAfterFee = (amount * (PERCENTAGE_DENOMINATOR - fee)) / PERCENTAGE_DENOMINATOR + const amountAfterFee = ((amount * (PERCENTAGE_DENOMINATOR - fee)) / + PERCENTAGE_DENOMINATOR) as TokenAmount amountIn = xToY ? getDeltaX(targetSqrtPrice, currentSqrtPrice, liquidity, true) : getDeltaY(currentSqrtPrice, targetSqrtPrice, liquidity, true) @@ -476,11 +489,12 @@ const computeSwapStep = ( amountOut = amount } - let feeAmount: bigint + let feeAmount: TokenAmount if (byAmountIn && nextSqrtPrice !== targetSqrtPrice) { - feeAmount = amount - amountIn + feeAmount = (amount - amountIn) as TokenAmount } else { - feeAmount = (PERCENTAGE_DENOMINATOR - 1n + amountIn * fee) / PERCENTAGE_DENOMINATOR + feeAmount = ((PERCENTAGE_DENOMINATOR - 1n + amountIn * fee) / + PERCENTAGE_DENOMINATOR) as TokenAmount } return { @@ -492,11 +506,11 @@ const computeSwapStep = ( } const getDeltaX = ( - sqrtPriceA: bigint, - sqrtPriceB: bigint, - liquidity: bigint, + sqrtPriceA: SqrtPrice, + sqrtPriceB: SqrtPrice, + liquidity: Liquidity, roundingUp: boolean -): bigint => { +): TokenAmount => { const deltaSqrtPrice = sqrtPriceA > sqrtPriceB ? sqrtPriceA - sqrtPriceB : sqrtPriceB - sqrtPriceA const nominator = mulDiv(deltaSqrtPrice, liquidity, LIQUIDITY_DENOMINATOR) @@ -510,31 +524,31 @@ const getDeltaX = ( } const getDeltaY = ( - sqrtPriceA: bigint, - sqrtPriceB: bigint, - liquidity: bigint, + sqrtPriceA: SqrtPrice, + sqrtPriceB: SqrtPrice, + liquidity: Liquidity, roundingUp: boolean -): bigint => { +): TokenAmount => { const deltaSqrtPrice = sqrtPriceA > sqrtPriceB ? sqrtPriceA - sqrtPriceB : sqrtPriceB - sqrtPriceA let result: bigint if (roundingUp) { result = mulDiv(deltaSqrtPrice, liquidity, LIQUIDITY_DENOMINATOR) result = divUp(result, SQRT_PRICE_DENOMINATOR, 1n) - return result + return result as TokenAmount } else { result = mulDiv(deltaSqrtPrice, liquidity, LIQUIDITY_DENOMINATOR) result = div(result, SQRT_PRICE_DENOMINATOR, 1n) - return result + return result as TokenAmount } } const getNextSqrtPriceFromInput = ( - startingSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, xToY: boolean -): bigint => { +): SqrtPrice => { if (xToY) { return getNextSqrtPriceXUp(startingSqrtPrice, liquidity, amount, true) } else { @@ -543,11 +557,11 @@ const getNextSqrtPriceFromInput = ( } const getNextSqrtPriceFromOutput = ( - startingSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, xToY: boolean -): bigint => { +): SqrtPrice => { if (xToY) { return getNextSqrtPriceYDown(startingSqrtPrice, liquidity, amount, false) } else { @@ -556,11 +570,11 @@ const getNextSqrtPriceFromOutput = ( } const getNextSqrtPriceXUp = ( - startingSqrtPrice: bigint, - liquidity: bigint, - x: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + x: TokenAmount, addX: Boolean -): bigint => { +): SqrtPrice => { if (x === 0n) { return startingSqrtPrice } @@ -576,28 +590,28 @@ const getNextSqrtPriceXUp = ( const nominator = mulDivUp(startingSqrtPrice, liquidity, LIQUIDITY_DENOMINATOR) - return divUp(nominator, denominator, SQRT_PRICE_DENOMINATOR) + return divUp(nominator, denominator, SQRT_PRICE_DENOMINATOR) as SqrtPrice } const getNextSqrtPriceYDown = ( - startingSqrtPrice: bigint, - liquidity: bigint, - y: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + y: TokenAmount, addY: Boolean -): bigint => { +): SqrtPrice => { const numerator = rescale(y, TOKEN_AMOUNT_SCALE, SQRT_PRICE_SCALE) const denominator = rescale(liquidity, LIQUIDITY_SCALE, SQRT_PRICE_SCALE) if (addY) { - return startingSqrtPrice + div(numerator, denominator, SQRT_PRICE_DENOMINATOR) + return (startingSqrtPrice + div(numerator, denominator, SQRT_PRICE_DENOMINATOR)) as SqrtPrice } else { - return startingSqrtPrice - divUp(numerator, denominator, SQRT_PRICE_DENOMINATOR) + return (startingSqrtPrice - divUp(numerator, denominator, SQRT_PRICE_DENOMINATOR)) as SqrtPrice } } type poolUpdateTickResult = { - amountToAdd: bigint - amountAfterTickUpdate: bigint + amountToAdd: TokenAmount + amountAfterTickUpdate: TokenAmount hasCrossed: boolean stateInconsistency: boolean } @@ -606,9 +620,9 @@ type poolUpdateTickResult = { const poolUpdateTick = ( pool: Pool, tick: TickVariant | undefined, - nextSqrtPrice: bigint, - swapLimit: bigint, - remainingAmount: bigint, + nextSqrtPrice: SqrtPrice, + swapLimit: SqrtPrice, + remainingAmount: TokenAmount, byAmountIn: boolean, xToY: boolean, hasLimitingTick: boolean, @@ -617,7 +631,7 @@ const poolUpdateTick = ( ): poolUpdateTickResult => { let hasCrossed = false let stateInconsistency = false - let totalAmount = 0n + let totalAmount = 0n as TokenAmount // if there's no tick we do not have to check for initialization if (!tick || swapLimit !== nextSqrtPrice) { @@ -653,7 +667,7 @@ const poolUpdateTick = ( // await poolAddFee(pool, remainingAmount, xToY, protocolFee) totalAmount = remainingAmount } - remainingAmount = 0n + remainingAmount = 0n as TokenAmount } } } @@ -673,10 +687,10 @@ const poolUpdateTick = ( } const isEnoughAmountToChangePrice = ( - amount: bigint, - startingSqrtPrice: bigint, - liquidity: bigint, - fee: bigint, + amount: TokenAmount, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + fee: Percentage, byAmountIn: boolean, xToY: boolean ): boolean => { @@ -684,9 +698,13 @@ const isEnoughAmountToChangePrice = ( return true } - let nextSqrtPrice: bigint + let nextSqrtPrice: SqrtPrice if (byAmountIn) { - const amountAfterFee = mulDiv(amount, PERCENTAGE_DENOMINATOR - fee, PERCENTAGE_DENOMINATOR) + const amountAfterFee = mulDiv( + amount, + PERCENTAGE_DENOMINATOR - fee, + PERCENTAGE_DENOMINATOR + ) as TokenAmount nextSqrtPrice = getNextSqrtPriceFromInput(startingSqrtPrice, liquidity, amountAfterFee, xToY) } else { nextSqrtPrice = getNextSqrtPriceFromOutput(startingSqrtPrice, liquidity, amount, xToY) @@ -695,89 +713,89 @@ const isEnoughAmountToChangePrice = ( return startingSqrtPrice !== nextSqrtPrice } -const cross = (tick: TickVariant, currentTick: bigint): [boolean, bigint] => { +const cross = (tick: TickVariant, currentTick: bigint): [boolean, Liquidity] => { const isBelowCurrent = currentTick >= tick.index return [(isBelowCurrent && !tick.sign) || (!isBelowCurrent && tick.sign), tick.liquidityChange] } -const poolCrossLiquidityUpdate = (pool: Pool, add: boolean, liquidityDelta: bigint) => { +const poolCrossLiquidityUpdate = (pool: Pool, add: boolean, liquidityDelta: Liquidity) => { if (add) { - pool.liquidity += liquidityDelta + pool.liquidity = (pool.liquidity + liquidityDelta) as Liquidity } else { - pool.liquidity -= liquidityDelta + pool.liquidity = (pool.liquidity - liquidityDelta) as Liquidity } } -const calculateSqrtPrice = (tickIndex: bigint): bigint => { +const calculateSqrtPrice = (tickIndex: bigint): SqrtPrice => { const tickIndexAbs = tickIndex < 0n ? -tickIndex : tickIndex - let sqrtPrice = FIXED_POINT_DENOMINATOR + let sqrtPrice = FIXED_POINT_DENOMINATOR as FixedPoint if (tickIndexAbs > GLOBAL_MAX_TICK) { throw new Error(String(DecimalError.TickOverBounds)) } if (tickIndexAbs & 0x1n) { - sqrtPrice = (sqrtPrice * 1000049998750n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1000049998750n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x2n) { - sqrtPrice = (sqrtPrice * 1000100000000n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1000100000000n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x4n) { - sqrtPrice = (sqrtPrice * 1000200010000n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1000200010000n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x8n) { - sqrtPrice = (sqrtPrice * 1000400060004n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1000400060004n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x10n) { - sqrtPrice = (sqrtPrice * 1000800280056n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1000800280056n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x20n) { - sqrtPrice = (sqrtPrice * 1001601200560n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1001601200560n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x40n) { - sqrtPrice = (sqrtPrice * 1003204964963n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1003204964963n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x80n) { - sqrtPrice = (sqrtPrice * 1006420201726n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1006420201726n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x100n) { - sqrtPrice = (sqrtPrice * 1012881622442n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1012881622442n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x200n) { - sqrtPrice = (sqrtPrice * 1025929181080n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1025929181080n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x400n) { - sqrtPrice = (sqrtPrice * 1052530684591n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1052530684591n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x800n) { - sqrtPrice = (sqrtPrice * 1107820842005n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1107820842005n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x1000n) { - sqrtPrice = (sqrtPrice * 1227267017980n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1227267017980n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x2000n) { - sqrtPrice = (sqrtPrice * 1506184333421n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 1506184333421n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x4000n) { - sqrtPrice = (sqrtPrice * 2268591246242n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 2268591246242n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x8000n) { - sqrtPrice = (sqrtPrice * 5146506242525n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 5146506242525n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x00010000n) { - sqrtPrice = (sqrtPrice * 26486526504348n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 26486526504348n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndexAbs & 0x00020000n) { - sqrtPrice = (sqrtPrice * 701536086265529n) / FIXED_POINT_DENOMINATOR + sqrtPrice = ((sqrtPrice * 701536086265529n) / FIXED_POINT_DENOMINATOR) as FixedPoint } if (tickIndex >= 0n) { - return rescale(sqrtPrice, FIXED_POINT_SCALE, SQRT_PRICE_SCALE) + return rescale(sqrtPrice, FIXED_POINT_SCALE, SQRT_PRICE_SCALE) as SqrtPrice } else { let sqrtPriceInFixedPointScale = (FIXED_POINT_DENOMINATOR * FIXED_POINT_DENOMINATOR) / sqrtPrice - return rescale(sqrtPriceInFixedPointScale, FIXED_POINT_SCALE, SQRT_PRICE_SCALE) + return rescale(sqrtPriceInFixedPointScale, FIXED_POINT_SCALE, SQRT_PRICE_SCALE) as SqrtPrice } } @@ -791,20 +809,20 @@ const rescale = (fromValue: bigint, fromScale: bigint, expectedScale: bigint): b } } -const divToTokenUp = (a: bigint, b: bigint): bigint => { +const divToTokenUp = (a: bigint, b: bigint): TokenAmount => { let result = a * SQRT_PRICE_DENOMINATOR result += b - 1n result /= b result += SQRT_PRICE_DENOMINATOR - 1n result /= SQRT_PRICE_DENOMINATOR - return result + return result as TokenAmount } -const divToToken = (a: bigint, b: bigint): bigint => { +const divToToken = (a: bigint, b: bigint): TokenAmount => { let result = a * SQRT_PRICE_DENOMINATOR result /= b result /= SQRT_PRICE_DENOMINATOR - return result + return result as TokenAmount } const mulDiv = (a: bigint, b: bigint, bDenominator: bigint): bigint => { diff --git a/src/snippets.ts b/src/snippets.ts index fa68afb..aa08422 100644 --- a/src/snippets.ts +++ b/src/snippets.ts @@ -12,28 +12,27 @@ import { transferPosition, verifyPositionList, withdrawTokens, - quote + quote, + TokenInstance } from './testUtils' import { balanceOf, deployInvariant, newFeeTier, newPoolKey } from './utils' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { calculateSqrtPrice, toLiquidity, toPercentage } from './math' -import { PoolKey, Position } from './types' - -type TokenInstance = TokenFaucetInstance +import { Percentage, PoolKey, Position, TokenAmount } from './types' // 0.6% fee -const fee = 6n * 10n ** (PERCENTAGE_SCALE - 3n) +const fee = (6n * 10n ** (PERCENTAGE_SCALE - 3n)) as Percentage const tickSpacing = 10n -export const getBasicFeeTickSpacing = (): [bigint, bigint] => { +export const getBasicFeeTickSpacing = (): [Percentage, bigint] => { return [fee, tickSpacing] } /** Tokens are already ordered. */ export const initDexAndTokens = async ( admin: SignerProvider, - supply = 1000000n -): Promise<[InvariantInstance, TokenFaucetInstance, TokenFaucetInstance]> => { + supply = 1000000n as TokenAmount +): Promise<[InvariantInstance, TokenInstance, TokenInstance]> => { // 1% const protocolFee = toPercentage(1n, 2n) const invariant = await deployInvariant(admin, protocolFee) @@ -64,7 +63,7 @@ export const initBasicPosition = async ( tokenX: TokenInstance, tokenY: TokenInstance ) => { - const withdrawAmount = 1000n + const withdrawAmount = 1000n as TokenAmount await withdrawTokens(positionOwner, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) const feeTier = await newFeeTier(fee, tickSpacing) @@ -103,7 +102,7 @@ export const initBasicSwap = async ( const poolBefore = await getPool(invariant, poolKey) - const swapAmount = 1000n + const swapAmount = 1000n as TokenAmount await withdrawTokens(swapper, [tokenX, swapAmount]) const swapperTokenXBalanceBefore = await balanceOf(tokenX.contractId, swapper.address) @@ -142,10 +141,10 @@ export const swapExactLimit = async ( signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean ) => { - const sqrtPriceLimit: bigint = xToY ? MIN_SQRT_PRICE : MAX_SQRT_PRICE + const sqrtPriceLimit = xToY ? MIN_SQRT_PRICE : MAX_SQRT_PRICE const quoteResult = await quote(invariant, poolKey, xToY, amount, byAmountIn, sqrtPriceLimit) await initSwap(invariant, signer, poolKey, xToY, amount, byAmountIn, quoteResult.targetSqrtPrice) diff --git a/src/testUtils.ts b/src/testUtils.ts index bd84fc9..9830fd3 100644 --- a/src/testUtils.ts +++ b/src/testUtils.ts @@ -31,11 +31,17 @@ import { decodePool, decodePosition, decodeTick, + FeeGrowth, FeeTier, + Liquidity, + Percentage, Pool, PoolKey, Position, + SqrtPrice, + SwapResult, Tick, + TokenAmount, unwrapFeeTier, unwrapPool, unwrapPosition, @@ -44,9 +50,8 @@ import { wrapFeeTier, wrapPoolKey } from './types' -import { wrap } from 'module' -type TokenInstance = TokenFaucetInstance +export type TokenInstance = TokenFaucetInstance export async function expectError( errorCode: bigint, @@ -83,7 +88,7 @@ export async function expectVMError(error: VMError, script: Promise) { expect(isError).toBeTruthy() } -export async function initTokensXY(signer: SignerProvider, supply: bigint) { +export async function initTokensXY(signer: SignerProvider, supply: TokenAmount) { const token0 = TokenFaucet.at( (await deployTokenFaucet(signer, '', '', supply, supply)).contractInstance.address ) @@ -141,7 +146,7 @@ export async function initPool( token0: TokenInstance, token1: TokenInstance, feeTier: FeeTier, - initSqrtPrice: bigint, + initSqrtPrice: SqrtPrice, initTick: bigint ) { return await CreatePool.execute(signer, { @@ -173,7 +178,7 @@ export const withdrawProtocolFee = async ( export async function withdrawTokens( signer: SignerProvider, - ...tokens: [token: TokenInstance, amount: bigint][] + ...tokens: [token: TokenInstance, amount: TokenAmount][] ) { for (const [tokenN, amountN] of tokens) { await Withdraw.execute(signer, { @@ -238,7 +243,7 @@ export async function getPositionWithAssociates( export const changeProtocolFee = async ( invariant: InvariantInstance, signer: SignerProvider, - newFee: bigint + newFee: Percentage ) => { return await ChangeProtocolFee.execute(signer, { initialFields: { @@ -256,13 +261,13 @@ export async function initPosition( invariant: InvariantInstance, signer: PrivateKeyWallet, poolKey: PoolKey, - approvedTokensX: bigint, - approvedTokensY: bigint, + approvedTokensX: TokenAmount, + approvedTokensY: TokenAmount, lowerTick: bigint, upperTick: bigint, - liquidityDelta: bigint, - slippageLimitLower: bigint, - slippageLimitUpper: bigint + liquidityDelta: Liquidity, + slippageLimitLower: SqrtPrice, + slippageLimitUpper: SqrtPrice ) { return await CreatePosition.execute(signer, { initialFields: { @@ -286,9 +291,9 @@ export const quote = async ( invariant: InvariantInstance, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint + sqrtPriceLimit: SqrtPrice ) => { return unwrapQuoteResult( ( @@ -356,9 +361,9 @@ export async function initSwap( signer: SignerProvider, poolKey: PoolKey, xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint, + sqrtPriceLimit: SqrtPrice, approvedAmount = amount ) { const id = xToY ? poolKey.tokenX : poolKey.tokenY @@ -437,40 +442,40 @@ export const getReserveBalances = async (invariant: InvariantInstance, poolKey: export const feeGrowthFromFee = async ( clamm: CLAMMInstance, - liquidity: bigint, - fee: bigint -): Promise => { + liquidity: Liquidity, + fee: TokenAmount +): Promise => { return ( await clamm.view.feeGrowthFromFee({ args: { liquidity: { v: liquidity }, fee: { v: fee } } }) - ).returns.v + ).returns.v as FeeGrowth } export const calculateSqrtPrice = async ( clamm: CLAMMInstance | InvariantInstance, tickIndex: bigint -): Promise => { +): Promise => { return ( await clamm.view.calculateSqrtPrice({ args: { tickIndex } }) - ).returns.v + ).returns.v as SqrtPrice } export const toFee = async ( clamm: CLAMMInstance, - liquidity: bigint, - feeGrowth: bigint -): Promise => { + liquidity: Liquidity, + feeGrowth: FeeGrowth +): Promise => { return ( await clamm.view.toFee({ args: { liquidity: { v: liquidity }, feeGrowth: { v: feeGrowth } } }) - ).returns.v + ).returns.v as TokenAmount } export const getTickAtSqrtPrice = async ( clamm: CLAMMInstance, - sqrtPrice: bigint, + sqrtPrice: SqrtPrice, tickSpacing: bigint ): Promise => { return ( @@ -482,11 +487,11 @@ export const getTickAtSqrtPrice = async ( export const getDeltaX = async ( clamm: CLAMMInstance, - sqrtPriceA: bigint, - sqrtPriceB: bigint, - liquidity: bigint, + sqrtPriceA: SqrtPrice, + sqrtPriceB: SqrtPrice, + liquidity: Liquidity, roundingUp: boolean -): Promise => { +): Promise => { return ( await clamm.view.getDeltaX({ args: { @@ -496,16 +501,16 @@ export const getDeltaX = async ( roundingUp } }) - ).returns.v + ).returns.v as TokenAmount } export const getDeltaY = async ( clamm: CLAMMInstance, - sqrtPriceA: bigint, - sqrtPriceB: bigint, - liquidity: bigint, + sqrtPriceA: SqrtPrice, + sqrtPriceB: SqrtPrice, + liquidity: Liquidity, roundingUp: boolean -): Promise => { +): Promise => { return ( await clamm.view.getDeltaY({ args: { @@ -515,16 +520,16 @@ export const getDeltaY = async ( roundingUp } }) - ).returns.v + ).returns.v as TokenAmount } export const getNextSqrtPriceYDown = async ( clamm: CLAMMInstance, - startingSqrtPrice: bigint, - liquidity: bigint, - y: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + y: TokenAmount, addY: boolean -): Promise => { +): Promise => { return ( await clamm.view.getNextSqrtPriceYDown({ args: { @@ -534,27 +539,27 @@ export const getNextSqrtPriceYDown = async ( addY } }) - ).returns.v + ).returns.v as SqrtPrice } export const calculateMinAmountOut = async ( clamm: CLAMMInstance, - expectedAmountOut: bigint, - slippage: bigint -): Promise => { + expectedAmountOut: TokenAmount, + slippage: Percentage +): Promise => { return ( await clamm.view.calculateMinAmountOut({ args: { expectedAmountOut: { v: expectedAmountOut }, slippage: { v: slippage } } }) - ).returns.v + ).returns.v as TokenAmount } export const isEnoughAmountToChangePrice = async ( clamm: CLAMMInstance, - amount: bigint, - startingSqrtPrice: bigint, - liquidity: bigint, - fee: bigint, + amount: TokenAmount, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + fee: Percentage, byAmountIn: boolean, xToY: boolean ): Promise => { @@ -575,15 +580,15 @@ export const isEnoughAmountToChangePrice = async ( export const calculateFeeGrowthInside = async ( clamm: CLAMMInstance, tickLowerIndex: bigint, - tickLowerFeeGrowthOutsideX: bigint, - tickLowerFeeGrowthOutsideY: bigint, + tickLowerFeeGrowthOutsideX: FeeGrowth, + tickLowerFeeGrowthOutsideY: FeeGrowth, tickUpperIndex: bigint, - tickUpperFeeGrowthOutsideX: bigint, - tickUpperFeeGrowthOutsideY: bigint, + tickUpperFeeGrowthOutsideX: FeeGrowth, + tickUpperFeeGrowthOutsideY: FeeGrowth, tickCurrent: bigint, - globalFeeGrowthX: bigint, - globalFeeGrowthY: bigint -): Promise<[bigint, bigint]> => { + globalFeeGrowthX: FeeGrowth, + globalFeeGrowthY: FeeGrowth +): Promise<[FeeGrowth, FeeGrowth]> => { const returns = ( await clamm.view.calculateFeeGrowthInside({ args: { @@ -599,18 +604,18 @@ export const calculateFeeGrowthInside = async ( } }) ).returns - return [returns[0].v, returns[1].v] + return [returns[0].v as FeeGrowth, returns[1].v as FeeGrowth] } export const calculateAmountDelta = async ( clamm: CLAMMInstance, currentTickIndex: bigint, - currentSqrtPrice: bigint, - liquidityDelta: bigint, + currentSqrtPrice: SqrtPrice, + liquidityDelta: Liquidity, liquiditySign: boolean, upperTick: bigint, lowerTick: bigint -): Promise<[bigint, bigint, boolean]> => { +): Promise<[TokenAmount, TokenAmount, boolean]> => { const returns = ( await clamm.view.calculateAmountDelta({ args: { @@ -623,16 +628,16 @@ export const calculateAmountDelta = async ( } }) ).returns - return [returns[0].v, returns[1].v, returns[2]] + return [returns[0].v as TokenAmount, returns[1].v as TokenAmount, returns[2]] } export const getNextSqrtPriceXUp = async ( clamm: CLAMMInstance, - startingSqrtPrice: bigint, - liquidity: bigint, - x: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + x: TokenAmount, addX: boolean -): Promise => { +): Promise => { return ( await clamm.view.getNextSqrtPriceXUp({ args: { @@ -642,16 +647,16 @@ export const getNextSqrtPriceXUp = async ( addX } }) - ).returns.v + ).returns.v as SqrtPrice } export const getNextSqrtPriceFromInput = async ( clamm: CLAMMInstance, - startingSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, xToY: boolean -): Promise => { +): Promise => { return ( await clamm.view.getNextSqrtPriceFromInput({ args: { @@ -661,16 +666,16 @@ export const getNextSqrtPriceFromInput = async ( xToY } }) - ).returns.v + ).returns.v as SqrtPrice } export const getNextSqrtPriceFromOutput = async ( clamm: CLAMMInstance, - startingSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + startingSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, xToY: boolean -): Promise => { +): Promise => { return ( await clamm.view.getNextSqrtPriceFromOutput({ args: { @@ -680,18 +685,18 @@ export const getNextSqrtPriceFromOutput = async ( xToY } }) - ).returns.v + ).returns.v as SqrtPrice } export const computeSwapStep = async ( clamm: CLAMMInstance, - currentSqrtPrice: bigint, - targetSqrtPrice: bigint, - liquidity: bigint, - amount: bigint, + currentSqrtPrice: SqrtPrice, + targetSqrtPrice: SqrtPrice, + liquidity: Liquidity, + amount: TokenAmount, byAmountIn: boolean, - fee: bigint -): Promise<{ nextSqrtPrice: bigint; amountIn: bigint; amountOut: bigint; feeAmount: bigint }> => { + fee: Percentage +): Promise => { const swapResult = ( await clamm.view.computeSwapStep({ args: { @@ -705,20 +710,20 @@ export const computeSwapStep = async ( }) ).returns return { - nextSqrtPrice: swapResult.nextSqrtPrice.v, - amountIn: swapResult.amountIn.v, - amountOut: swapResult.amountOut.v, - feeAmount: swapResult.feeAmount.v + nextSqrtPrice: swapResult.nextSqrtPrice.v as SqrtPrice, + amountIn: swapResult.amountIn.v as TokenAmount, + amountOut: swapResult.amountOut.v as TokenAmount, + feeAmount: swapResult.feeAmount.v as TokenAmount } } export const calculateMaxLiquidityPerTick = async ( clamm: CLAMMInstance, tickSpacing: bigint -): Promise => { +): Promise => { return ( await clamm.view.calculateMaxLiquidityPerTick({ args: { tickSpacing } }) - ).returns.v + ).returns.v as Liquidity } diff --git a/src/types.ts b/src/types.ts index 9262db5..8dc3aa7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,11 +1,6 @@ import { Address, HexString } from '@alephium/web3' import { PoolKey as _PoolKey, - FeeGrowth as _FeeGrowth, - Liquidity as _Liquidity, - Percentage as _Percentage, - SqrtPrice as _SqrtPrice, - TokenAmount as _TokenAmount, Pool as _Pool, Position as _Position, Tick as _Tick, @@ -19,17 +14,18 @@ import { } from '../artifacts/ts/types' import { InvariantError } from './consts' -type WrappedNumber = _FeeGrowth | _Liquidity | _Percentage | _SqrtPrice | _TokenAmount - -type UnwrapNumbers = { - [P in keyof T]: T[P] extends WrappedNumber ? bigint : T[P] -} +export type SqrtPrice = bigint & { readonly brand: unique symbol } +export type Price = bigint & { readonly brand: unique symbol } +export type FeeGrowth = bigint & { readonly brand: unique symbol } +export type Liquidity = bigint & { readonly brand: unique symbol } +export type TokenAmount = bigint & { readonly brand: unique symbol } +export type Percentage = bigint & { readonly brand: unique symbol } +export type FixedPoint = bigint & { readonly brand: unique symbol } export type TickVariant = LiquidityTick | Tick export interface FeeTier { - // percentage - fee: bigint + fee: Percentage tickSpacing: bigint } @@ -41,48 +37,81 @@ export type PoolKey = { export interface Pool { poolKey: PoolKey - // liquidity - liquidity: bigint - sqrtPrice: bigint + liquidity: Liquidity + sqrtPrice: SqrtPrice currentTickIndex: bigint - // feeGrowth x2 - feeGrowthGlobalX: bigint - feeGrowthGlobalY: bigint - // tokenAmount x2 - feeProtocolTokenX: bigint - feeProtocolTokenY: bigint + feeGrowthGlobalX: FeeGrowth + feeGrowthGlobalY: FeeGrowth + feeProtocolTokenX: TokenAmount + feeProtocolTokenY: TokenAmount startTimestamp: bigint lastTimestamp: bigint - // address feeReceiver: Address - // hexString reserveX: HexString reserveY: HexString } export interface Position { poolKey: PoolKey - // liquidity - liquidity: bigint + liquidity: Liquidity lowerTickIndex: bigint upperTickIndex: bigint - // feeGrowth x2 - feeGrowthInsideX: bigint - feeGrowthInsideY: bigint + feeGrowthInsideX: FeeGrowth + feeGrowthInsideY: FeeGrowth lastBlockNumber: bigint - // tokenAmount x2 - tokensOwedX: bigint - tokensOwedY: bigint + tokensOwedX: TokenAmount + tokensOwedY: TokenAmount owner: Address } -export type Tick = UnwrapNumbers<_Tick> -export type SwapResult = UnwrapNumbers<_SwapResult> -export type CalculateSwapResult = UnwrapNumbers<_CalculateSwapResult> -export type QuoteResult = UnwrapNumbers<_QuoteResult> -export type LiquidityResult = UnwrapNumbers<_LiquidityResult> -export type SingleTokenLiquidity = UnwrapNumbers<_SingleTokenLiquidity> -export type LiquidityTick = UnwrapNumbers<_LiquidityTick> +export interface Tick { + sign: boolean + index: bigint + liquidityChange: Liquidity + liquidityGross: Liquidity + sqrtPrice: SqrtPrice + feeGrowthOutsideX: FeeGrowth + feeGrowthOutsideY: FeeGrowth + secondsOutside: bigint +} + +export interface SwapResult { + nextSqrtPrice: SqrtPrice + amountIn: TokenAmount + amountOut: TokenAmount + feeAmount: TokenAmount +} + +export interface CalculateSwapResult { + amountIn: TokenAmount + amountOut: TokenAmount + startSqrtPrice: SqrtPrice + targetSqrtPrice: SqrtPrice + fee: TokenAmount +} + +export interface QuoteResult { + amountIn: TokenAmount + amountOut: TokenAmount + targetSqrtPrice: SqrtPrice +} + +export interface LiquidityResult { + x: TokenAmount + y: TokenAmount + l: Liquidity +} + +export interface SingleTokenLiquidity { + l: Liquidity + amount: TokenAmount +} + +export interface LiquidityTick { + index: bigint + liquidityChange: Liquidity + sign: boolean +} // stores bitmap chunks of ticks that have been initialized export type Tickmap = Map @@ -103,7 +132,7 @@ export function wrapPoolKey(poolKey: PoolKey): _PoolKey { } export function unwrapFeeTier(feeTier: _FeeTier): FeeTier { - return { ...feeTier, fee: feeTier.fee.v } + return { ...feeTier, fee: feeTier.fee.v as Percentage } } export function unwrapPoolKey(poolKey: _PoolKey): PoolKey { @@ -113,12 +142,12 @@ export function unwrapPoolKey(poolKey: _PoolKey): PoolKey { export function unwrapPool(pool: _Pool): Pool { const unwrapped = { poolKey: unwrapPoolKey(pool.poolKey), - liquidity: pool.liquidity.v, - sqrtPrice: pool.sqrtPrice.v, - feeGrowthGlobalX: pool.feeGrowthGlobalX.v, - feeGrowthGlobalY: pool.feeGrowthGlobalY.v, - feeProtocolTokenX: pool.feeProtocolTokenX.v, - feeProtocolTokenY: pool.feeProtocolTokenY.v + liquidity: pool.liquidity.v as Liquidity, + sqrtPrice: pool.sqrtPrice.v as SqrtPrice, + feeGrowthGlobalX: pool.feeGrowthGlobalX.v as FeeGrowth, + feeGrowthGlobalY: pool.feeGrowthGlobalY.v as FeeGrowth, + feeProtocolTokenX: pool.feeProtocolTokenX.v as TokenAmount, + feeProtocolTokenY: pool.feeProtocolTokenY.v as TokenAmount } return { ...pool, ...unwrapped } @@ -126,11 +155,11 @@ export function unwrapPool(pool: _Pool): Pool { export function unwrapTick(tick: _Tick): Tick { const unwrapped = { - liquidityChange: tick.liquidityChange.v, - liquidityGross: tick.liquidityGross.v, - sqrtPrice: tick.sqrtPrice.v, - feeGrowthOutsideX: tick.feeGrowthOutsideX.v, - feeGrowthOutsideY: tick.feeGrowthOutsideY.v + liquidityChange: tick.liquidityChange.v as Liquidity, + liquidityGross: tick.liquidityGross.v as Liquidity, + sqrtPrice: tick.sqrtPrice.v as SqrtPrice, + feeGrowthOutsideX: tick.feeGrowthOutsideX.v as FeeGrowth, + feeGrowthOutsideY: tick.feeGrowthOutsideY.v as FeeGrowth } return { ...tick, ...unwrapped } @@ -139,11 +168,11 @@ export function unwrapTick(tick: _Tick): Tick { export function unwrapPosition(position: _Position): Position { const unwrapped = { poolKey: unwrapPoolKey(position.poolKey), - liquidity: position.liquidity.v, - feeGrowthInsideX: position.feeGrowthInsideX.v, - feeGrowthInsideY: position.feeGrowthInsideY.v, - tokensOwedX: position.tokensOwedX.v, - tokensOwedY: position.tokensOwedY.v + liquidity: position.liquidity.v as Liquidity, + feeGrowthInsideX: position.feeGrowthInsideX.v as FeeGrowth, + feeGrowthInsideY: position.feeGrowthInsideY.v as FeeGrowth, + tokensOwedX: position.tokensOwedX.v as TokenAmount, + tokensOwedY: position.tokensOwedY.v as TokenAmount } return { ...position, ...unwrapped } @@ -151,9 +180,9 @@ export function unwrapPosition(position: _Position): Position { export function unwrapQuoteResult(quote: _QuoteResult): QuoteResult { const unwrapped = { - amountIn: quote.amountIn.v, - amountOut: quote.amountOut.v, - targetSqrtPrice: quote.targetSqrtPrice.v + amountIn: quote.amountIn.v as TokenAmount, + amountOut: quote.amountOut.v as TokenAmount, + targetSqrtPrice: quote.targetSqrtPrice.v as SqrtPrice } return { ...quote, ...unwrapped } @@ -161,20 +190,23 @@ export function unwrapQuoteResult(quote: _QuoteResult): QuoteResult { export function unwrapLiquidityResult(liquidityResult: _LiquidityResult): LiquidityResult { return { - x: liquidityResult.x.v, - y: liquidityResult.y.v, - l: liquidityResult.l.v + x: liquidityResult.x.v as TokenAmount, + y: liquidityResult.y.v as TokenAmount, + l: liquidityResult.l.v as Liquidity } } export function unwrapSingleTokenLiquidity( singleTokenLiquidity: _SingleTokenLiquidity ): SingleTokenLiquidity { - return { l: singleTokenLiquidity.l.v, amount: singleTokenLiquidity.amount.v } + return { + l: singleTokenLiquidity.l.v as Liquidity, + amount: singleTokenLiquidity.amount.v as TokenAmount + } } export function unwrapLiquidityTick(liquidityTick: _LiquidityTick): LiquidityTick { - return { ...liquidityTick, liquidityChange: liquidityTick.liquidityChange.v } + return { ...liquidityTick, liquidityChange: liquidityTick.liquidityChange.v as Liquidity } } function existsOnly(entity: T, exists: boolean, errorCode: bigint): T { diff --git a/src/utils.ts b/src/utils.ts index 20794ce..a4f7d70 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -23,14 +23,19 @@ import { } from './consts' import { Network } from './network' import { + FeeGrowth, FeeTier, + Liquidity, LiquidityTick, + Percentage, Pool, PoolKey, Position, SimulateSwapResult, + SqrtPrice, Tickmap, TickVariant, + TokenAmount, unwrapFeeTier, unwrapPoolKey, wrapFeeTier @@ -79,7 +84,7 @@ export async function waitTxConfirmed(promise: Promi export async function deployInvariant( signer: SignerProvider, - protocolFee: bigint + protocolFee: Percentage ): Promise { const account = await signer.getSelectedAccount() const clamm = await deployCLAMM(signer) @@ -126,7 +131,7 @@ export async function deployTokenFaucet( name: string, symbol: string, decimals: bigint, - supply: bigint + supply: TokenAmount ) { return await waitTxConfirmed( TokenFaucet.deploy(signer, { @@ -147,20 +152,20 @@ export function simulateInvariantSwap( pool: Pool, ticks: TickVariant[], xToY: boolean, - amount: bigint, + amount: TokenAmount, byAmountIn: boolean, - sqrtPriceLimit: bigint + sqrtPriceLimit: SqrtPrice ): SimulateSwapResult { return simulateSwap(tickmap, pool, ticks, xToY, amount, byAmountIn, sqrtPriceLimit) } -export async function balanceOf(tokenId: string, address: string): Promise { +export async function balanceOf(tokenId: string, address: string): Promise { const balances = await web3.getCurrentNodeProvider().addresses.getAddressesAddressBalance(address) if (tokenId == ALPH_TOKEN_ID) { - return BigInt(balances.balance) + return BigInt(balances.balance) as TokenAmount } const balance = balances.tokenBalances?.find(t => t.id === tokenId) - return balance === undefined ? 0n : BigInt(balance.amount) + return (balance === undefined ? 0n : BigInt(balance.amount)) as TokenAmount } export function decodeFeeTiers(string: string) { @@ -189,17 +194,17 @@ export function decodePools(string: string): Array { tokenX: parts[i], tokenY: parts[i + 1], feeTier: { - fee: decodeU256(parts[i + 2]), + fee: decodeU256(parts[i + 2]) as Percentage, tickSpacing: decodeU256(parts[i + 3]) } }, - liquidity: decodeU256(parts[i + 4]), - sqrtPrice: decodeU256(parts[i + 5]), + liquidity: decodeU256(parts[i + 4]) as Liquidity, + sqrtPrice: decodeU256(parts[i + 5]) as SqrtPrice, currentTickIndex: decodeI256(parts[i + 6]), - feeGrowthGlobalX: decodeU256(parts[i + 7]), - feeGrowthGlobalY: decodeU256(parts[i + 8]), - feeProtocolTokenX: decodeU256(parts[i + 9]), - feeProtocolTokenY: decodeU256(parts[i + 10]), + feeGrowthGlobalX: decodeU256(parts[i + 7]) as FeeGrowth, + feeGrowthGlobalY: decodeU256(parts[i + 8]) as FeeGrowth, + feeProtocolTokenX: decodeU256(parts[i + 9]) as TokenAmount, + feeProtocolTokenY: decodeU256(parts[i + 10]) as TokenAmount, startTimestamp: decodeU256(parts[i + 11]), lastTimestamp: decodeU256(parts[i + 12]), feeReceiver: AddressFromByteVec(parts[i + 13]), @@ -219,7 +224,10 @@ export const decodePoolKeys = (string: string): Array => { const poolKey: PoolKey = { tokenX: parts[i], tokenY: parts[i + 1], - feeTier: { fee: decodeU256(parts[i + 2]), tickSpacing: decodeU256(parts[i + 3]) } + feeTier: { + fee: decodeU256(parts[i + 2]) as Percentage, + tickSpacing: decodeU256(parts[i + 3]) + } } poolKeys.push(poolKey) } @@ -261,7 +269,7 @@ export const newPoolKey = async ( ) } -export const newFeeTier = async (fee: bigint, tickSpacing: bigint): Promise => { +export const newFeeTier = async (fee: Percentage, tickSpacing: bigint): Promise => { return unwrapFeeTier( ( await Utils.tests.newFeeTier({ @@ -295,18 +303,18 @@ export const decodePositions = (string: string): [[Position, Pool][], bigint] => tokenX: parts[i], tokenY: parts[i + 1], feeTier: { - fee: decodeU256(parts[i + 2]), + fee: decodeU256(parts[i + 2]) as Percentage, tickSpacing: decodeU256(parts[i + 3]) } }, - liquidity: decodeU256(parts[i + 4]), + liquidity: decodeU256(parts[i + 4]) as Liquidity, lowerTickIndex: decodeI256(parts[i + 5]), upperTickIndex: decodeI256(parts[i + 6]), - feeGrowthInsideX: decodeU256(parts[i + 7]), - feeGrowthInsideY: decodeU256(parts[i + 8]), + feeGrowthInsideX: decodeU256(parts[i + 7]) as FeeGrowth, + feeGrowthInsideY: decodeU256(parts[i + 8]) as FeeGrowth, lastBlockNumber: decodeU256(parts[i + 9]), - tokensOwedX: decodeU256(parts[i + 10]), - tokensOwedY: decodeU256(parts[i + 11]), + tokensOwedX: decodeU256(parts[i + 10]) as TokenAmount, + tokensOwedY: decodeU256(parts[i + 11]) as TokenAmount, owner: AddressFromByteVec(parts[i + 12]) } const pool: Pool = { @@ -314,17 +322,17 @@ export const decodePositions = (string: string): [[Position, Pool][], bigint] => tokenX: parts[i + 13], tokenY: parts[i + 14], feeTier: { - fee: decodeU256(parts[i + 15]), + fee: decodeU256(parts[i + 15]) as Percentage, tickSpacing: decodeU256(parts[i + 16]) } }, - liquidity: decodeU256(parts[i + 17]), - sqrtPrice: decodeU256(parts[i + 18]), + liquidity: decodeU256(parts[i + 17]) as Liquidity, + sqrtPrice: decodeU256(parts[i + 18]) as SqrtPrice, currentTickIndex: decodeI256(parts[i + 19]), - feeGrowthGlobalX: decodeU256(parts[i + 20]), - feeGrowthGlobalY: decodeU256(parts[i + 21]), - feeProtocolTokenX: decodeU256(parts[i + 22]), - feeProtocolTokenY: decodeU256(parts[i + 23]), + feeGrowthGlobalX: decodeU256(parts[i + 20]) as FeeGrowth, + feeGrowthGlobalY: decodeU256(parts[i + 21]) as FeeGrowth, + feeProtocolTokenX: decodeU256(parts[i + 22]) as TokenAmount, + feeProtocolTokenY: decodeU256(parts[i + 23]) as TokenAmount, startTimestamp: decodeU256(parts[i + 24]), lastTimestamp: decodeU256(parts[i + 25]), feeReceiver: AddressFromByteVec(parts[i + 26]), @@ -384,7 +392,7 @@ export const decodeLiquidityTicks = (string: string): LiquidityTick[] => { for (let i = 0; i < parts.length - 1; i += 3) { const tick: LiquidityTick = { index: decodeI256(parts[i]), - liquidityChange: decodeU256(parts[i + 1]), + liquidityChange: decodeU256(parts[i + 1]) as Liquidity, sign: decodeBool(hexToBytes(parts[i + 2])) } ticks.push(tick) diff --git a/test/contract/e2e/add-fee-tier.test.ts b/test/contract/e2e/add-fee-tier.test.ts index 0622094..3e39940 100644 --- a/test/contract/e2e/add-fee-tier.test.ts +++ b/test/contract/e2e/add-fee-tier.test.ts @@ -1,11 +1,11 @@ import { ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' -import { InvariantError, PERCENTAGE_SCALE } from '../../../src/consts' +import { InvariantError } from '../../../src/consts' import { expectError, feeTierExists, getFeeTiers, initFeeTier } from '../../../src/testUtils' import { deployInvariant, newFeeTier } from '../../../src/utils' import { toPercentage } from '../../../src/math' -import { FeeTier } from '../../../src/types' +import { FeeTier, Percentage } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -17,7 +17,7 @@ describe('add fee tier tests', () => { }) test('multiple', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 0.02% const fee = toPercentage(2n, 4n) @@ -80,7 +80,7 @@ describe('add fee tier tests', () => { }) test('existing', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 0.02% const fee = toPercentage(2n, 4n) @@ -97,7 +97,7 @@ describe('add fee tier tests', () => { }) test('not admin', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 0.02% const fee = toPercentage(2n, 4n) @@ -110,16 +110,16 @@ describe('add fee tier tests', () => { }) test('zero fee', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) - const fee = 0n + const fee = 0n as Percentage const tickSpacing = 10n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) }) test('zero tick spacing', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 0.02% const fee = toPercentage(2n, 4n) @@ -133,7 +133,7 @@ describe('add fee tier tests', () => { }) test('over upper bound tick spacing', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 0.02% const fee = toPercentage(2n, 4n) @@ -147,10 +147,10 @@ describe('add fee tier tests', () => { }) test('fee above limit', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) // 100% - const fee = 10n ** PERCENTAGE_SCALE + const fee = toPercentage(1n) const tickSpacing = 10n const feeTier: FeeTier = { fee, tickSpacing } await expectError(InvariantError.InvalidFee, initFeeTier(invariant, admin, feeTier), invariant) diff --git a/test/contract/e2e/change-fee-receiver.test.ts b/test/contract/e2e/change-fee-receiver.test.ts index e888ae8..4feb1ed 100644 --- a/test/contract/e2e/change-fee-receiver.test.ts +++ b/test/contract/e2e/change-fee-receiver.test.ts @@ -1,11 +1,19 @@ import { ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' -import { getPool, expectError, initTokensXY, initFeeTier, initPool, changeFeeReceiver } from '../../../src/testUtils' +import { + getPool, + expectError, + initTokensXY, + initFeeTier, + initPool, + changeFeeReceiver +} from '../../../src/testUtils' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' import { deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' -import { InvariantError } from '../../../src/consts' -import { FeeTier, PoolKey } from '../../../src/types' +import { InvariantError, SQRT_PRICE_DENOMINATOR } from '../../../src/consts' +import { FeeTier, PoolKey, TokenAmount } from '../../../src/types' +import { toPercentage } from '../../../src/math' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -14,8 +22,8 @@ let tokenX: TokenFaucetInstance let tokenY: TokenFaucetInstance describe('change fee receiver tests', () => { - const protocolFee = 10n ** 10n - const fee = 6n * 10n ** 9n + const protocolFee = toPercentage(1n, 2n) + const fee = toPercentage(6n, 3n) const tickSpacing = 10n let feeTier: FeeTier let poolKey: PoolKey @@ -26,11 +34,11 @@ describe('change fee receiver tests', () => { beforeEach(async () => { invariant = await deployInvariant(admin, protocolFee) - ;[tokenX, tokenY] = await initTokensXY(admin, 0n) + ;[tokenX, tokenY] = await initTokensXY(admin, 0n as TokenAmount) feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - await initPool(invariant, admin, tokenX, tokenY, feeTier, 10n ** 24n, 0n) + await initPool(invariant, admin, tokenX, tokenY, feeTier, SQRT_PRICE_DENOMINATOR, 0n) poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) }) diff --git a/test/contract/e2e/change-protocol-fee.test.ts b/test/contract/e2e/change-protocol-fee.test.ts index de6762b..c2fa19c 100644 --- a/test/contract/e2e/change-protocol-fee.test.ts +++ b/test/contract/e2e/change-protocol-fee.test.ts @@ -4,6 +4,7 @@ import { PrivateKeyWallet } from '@alephium/web3-wallet' import { deployInvariant } from '../../../src/utils' import { changeProtocolFee, expectError, getProtocolFee } from '../../../src/testUtils' import { InvariantError } from '../../../src/consts' +import { Percentage } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -15,17 +16,17 @@ describe('change protocol fee tests', () => { unauthorizedUser = await getSigner(ONE_ALPH * 1000n, 0) }) it('change protocol fee', async () => { - const protocolFee = 0n + const protocolFee = 0n as Percentage const invariant = await deployInvariant(admin, protocolFee) - const newFee = 1n + const newFee = 1n as Percentage await changeProtocolFee(invariant, admin, newFee) const queriedFee = await getProtocolFee(invariant) expect(queriedFee).toBe(newFee) }) it('not fee receiver', async () => { - const protocolFee = 0n + const protocolFee = 0n as Percentage const invariant = await deployInvariant(admin, protocolFee) - const newFee = 1n + const newFee = 1n as Percentage await expectError( InvariantError.NotAdmin, changeProtocolFee(invariant, unauthorizedUser, newFee), diff --git a/test/contract/e2e/create-pool.test.ts b/test/contract/e2e/create-pool.test.ts index 24a376b..88ebf28 100644 --- a/test/contract/e2e/create-pool.test.ts +++ b/test/contract/e2e/create-pool.test.ts @@ -2,42 +2,49 @@ import { ONE_ALPH, addressFromContractId, fetchContractState, web3 } from '@alep import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' -import { CLAMMError, InvariantError, PERCENTAGE_SCALE } from '../../../src/consts' +import { CLAMMError, InvariantError } from '../../../src/consts' import { getPool, initPool, initFeeTier, initTokensXY, expectError, - calculateSqrtPrice + calculateSqrtPrice, + TokenInstance } from '../../../src/testUtils' -import { CLAMM, Invariant } from '../../../artifacts/ts' -import { PoolKey } from '../../../src/types' +import { CLAMM, Invariant, InvariantInstance } from '../../../artifacts/ts' +import { toPercentage, toSqrtPrice } from '../../../src/math' +import { SqrtPrice, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') +let invariant: InvariantInstance +let tokenX: TokenInstance +let tokenY: TokenInstance let admin: PrivateKeyWallet let poolCreator: PrivateKeyWallet describe('create pool tests', () => { + const protocolFee = toPercentage(1n, 2n) + const fee = toPercentage(5n, 1n) + const supply = (10n ** 6n + 1000n) as TokenAmount + beforeAll(async () => { admin = await getSigner(ONE_ALPH * 1000n, 0) poolCreator = await getSigner(ONE_ALPH * 1000n, 0) }) + beforeEach(async () => { + invariant = await deployInvariant(admin, protocolFee) + ;[tokenX, tokenY] = await initTokensXY(admin, supply) + }) test('create pool', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 100n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n - const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) await initPool(invariant, poolCreator, tokenX, tokenY, feeTier, initSqrtPrice, initTick) const pool = await getPool(invariant, poolKey) @@ -55,20 +62,16 @@ describe('create pool tests', () => { expect(pool).toMatchObject(expectedPool) }) test('x to y and y to x', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 100n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) await initPool(invariant, poolCreator, tokenX, tokenY, feeTier, initSqrtPrice, initTick) await getPool(invariant, poolKey) @@ -80,20 +83,15 @@ describe('create pool tests', () => { ) }) test('with same tokens', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 100n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX] = await initTokensXY(admin, supply) - const poolKey: PoolKey = { tokenX: tokenX.contractId, tokenY: tokenX.contractId, feeTier } const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) await expectError( InvariantError.TokensAreSame, @@ -102,18 +100,14 @@ describe('create pool tests', () => { ) }) test('fee tier not added', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 100n const feeTier = await newFeeTier(fee, tickSpacing) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) await expectError( InvariantError.FeeTierNotFound, @@ -122,15 +116,11 @@ describe('create pool tests', () => { ) }) test('init tick not divided by tick spacing', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 3n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const initTick = 2n @@ -146,40 +136,32 @@ describe('create pool tests', () => { ) }) test('init sqrt price minimal difference from tick', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 3n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const initTick = 0n - const initSqrtPrice = (await calculateSqrtPrice(invariant, initTick)) + 1n + const initSqrtPrice = ((await calculateSqrtPrice(invariant, initTick)) + 1n) as SqrtPrice await initPool(invariant, poolCreator, tokenX, tokenY, feeTier, initSqrtPrice, initTick) const pool = await getPool(invariant, poolKey) expect(pool.currentTickIndex).toBe(initTick) }) test('init sqrt price has closer init tick', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 1n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const initTick = 2n - const initSqrtPrice = 1000175003749000000000000n + const initSqrtPrice = 1000175003749000000000000n as SqrtPrice await expectError( InvariantError.TickAndSqrtPriceMismatch, initPool(invariant, poolCreator, tokenX, tokenY, feeTier, initSqrtPrice, initTick), @@ -193,20 +175,16 @@ describe('create pool tests', () => { expect(pool.currentTickIndex).toBe(correctInitTick) }) test('init sqrt price has closer init tick with tick spacing over one', async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const invariant = await deployInvariant(admin, protocolFee) - - const fee = 5n * 10n ** (PERCENTAGE_SCALE - 1n) const tickSpacing = 3n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const supply = 10n ** 6n + 1000n + const supply = (10n ** 6n + 1000n) as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const initTick = 0n - const initSqrtPrice = 1000225003749000000000000n + const initSqrtPrice = 1000225003749000000000000n as SqrtPrice await expectError( InvariantError.TickAndSqrtPriceMismatch, initPool(invariant, poolCreator, tokenX, tokenY, feeTier, initSqrtPrice, initTick), diff --git a/test/contract/e2e/cross-both-side.test.ts b/test/contract/e2e/cross-both-side.test.ts index af69457..4cd9b47 100644 --- a/test/contract/e2e/cross-both-side.test.ts +++ b/test/contract/e2e/cross-both-side.test.ts @@ -15,6 +15,7 @@ import { InvariantError, MAX_SQRT_PRICE, MIN_SQRT_PRICE } from '../../../src/con import { calculateSqrtPrice, toLiquidity } from '../../../src/math' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' import { newFeeTier, newPoolKey } from '../../../src/utils' +import { TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -31,7 +32,7 @@ describe('cross tests', () => { admin = await getSigner(ONE_ALPH * 100000n, 0) }) beforeEach(async () => { - ;[invariant, tokenX, tokenY] = await initDexAndTokens(admin, 10n ** 24n) + ;[invariant, tokenX, tokenY] = await initDexAndTokens(admin, (10n ** 24n) as TokenAmount) const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) @@ -40,8 +41,8 @@ describe('cross tests', () => { await initBasicPool(invariant, positionsOwner, tokenX, tokenY) // init positions { - const mintAmount = 10n ** 5n - const positionAmount = mintAmount / 2n + const mintAmount = (10n ** 5n) as TokenAmount + const positionAmount = (mintAmount / 2n) as TokenAmount await withdrawTokens(positionsOwner, [tokenX, mintAmount], [tokenY, mintAmount]) const [lowerTick, middleTick, upperTick] = [-20n, -10n, 10n] const liquidityDelta = toLiquidity(20006000n) @@ -77,7 +78,7 @@ describe('cross tests', () => { } swapper = await getSigner(ONE_ALPH * 1000n, 0) - const limitWithoutCrossTickAmount = 10_068n + const limitWithoutCrossTickAmount = 10_068n as TokenAmount await withdrawTokens( swapper, @@ -109,7 +110,7 @@ describe('cross tests', () => { const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) - const minAmountToCrossFromTickPrice = 3n + const minAmountToCrossFromTickPrice = 3n as TokenAmount await withdrawTokens( swapper, [tokenX, minAmountToCrossFromTickPrice], @@ -140,7 +141,7 @@ describe('cross tests', () => { } // a new position with massive liquidity { - const mintAmount = 10n ** 19n + const mintAmount = (10n ** 19n) as TokenAmount await withdrawTokens(positionsOwner, [tokenX, mintAmount], [tokenY, mintAmount]) const [lowerTick, upperTick] = [-20n, 0n] @@ -159,9 +160,9 @@ describe('cross tests', () => { ) } { - const predictedRequiredX = 3n - const xOut = 1n - const yIn = 2n + const predictedRequiredX = 3n as TokenAmount + const xOut = 1n as TokenAmount + const yIn = 2n as TokenAmount await withdrawTokens(swapper, [tokenX, predictedRequiredX]) await initSwap( @@ -211,7 +212,7 @@ describe('cross tests', () => { const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) - const notCrossAmount = 1n + const notCrossAmount = 1n as TokenAmount await withdrawTokens(swapper, [tokenX, notCrossAmount]) await expectError( diff --git a/test/contract/e2e/cross.test.ts b/test/contract/e2e/cross.test.ts index be6b25d..6da1c2e 100644 --- a/test/contract/e2e/cross.test.ts +++ b/test/contract/e2e/cross.test.ts @@ -19,6 +19,7 @@ import { withdrawTokens } from '../../../src/testUtils' import { toLiquidity } from '../../../src/math' +import { TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -28,7 +29,7 @@ describe('cross tests', () => { admin = await getSigner(ONE_ALPH * 1000n, 0) }) test('cross', async () => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, 10n ** 23n) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, (10n ** 23n) as TokenAmount) const feeTier = await newFeeTier(...getBasicFeeTickSpacing()) await initFeeTier(invariant, admin, feeTier) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) @@ -41,7 +42,7 @@ describe('cross tests', () => { const liquidityDelta = toLiquidity(1_000_000n) { // definitely enough for the given liquidity/ticks - const approvedAmount = liquidityDelta + const approvedAmount = BigInt(liquidityDelta) as TokenAmount await withdrawTokens(positionsOwner, [tokenX, approvedAmount], [tokenY, approvedAmount]) const [lowerTick, upperTick] = [-40n, -10n] @@ -68,7 +69,7 @@ describe('cross tests', () => { // cross swap { const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const approvedAmount = 1000n + const approvedAmount = 1000n as TokenAmount await withdrawTokens(swapper, [tokenX, approvedAmount]) { diff --git a/test/contract/e2e/interaction-with-pool-on-removed-fee-tier.test.ts b/test/contract/e2e/interaction-with-pool-on-removed-fee-tier.test.ts index 77ddf3e..a20bafd 100644 --- a/test/contract/e2e/interaction-with-pool-on-removed-fee-tier.test.ts +++ b/test/contract/e2e/interaction-with-pool-on-removed-fee-tier.test.ts @@ -2,7 +2,7 @@ import { DUST_AMOUNT, MAP_ENTRY_DEPOSIT, ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { balanceOf, deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' -import { InvariantError, MIN_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' +import { InvariantError, MIN_SQRT_PRICE } from '../../../src/consts' import { getPool, initPool, @@ -26,8 +26,8 @@ import { TransferPosition, WithdrawProtocolFee } from '../../../artifacts/ts' -import { toLiquidity } from '../../../src/math' -import { FeeTier, PoolKey, wrapPoolKey } from '../../../src/types' +import { toLiquidity, toPercentage, toSqrtPrice } from '../../../src/math' +import { FeeTier, PoolKey, TokenAmount, wrapPoolKey } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -41,15 +41,15 @@ let tokenX: TokenFaucetInstance let tokenY: TokenFaucetInstance describe('interaction with pool on removed fee tiers tests', () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const fee = 6n * 10n ** (PERCENTAGE_SCALE - 3n) + const protocolFee = toPercentage(1n, 2n) + const fee = toPercentage(6n, 3n) const tickSpacing = 10n const initTick = 0n - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 18n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 18n) as TokenAmount const lowerTickIndex = -20n const upperTickIndex = 10n - const mint = 10n ** 10n + const mint = (10n ** 10n) as TokenAmount const liquidityDelta = toLiquidity(1000000n) let feeTier: FeeTier let poolKey: PoolKey @@ -109,7 +109,7 @@ describe('interaction with pool on removed fee tiers tests', () => { expect(poolAfter.liquidity).toBe(liquidityDelta) }) test('init swap', async () => { - const amount = 1000n + const amount = 1000n as TokenAmount await withdrawTokens(swapper, [tokenX, amount], [tokenY, amount]) const { x: dexXBefore, y: dexYBefore } = await getReserveBalances(invariant, poolKey) diff --git a/test/contract/e2e/limits.test.ts b/test/contract/e2e/limits.test.ts index 689c0c3..4d709cc 100644 --- a/test/contract/e2e/limits.test.ts +++ b/test/contract/e2e/limits.test.ts @@ -7,8 +7,7 @@ import { GLOBAL_MIN_TICK, MAX_SQRT_PRICE, MAX_U256, - MIN_SQRT_PRICE, - PERCENTAGE_SCALE + MIN_SQRT_PRICE } from '../../../src/consts' import { getPool, @@ -24,14 +23,17 @@ import { getDeltaY, getLiquidityByX, getLiquidityByY, - getMaxTick + getMaxTick, + toPercentage } from '../../../src/math' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' +import { Liquidity, TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet +const withdrawAmount = MAX_U256 as TokenAmount describe('limits tests', () => { beforeAll(async () => { admin = await getSigner(ONE_ALPH * 1000n, 0) @@ -44,15 +46,15 @@ describe('limits tests', () => { await bigDepositOneAndSwapTheOther(false) }) test('big deposit both tokens', async () => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, MAX_U256) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, withdrawAmount) const user = await getSigner(ONE_ALPH * 1000n, 0) - await withdrawTokens(user, [tokenX, MAX_U256], [tokenY, MAX_U256]) + await withdrawTokens(user, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) // 2^176 - const limitAmount = 95780971304118053647396689196894323976171195136475136n + const limitAmount = 95780971304118053647396689196894323976171195136475136n as TokenAmount // 0.6% fee - const [fee, tickSpacing] = [6n * 10n ** (PERCENTAGE_SCALE - 3n), 1n] + const [fee, tickSpacing] = [toPercentage(6n, 3n), 1n] const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await initFeeTier(invariant, admin, feeTier) @@ -79,8 +81,8 @@ describe('limits tests', () => { invariant, user, poolKey, - MAX_U256, - MAX_U256, + withdrawAmount, + withdrawAmount, lowerTick, upperTick, liquidityDelta, @@ -105,15 +107,15 @@ describe('limits tests', () => { }) }) test('deposit limits at upper limit', async () => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, MAX_U256) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, withdrawAmount) const user = await getSigner(ONE_ALPH * 1000n, 0) - await withdrawTokens(user, [tokenX, MAX_U256], [tokenY, MAX_U256]) + await withdrawTokens(user, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) // 2^236 const limitAmount = 110427941548649020598956093796432407239217743554726184882600387580788736n // 0.6% fee - const [fee, tickSpacing] = [6n * 10n ** (PERCENTAGE_SCALE - 3n), 1n] + const [fee, tickSpacing] = [toPercentage(6n, 3n), 1n] const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await initFeeTier(invariant, admin, feeTier) @@ -127,7 +129,7 @@ describe('limits tests', () => { expect(currentTickIndex).toBe(initTick) expect(sqrtPrice).toBe(initSqrtPrice) - const positionAmount = limitAmount - 1n + const positionAmount = (limitAmount - 1n) as TokenAmount const { l: liquidityDelta } = await getLiquidityByY( positionAmount, 0n, @@ -142,8 +144,8 @@ describe('limits tests', () => { invariant, user, poolKey, - MAX_U256, - MAX_U256, + withdrawAmount, + withdrawAmount, 0n, GLOBAL_MAX_TICK, liquidityDelta, @@ -153,15 +155,15 @@ describe('limits tests', () => { }) test('big deposit and swaps', async () => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, MAX_U256) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, withdrawAmount) const user = await getSigner(ONE_ALPH * 1000n, 0) - await withdrawTokens(user, [tokenX, MAX_U256], [tokenY, MAX_U256]) + await withdrawTokens(user, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) // 2^177 const limitAmount = 191561942608236107294793378393788647952342390272950272n // 0.6% fee - const [fee, tickSpacing] = [6n * 10n ** (PERCENTAGE_SCALE - 3n), 1n] + const [fee, tickSpacing] = [toPercentage(6n, 3n), 1n] const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await initFeeTier(invariant, admin, feeTier) @@ -174,7 +176,7 @@ describe('limits tests', () => { const [lowerTick, upperTick] = [-tickSpacing, tickSpacing] const { sqrtPrice } = await getPool(invariant, poolKey) - const posAmount = limitAmount / 2n + const posAmount = (limitAmount / 2n) as TokenAmount const { l: liquidityDelta } = await getLiquidityByX( posAmount, lowerTick, @@ -190,8 +192,8 @@ describe('limits tests', () => { invariant, user, poolKey, - MAX_U256, - MAX_U256, + withdrawAmount, + withdrawAmount, lowerTick, upperTick, liquidityDelta, @@ -217,7 +219,7 @@ describe('limits tests', () => { }) } - const swapAmount = limitAmount / 8n + const swapAmount = (limitAmount / 8n) as TokenAmount for (let n = 1; n <= 4; ++n) { await initSwap( @@ -232,16 +234,16 @@ describe('limits tests', () => { } }) test('full range with max liquidity', async () => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, MAX_U256) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, withdrawAmount) const user = await getSigner(ONE_ALPH * 1000n, 0) - await withdrawTokens(user, [tokenX, MAX_U256], [tokenY, MAX_U256]) + await withdrawTokens(user, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) // 2^237 const liquidityLimitAmount = - 220855883097298041197912187592864814478435487109452369765200775161577472n + 220855883097298041197912187592864814478435487109452369765200775161577472n as Liquidity // 0.6% fee - const [fee, tickSpacing] = [6n * 10n ** (PERCENTAGE_SCALE - 3n), 1n] + const [fee, tickSpacing] = [toPercentage(6n, 3n), 1n] const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await initFeeTier(invariant, admin, feeTier) @@ -261,8 +263,8 @@ describe('limits tests', () => { invariant, user, poolKey, - MAX_U256, - MAX_U256, + withdrawAmount, + withdrawAmount, GLOBAL_MIN_TICK, GLOBAL_MAX_TICK, liquidityDelta, @@ -280,15 +282,16 @@ describe('limits tests', () => { }) const bigDepositOneAndSwapTheOther = async (xToY: boolean) => { - const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, MAX_U256) + const [invariant, tokenX, tokenY] = await initDexAndTokens(admin, withdrawAmount) const user = await getSigner(ONE_ALPH * 1000n, 0) - await withdrawTokens(user, [tokenX, MAX_U256], [tokenY, MAX_U256]) + await withdrawTokens(user, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) // 2^206 - const limitAmount = 102844034832575377634685573909834406561420991602098741459288064n + const limitAmount = + 102844034832575377634685573909834406561420991602098741459288064n as TokenAmount // 0.6% fee - const [fee, tickSpacing] = [6n * 10n ** (PERCENTAGE_SCALE - 3n), 1n] + const [fee, tickSpacing] = [toPercentage(6n, 3n), 1n] const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await initFeeTier(invariant, admin, feeTier) @@ -310,8 +313,8 @@ const bigDepositOneAndSwapTheOther = async (xToY: boolean) => { invariant, user, poolKey, - MAX_U256, - MAX_U256, + withdrawAmount, + withdrawAmount, lowerTick, upperTick, liquidityDelta, diff --git a/test/contract/e2e/liquidity-gap.test.ts b/test/contract/e2e/liquidity-gap.test.ts index bad4a4e..f67225b 100644 --- a/test/contract/e2e/liquidity-gap.test.ts +++ b/test/contract/e2e/liquidity-gap.test.ts @@ -20,12 +20,12 @@ import { withdrawTokens } from '../../../src/testUtils' import { toLiquidity, toPercentage, toSqrtPrice } from '../../../src/math' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, PoolKey, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('liquidity gap tests', () => { - const mintAmount = 10n ** 10n + const mintAmount = (10n ** 10n) as TokenAmount let deployer: PrivateKeyWallet let positionOwner: PrivateKeyWallet let swapper: PrivateKeyWallet @@ -53,7 +53,7 @@ describe('liquidity gap tests', () => { await initPool(invariant, deployer, tokenX, tokenY, feeTier, initSqrtPrice, initTick) }) test('init position', async () => { - const amount = 10n ** 6n + const amount = (10n ** 6n) as TokenAmount const lowerTick = -10n const upperTick = 10n const liquidityDelta = toLiquidity(20006000n) @@ -79,7 +79,7 @@ describe('liquidity gap tests', () => { expect(poolAfter.liquidity).toEqual(liquidityDelta) }) test('init swap', async () => { - const amount = 10067n + const amount = 10067n as TokenAmount await withdrawTokens(swapper, [tokenX, amount], [tokenY, amount]) const { x: dexXBefore, y: dexYBefore } = await getReserveBalances(invariant, poolKey) @@ -120,7 +120,7 @@ describe('liquidity gap tests', () => { const lowerTick = -90n const upperTick = -50n const liquidityDelta = toLiquidity(20008000n) - const amount = 10n ** 6n + const amount = (10n ** 6n) as TokenAmount await withdrawTokens(positionOwner, [tokenX, amount], [tokenY, amount]) const poolBefore = await getPool(invariant, poolKey) @@ -141,7 +141,7 @@ describe('liquidity gap tests', () => { ) }) test('should skip gap and then swap', async () => { - const amount = 10067n + const amount = 10067n as TokenAmount await withdrawTokens(swapper, [tokenX, amount], [tokenY, amount]) const slippage = MIN_SQRT_PRICE diff --git a/test/contract/e2e/max-tick-cross.test.ts b/test/contract/e2e/max-tick-cross.test.ts index 112a06c..cbfbc32 100644 --- a/test/contract/e2e/max-tick-cross.test.ts +++ b/test/contract/e2e/max-tick-cross.test.ts @@ -15,7 +15,7 @@ import { MAX_SQRT_PRICE, MIN_SQRT_PRICE, SEARCH_RANGE } from '../../../src/const import { PrivateKeyWallet } from '@alephium/web3-wallet' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' import { toLiquidity } from '../../../src/math' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Percentage, PoolKey, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -23,9 +23,9 @@ describe('max tick cross spec', () => { const [fee, tickSpacing] = getBasicFeeTickSpacing() const searchLimit = SEARCH_RANGE * tickSpacing const txGasLimit = 5000000n - const positionOwnerMint = 1n << 128n - const swapperMint = 1n << 30n - const supply = positionOwnerMint + swapperMint + const positionOwnerMint = (1n << 128n) as TokenAmount + const swapperMint = (1n << 30n) as TokenAmount + const supply = (positionOwnerMint + swapperMint) as TokenAmount const liquidityDelta = toLiquidity(10000000n) let admin: PrivateKeyWallet let positionOwner: PrivateKeyWallet @@ -40,7 +40,7 @@ describe('max tick cross spec', () => { admin = await getSigner(ONE_ALPH * 1000n, 0) positionOwner = await getSigner(ONE_ALPH * 1000n, 0) swapper = await getSigner(ONE_ALPH * 1000n, 0) - invariant = await deployInvariant(admin, 0n) + invariant = await deployInvariant(admin, 0n as Percentage) ;[tokenX, tokenY] = await initTokensXY(admin, supply) await withdrawTokens(positionOwner, [tokenX, positionOwnerMint], [tokenY, positionOwnerMint]) feeTier = await newFeeTier(fee, tickSpacing) @@ -51,7 +51,7 @@ describe('max tick cross spec', () => { test('max tick cross swap xToY and ByAmountIn, no liquidity gap between positions', async () => { const lastInitializedTick = -250n - const amount = 40282n + const amount = 40282n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = true @@ -96,7 +96,7 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountIn, no liquidity gap between positions', async () => { const lastInitializedTick = 120n - const amount = 44998n + const amount = 44998n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE const byAmountIn = true @@ -142,7 +142,7 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap xToY and ByAmountIn, liquidity gap between positions', async () => { const lastInitializedTick = -250n - const amount = 35250n + const amount = 35250n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = true @@ -186,7 +186,7 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountIn, liquidity gap between positions', async () => { const lastInitializedTick = 240n - const amount = 40000n + const amount = 40000n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE const byAmountIn = true @@ -231,7 +231,7 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap xToY and ByAmountIn, positions between search limit range', async () => { const lastInitializedTick = -35000n - const amount = 13569916n + const amount = 13569916n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = true @@ -274,7 +274,7 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountIn, positions between search limit range', async () => { const lastInitializedTick = 25000n - const amount = 17947500n + const amount = 17947500n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE const byAmountIn = true @@ -317,8 +317,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap xToY and ByAmountOut, no liquidity gap between positions', async () => { const lastInitializedTick = -250n - const mintAmount = 60000n - const swapAmount = 44500n + const mintAmount = 60000n as TokenAmount + const swapAmount = 44500n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = false @@ -372,8 +372,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountOut, no liquidity gap between positions', async () => { const lastInitializedTick = 120n - const mintAmount = 60000n - const swapAmount = 39000n + const mintAmount = 60000n as TokenAmount + const swapAmount = 39000n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE @@ -427,8 +427,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap xToY and ByAmountOut, liquidity gap between positions', async () => { const lastInitializedTick = -500n - const mintAmount = 60000n - const swapAmount = 39500n + const mintAmount = 60000n as TokenAmount + const swapAmount = 39500n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = false @@ -482,8 +482,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountOut, liquidity gap between positions', async () => { const lastInitializedTick = 360n - const mintAmount = 60000n - const swapAmount = 39000n + const mintAmount = 60000n as TokenAmount + const swapAmount = 39000n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE @@ -537,8 +537,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap xToY and ByAmountOut, positions between search limit range', async () => { const lastInitializedTick = -25000n - const mintAmount = 20000000n - const swapAmount = 6050000n + const mintAmount = 20000000n as TokenAmount + const swapAmount = 6050000n as TokenAmount const xToY = true const slippage = MIN_SQRT_PRICE const byAmountIn = false @@ -591,8 +591,8 @@ describe('max tick cross spec', () => { }, 100000) test('max tick cross swap yToX and ByAmountOut, positions between search limit range', async () => { const lastInitializedTick = 25000n - const mintAmount = 20000000n - const swapAmount = 6408000n + const mintAmount = 20000000n as TokenAmount + const swapAmount = 6408000n as TokenAmount const xToY = false const slippage = MAX_SQRT_PRICE const byAmountIn = false diff --git a/test/contract/e2e/multiple-swap.test.ts b/test/contract/e2e/multiple-swap.test.ts index 10a5e0d..a0f5de2 100644 --- a/test/contract/e2e/multiple-swap.test.ts +++ b/test/contract/e2e/multiple-swap.test.ts @@ -2,7 +2,7 @@ import { ONE_ALPH } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { balanceOf, deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' -import { MAX_SQRT_PRICE, MIN_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' +import { MAX_SQRT_PRICE, MIN_SQRT_PRICE } from '../../../src/consts' import { feeTierExists, getPool, @@ -16,8 +16,8 @@ import { withdrawTokens } from '../../../src/testUtils' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' -import { calculateSqrtPrice, getLiquidity } from '../../../src/math' -import { FeeTier, PoolKey } from '../../../src/types' +import { calculateSqrtPrice, getLiquidity, toPercentage } from '../../../src/math' +import { FeeTier, PoolKey, TokenAmount } from '../../../src/types' let admin: PrivateKeyWallet let positionOwner: PrivateKeyWallet @@ -27,15 +27,15 @@ let tokenX: TokenFaucetInstance let tokenY: TokenFaucetInstance describe('multiple swap tests', () => { - const fee = 10n ** (PERCENTAGE_SCALE - 3n) + const fee = toPercentage(1n, 3n) const tickSpacing = 1n const initTick = 0n const [lowerTick, upperTick] = [-953n, 953n] - const approvedAmount = 100n + const approvedAmount = 100n as TokenAmount let feeTier: FeeTier let poolKey: PoolKey - const mintSwapper = 100n + const mintSwapper = 100n as TokenAmount beforeAll(async () => { admin = await getSigner(ONE_ALPH * 1000n, 0) @@ -44,11 +44,11 @@ describe('multiple swap tests', () => { }) beforeEach(async () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) + const protocolFee = toPercentage(1n, 2n) invariant = await deployInvariant(admin, protocolFee) - const mintPosition = 10n ** 10n - ;[tokenX, tokenY] = await initTokensXY(admin, mintPosition + mintSwapper) + const mintPosition = (10n ** 10n) as TokenAmount + ;[tokenX, tokenY] = await initTokensXY(admin, (mintPosition + mintSwapper) as TokenAmount) feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) @@ -97,7 +97,7 @@ describe('multiple swap tests', () => { // swaps { await withdrawTokens(swapper, [tokenX, mintSwapper]) - const swapAmount = 10n + const swapAmount = 10n as TokenAmount const sqrtPriceLimit = MIN_SQRT_PRICE for (let n = 0; n < 10; n++) { const { targetSqrtPrice } = await quote( @@ -149,7 +149,7 @@ describe('multiple swap tests', () => { // swaps { await withdrawTokens(swapper, [tokenY, mintSwapper]) - const swapAmount = 10n + const swapAmount = 10n as TokenAmount const sqrtPriceLimit = MAX_SQRT_PRICE for (let n = 0; n < 10; n++) { const { targetSqrtPrice } = await quote( diff --git a/test/contract/e2e/position-list.test.ts b/test/contract/e2e/position-list.test.ts index 35da179..423e617 100644 --- a/test/contract/e2e/position-list.test.ts +++ b/test/contract/e2e/position-list.test.ts @@ -17,18 +17,19 @@ import { verifyPositionList, withdrawTokens } from '../../../src/testUtils' -import { calculateSqrtPrice, toLiquidity } from '../../../src/math' -import { InvariantError, MAX_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' +import { calculateSqrtPrice, toLiquidity, toPercentage } from '../../../src/math' +import { InvariantError, MAX_SQRT_PRICE } from '../../../src/consts' import { deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' +import { Liquidity, Percentage, TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet -const tokenSupply = 10n ** 10n +const tokenSupply = (10n ** 10n) as TokenAmount // the value just has to be >= available tokens during every deposit -const approvedTokens = tokenSupply / 4n +const approvedTokens = (tokenSupply / 4n) as TokenAmount describe('position list tests', () => { beforeAll(async () => { @@ -36,8 +37,8 @@ describe('position list tests', () => { }) test('remove position from an empty list', async () => { - const invariant = await deployInvariant(admin, 0n) - const [tokenX, tokenY] = await initTokensXY(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) + const [tokenX, tokenY] = await initTokensXY(admin, 0n as TokenAmount) const withoutPositions = await getSigner(ONE_ALPH * 1000n, 0) const [fee] = getBasicFeeTickSpacing() @@ -64,11 +65,11 @@ describe('position list tests', () => { }) test('multiple positions on the same tick', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) const [tokenX, tokenY] = await initTokensXY(admin, tokenSupply) // 0.02% - const fee = 2n * 10n ** (PERCENTAGE_SCALE - 4n) + const fee = toPercentage(2n, 4n) const tickSpacing = 10n const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) @@ -88,7 +89,7 @@ describe('position list tests', () => { const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) const { sqrtPrice: slippageLimitLower } = await getPool(invariant, poolKey) - const liquiditiyDelta = 100n + const liquiditiyDelta = 100n as Liquidity // all 3 exact same ticks { const [lowerTickIndex, upperTickIndex] = [-10n, 10n] @@ -229,7 +230,7 @@ describe('position list tests', () => { admin = await getSigner(ONE_ALPH * 1000n, 0) }) beforeEach(async () => { - invariant = await deployInvariant(admin, 0n) + invariant = await deployInvariant(admin, 0n as Percentage) ;[tokenX, tokenY] = await initTokensXY(admin, tokenSupply) const feeTier = await newFeeTier(getBasicFeeTickSpacing()[0], 3n) diff --git a/test/contract/e2e/position-slippage.test.ts b/test/contract/e2e/position-slippage.test.ts index 908b590..8e37745 100644 --- a/test/contract/e2e/position-slippage.test.ts +++ b/test/contract/e2e/position-slippage.test.ts @@ -15,6 +15,7 @@ import { import { calculateSqrtPrice, toLiquidity } from '../../../src/math' import { InvariantError } from '../../../src/consts' import { InvariantInstance, TokenFaucetInstance } from '../../../artifacts/ts' +import { Percentage, SqrtPrice, TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -26,7 +27,7 @@ let tokenY: TokenFaucetInstance describe('position slippage tests', () => { const [fee, tickSpacing] = getBasicFeeTickSpacing() - const approvedTokens = 10n ** 10n + const approvedTokens = (10n ** 10n) as TokenAmount const liquidityDelta = toLiquidity(1_000_000n) const [lowerTick, upperTick] = [-tickSpacing, tickSpacing] @@ -35,11 +36,11 @@ describe('position slippage tests', () => { }) beforeEach(async () => { - invariant = await deployInvariant(admin, 0n) + invariant = await deployInvariant(admin, 0n as Percentage) const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const tokenSupply = 10n ** 23n + const tokenSupply = (10n ** 23n) as TokenAmount ;[tokenX, tokenY] = await initTokensXY(admin, tokenSupply) positionOwner = await getSigner(ONE_ALPH * 1000n, 0) await withdrawTokens(positionOwner, [tokenX, tokenSupply], [tokenY, tokenSupply]) @@ -95,8 +96,8 @@ describe('position slippage tests', () => { const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.address, tokenY.address, feeTier) - const slippageLimitLower = 994734637981406576896367n - const slippageLimitUpper = 1025038048074314166333500n + const slippageLimitLower = 994734637981406576896367n as SqrtPrice + const slippageLimitUpper = 1025038048074314166333500n as SqrtPrice await initPosition( invariant, positionOwner, @@ -114,8 +115,8 @@ describe('position slippage tests', () => { const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.address, tokenY.address, feeTier) - const slippageLimitLower = 1014432353584998786339859n - const slippageLimitUpper = 1045335831204498605270797n + const slippageLimitLower = 1014432353584998786339859n as SqrtPrice + const slippageLimitUpper = 1045335831204498605270797n as SqrtPrice await expectError( InvariantError.PriceLimitReached, @@ -139,8 +140,8 @@ describe('position slippage tests', () => { const feeTier = await newFeeTier(fee, tickSpacing) const poolKey = await newPoolKey(tokenX.address, tokenY.address, feeTier) - const slippageLimitLower = 955339206774222158009382n - const slippageLimitUpper = 984442481813945288458906n + const slippageLimitLower = 955339206774222158009382n as SqrtPrice + const slippageLimitUpper = 984442481813945288458906n as SqrtPrice await expectError( InvariantError.PriceLimitReached, diff --git a/test/contract/e2e/position.test.ts b/test/contract/e2e/position.test.ts index cb6cb3f..eedf3ff 100644 --- a/test/contract/e2e/position.test.ts +++ b/test/contract/e2e/position.test.ts @@ -1,7 +1,6 @@ -import { ONE_ALPH, addressFromContractId, fetchContractState, web3 } from '@alephium/web3' +import { ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' -import { CLAMM, Invariant } from '../../../artifacts/ts' import { balanceOf, deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' import { calculateSqrtPrice, @@ -25,7 +24,8 @@ import { MIN_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' -import { toLiquidity } from '../../../src/math' +import { toLiquidity, toPercentage } from '../../../src/math' +import { Liquidity, Percentage, SqrtPrice, TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -38,11 +38,11 @@ describe('position tests', () => { test('create basic position', async () => { const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 500n - const fee = 0n + const supply = 500n as TokenAmount + const fee = 0n as Percentage const tickSpacing = 1n - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) const [tokenX, tokenY] = await initTokensXY(admin, supply) const feeTier = await newFeeTier(fee, tickSpacing) @@ -58,7 +58,7 @@ describe('position tests', () => { const lowerTickIndex = -10n const upperTickIndex = 10n - const liquidityDelta = 10n + const liquidityDelta = 10n as Liquidity await initPosition( invariant, @@ -69,7 +69,7 @@ describe('position tests', () => { lowerTickIndex, upperTickIndex, liquidityDelta, - 0n, + 0n as SqrtPrice, MAX_SQRT_PRICE ) @@ -90,11 +90,11 @@ describe('position tests', () => { }) test('create with equal lower and upper tick', async () => { const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 500n - const fee = 0n + const supply = 500n as TokenAmount + const fee = 0n as Percentage const tickSpacing = 1n - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) const [tokenX, tokenY] = await initTokensXY(admin, supply) await withdrawTokens(positionOwner, [tokenX, supply], [tokenY, supply]) @@ -109,11 +109,7 @@ describe('position tests', () => { const tickIndex = 10n - const liquidityDelta = 10n - - const clamm = CLAMM.at( - addressFromContractId((await fetchContractState(Invariant, invariant)).fields.clamm) - ) + const liquidityDelta = 10n as Liquidity await expectError( InvariantError.InvalidTickIndex, @@ -126,7 +122,7 @@ describe('position tests', () => { tickIndex, tickIndex, liquidityDelta, - 0n, + 0n as SqrtPrice, MAX_SQRT_PRICE ), invariant @@ -134,10 +130,10 @@ describe('position tests', () => { }) test('remove', async () => { const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 10n ** 20n + 1000n - const mint = 10n ** 10n - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) - const fee = 6n * 10n ** (PERCENTAGE_SCALE - 3n) + const supply = (10n ** 20n + 1000n) as TokenAmount + const mint = (10n ** 10n) as TokenAmount + const protocolFee = toPercentage(1n, 2n) + const fee = toPercentage(6n, 3n) const tickSpacing = 10n const invariant = await deployInvariant(admin, protocolFee) @@ -232,7 +228,7 @@ describe('position tests', () => { } const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const amount = 1000n + const amount = 1000n as TokenAmount await withdrawTokens(swapper, [tokenX, amount], [tokenY, amount]) const poolBefore = await getPool(invariant, poolKey) @@ -286,9 +282,9 @@ describe('position tests', () => { const maxTick = 177450n const minTick = -maxTick const initTick = -23028n - const initialBalance = 100000000n - const protocolFee = 0n - const fee = 2n * 10n ** (PERCENTAGE_SCALE - 4n) + const initialBalance = 100000000n as TokenAmount + const protocolFee = 0n as Percentage + const fee = toPercentage(2n, 4n) const positionOwner = await getSigner(ONE_ALPH * 1001n, 0) @@ -367,9 +363,9 @@ describe('position tests', () => { }) test('create below current tick', async () => { const initTick = -23028n - const initialBalance = 10000000000n - const protocolFee = 0n - const fee = 2n * 10n ** (PERCENTAGE_SCALE - 4n) + const initialBalance = 10000000000n as TokenAmount + const protocolFee = 0n as Percentage + const fee = (2n * 10n ** (PERCENTAGE_SCALE - 4n)) as Percentage const tickSpacing = 4n const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) @@ -454,9 +450,9 @@ describe('position tests', () => { }) test('create above current tick', async () => { const initTick = -23028n - const initialBalance = 10000000000n - const protocolFee = 0n - const fee = 2n * 10n ** (PERCENTAGE_SCALE - 4n) + const initialBalance = 10000000000n as TokenAmount + const protocolFee = 0n as Percentage + const fee = toPercentage(2n, 4n) const tickSpacing = 4n const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) diff --git a/test/contract/e2e/remove-fee-tier.test.ts b/test/contract/e2e/remove-fee-tier.test.ts index e88d3ed..cda5da6 100644 --- a/test/contract/e2e/remove-fee-tier.test.ts +++ b/test/contract/e2e/remove-fee-tier.test.ts @@ -2,7 +2,7 @@ import { ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { deployInvariant, newFeeTier } from '../../../src/utils' -import { InvariantError, PERCENTAGE_SCALE } from '../../../src/consts' +import { InvariantError } from '../../../src/consts' import { expectError, feeTierExists, @@ -10,7 +10,8 @@ import { initFeeTier, removeFeeTier } from '../../../src/testUtils' -import { FeeTier } from '../../../src/types' +import { FeeTier, Percentage } from '../../../src/types' +import { toPercentage } from '../../../src/math' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -18,7 +19,7 @@ let admin: PrivateKeyWallet describe('remove fee tier tests', () => { // 0.02% - const fee = 2n * 10n ** (PERCENTAGE_SCALE - 4n) + const fee = toPercentage(2n, 4n) const tickSpacings = [1n, 2n] let feeTier1TS: FeeTier let feeTier2TS: FeeTier @@ -30,7 +31,7 @@ describe('remove fee tier tests', () => { }) test('remove fee tier', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) await initFeeTier(invariant, admin, feeTier1TS) await initFeeTier(invariant, admin, feeTier2TS) @@ -44,7 +45,7 @@ describe('remove fee tier tests', () => { }) test('non existing', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) await initFeeTier(invariant, admin, feeTier1TS) const [tierExists] = await feeTierExists(invariant, feeTier2TS) @@ -58,7 +59,7 @@ describe('remove fee tier tests', () => { }) test('not admin', async () => { - const invariant = await deployInvariant(admin, 0n) + const invariant = await deployInvariant(admin, 0n as Percentage) await initFeeTier(invariant, admin, feeTier1TS) await initFeeTier(invariant, admin, feeTier2TS) diff --git a/test/contract/e2e/reserves.test.ts b/test/contract/e2e/reserves.test.ts index c815b2b..9be8b2c 100644 --- a/test/contract/e2e/reserves.test.ts +++ b/test/contract/e2e/reserves.test.ts @@ -2,7 +2,7 @@ import { ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { deployInvariant, newFeeTier, newPoolKey } from '../../../src/utils' -import { MAX_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' +import { MAX_SQRT_PRICE } from '../../../src/consts' import { getPool, initPool, @@ -18,7 +18,8 @@ import { initBasicPosition, initBasicSwap } from '../../../src/snippets' -import { FeeTier } from '../../../src/types' +import { FeeTier, Liquidity, SqrtPrice, TokenAmount } from '../../../src/types' +import { toPercentage, toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -26,7 +27,7 @@ let positionOwner: PrivateKeyWallet let swapper: PrivateKeyWallet let invariant: InvariantInstance describe('reserves tests - manage multiple tokens', () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) + const protocolFee = toPercentage(1n, 2n) const [fee, tickSpacing] = getBasicFeeTickSpacing() let feeTier: FeeTier @@ -41,14 +42,14 @@ describe('reserves tests - manage multiple tokens', () => { }) test('init 5 pools and open position on each of them, invariant manages 10 assets', async () => { for (let i = 0n; i < 5n; i++) { - const supply = 100n + const supply = 100n as TokenAmount const [tokenX, tokenY] = await initTokensXY(admin, supply) const poolKey = await newPoolKey(tokenX.contractId, tokenY.contractId, feeTier) await withdrawTokens(positionOwner, [tokenX, supply], [tokenY, supply]) const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) await initPool(invariant, positionOwner, tokenX, tokenY, feeTier, initSqrtPrice, initTick) const pool = await getPool(invariant, poolKey) @@ -66,7 +67,7 @@ describe('reserves tests - manage multiple tokens', () => { expect(pool).toMatchObject(expectedPool) const lowerTickIndex = -10n const upperTickIndex = 10n - const liquidityDelta = 100n + const liquidityDelta = 100n as Liquidity await initPosition( invariant, @@ -77,13 +78,13 @@ describe('reserves tests - manage multiple tokens', () => { lowerTickIndex, upperTickIndex, liquidityDelta, - 0n, + 0n as SqrtPrice, MAX_SQRT_PRICE ) } }) test('pool where assets are stored in different reserves', async () => { - const supply = 1000000n + const supply = 1000000n as TokenAmount let firstReserveId: string = '' // Perform operations on 2 pools - 4 Tokens in Reserve for (let i = 0n; i < 2n; i++) { diff --git a/test/contract/e2e/slippage.test.ts b/test/contract/e2e/slippage.test.ts index ebee7e7..465ca55 100644 --- a/test/contract/e2e/slippage.test.ts +++ b/test/contract/e2e/slippage.test.ts @@ -22,8 +22,8 @@ import { initPool } from '../../../src/testUtils' import { InvariantError, MAX_SQRT_PRICE } from '../../../src/consts' -import { calculateSqrtPrice, toLiquidity } from '../../../src/math' -import { PoolKey } from '../../../src/types' +import { calculateSqrtPrice, toLiquidity, toPercentage } from '../../../src/math' +import { PoolKey, SqrtPrice, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -34,21 +34,21 @@ let tokenY: TokenFaucetInstance let poolKey: PoolKey describe('Invariant Swap Tests', () => { - const swapAmount = 10n ** 8n + const swapAmount = (10n ** 8n) as TokenAmount const [fee, tickSpacing] = getBasicFeeTickSpacing() - const withdrawAmount = 10n ** 10n + const withdrawAmount = (10n ** 10n) as TokenAmount beforeAll(async () => { admin = await getSigner(ONE_ALPH * 1000n, 0) }) beforeEach(async () => { - invariant = await deployInvariant(admin, 10n ** 10n) + invariant = await deployInvariant(admin, toPercentage(1n, 2n)) const feeTier = await newFeeTier(fee, tickSpacing) await initFeeTier(invariant, admin, feeTier) - const tokenSupply = 10n ** 23n + const tokenSupply = (10n ** 23n) as TokenAmount ;[tokenX, tokenY] = await initTokensXY(admin, tokenSupply) positionOwner = await getSigner(ONE_ALPH * 1000n, 0) await withdrawTokens(positionOwner, [tokenX, withdrawAmount], [tokenY, withdrawAmount]) @@ -91,10 +91,10 @@ describe('Invariant Swap Tests', () => { test('test_basic_slippage', async () => { const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const swapAmount = 10n ** 8n + const swapAmount = (10n ** 8n) as TokenAmount await withdrawTokens(swapper, [tokenY, swapAmount]) - const targetSqrtPrice = 1009940000000000000000001n + const targetSqrtPrice = 1009940000000000000000001n as SqrtPrice await initSwap(invariant, swapper, poolKey, false, swapAmount, true, targetSqrtPrice) let expectedSqrtPrice = 1009940000000000000000000n @@ -113,7 +113,7 @@ describe('Invariant Swap Tests', () => { const quoteResult = await quote(invariant, poolKey, false, swapAmount, true, MAX_SQRT_PRICE) - const targetSqrtPrice = quoteResult.targetSqrtPrice - 1n + const targetSqrtPrice = (quoteResult.targetSqrtPrice - 1n) as SqrtPrice await expectError( InvariantError.PriceLimitReached, @@ -123,8 +123,8 @@ describe('Invariant Swap Tests', () => { }) test('test_swap_exact_limit', async () => { - invariant = await deployInvariant(admin, 10n ** 10n) - const tokenSupply = 10n ** 23n + invariant = await deployInvariant(admin, toPercentage(1n, 2n)) + const tokenSupply = (10n ** 23n) as TokenAmount ;[tokenX, tokenY] = await initTokensXY(admin, tokenSupply) const feeTier = await newFeeTier(fee, tickSpacing) @@ -134,7 +134,7 @@ describe('Invariant Swap Tests', () => { await initBasicPosition(invariant, positionOwner, tokenX, tokenY) - const swapAmount = 1000n + const swapAmount = 1000n as TokenAmount const swapper = await getSigner(ONE_ALPH * 1000n, 0) await withdrawTokens(swapper, [tokenX, swapAmount]) diff --git a/test/contract/e2e/swap.test.ts b/test/contract/e2e/swap.test.ts index acb3f4f..788aa9b 100644 --- a/test/contract/e2e/swap.test.ts +++ b/test/contract/e2e/swap.test.ts @@ -24,6 +24,7 @@ import { } from '../../../src/testUtils' import { InvariantError, MAX_SQRT_PRICE, MIN_SQRT_PRICE, VMError } from '../../../src/consts' import { toLiquidity, toPercentage } from '../../../src/math' +import { TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let admin: PrivateKeyWallet @@ -51,9 +52,12 @@ describe('swap tests', () => { test('x to y', async () => { const invariant = await deployInvariant(admin, protocolFee) - const positionsAmount = 2n * 10n ** 10n - const swapAmount = 1000n - const [tokenX, tokenY] = await initTokensXY(admin, positionsAmount + swapAmount) + const positionsAmount = (2n * 10n ** 10n) as TokenAmount + const swapAmount = 1000n as TokenAmount + const [tokenX, tokenY] = await initTokensXY( + admin, + (positionsAmount + swapAmount) as TokenAmount + ) const [fee, tickSpacing] = getBasicFeeTickSpacing() const feeTier = await newFeeTier(fee, tickSpacing) @@ -72,7 +76,7 @@ describe('swap tests', () => { const slippageLimit = poolBefore.sqrtPrice const liquidityDelta = toLiquidity(1000000n) - const positionAmount = positionsAmount / 2n + const positionAmount = (positionsAmount / 2n) as TokenAmount await initPosition( invariant, @@ -156,9 +160,12 @@ describe('swap tests', () => { test('y to x', async () => { const invariant = await deployInvariant(admin, protocolFee) - const positionsAmount = 2n * 10n ** 10n - const swapAmount = 1000n - const [tokenX, tokenY] = await initTokensXY(admin, positionsAmount + swapAmount) + const positionsAmount = (2n * 10n ** 10n) as TokenAmount + const swapAmount = 1000n as TokenAmount + const [tokenX, tokenY] = await initTokensXY( + admin, + (positionsAmount + swapAmount) as TokenAmount + ) const [fee, tickSpacing] = getBasicFeeTickSpacing() @@ -178,7 +185,7 @@ describe('swap tests', () => { const slippageLimit = poolBefore.sqrtPrice const liquidityDelta = toLiquidity(1000000n) - const positionAmount = positionsAmount / 2n + const positionAmount = (positionsAmount / 2n) as TokenAmount await initPosition( invariant, @@ -268,9 +275,12 @@ describe('swap tests', () => { test('not enough liquidity token x', async () => { const invariant = await deployInvariant(admin, protocolFee) - const positionsAmount = 2n * 10n ** 10n - const swapAmount = 1000n - const [tokenX, tokenY] = await initTokensXY(admin, positionsAmount + swapAmount) + const positionsAmount = (2n * 10n ** 10n) as TokenAmount + const swapAmount = 1000n as TokenAmount + const [tokenX, tokenY] = await initTokensXY( + admin, + (positionsAmount + swapAmount) as TokenAmount + ) const [fee, tickSpacing] = getBasicFeeTickSpacing() @@ -290,7 +300,7 @@ describe('swap tests', () => { const slippageLimit = poolBefore.sqrtPrice const liquidityDelta = toLiquidity(1000000n) - const positionAmount = positionsAmount / 2n + const positionAmount = (positionsAmount / 2n) as TokenAmount await initPosition( invariant, @@ -337,9 +347,12 @@ describe('swap tests', () => { test('not enough liquidity token y', async () => { const invariant = await deployInvariant(admin, protocolFee) - const positionsAmount = 2n * 10n ** 10n - const swapAmount = 1000n - const [tokenX, tokenY] = await initTokensXY(admin, positionsAmount + swapAmount) + const positionsAmount = (2n * 10n ** 10n) as TokenAmount + const swapAmount = 1000n as TokenAmount + const [tokenX, tokenY] = await initTokensXY( + admin, + (positionsAmount + swapAmount) as TokenAmount + ) const [fee, tickSpacing] = getBasicFeeTickSpacing() const feeTier = await newFeeTier(fee, tickSpacing) @@ -358,7 +371,7 @@ describe('swap tests', () => { const slippageLimit = poolBefore.sqrtPrice const liquidityDelta = toLiquidity(1000000n) - const positionAmount = positionsAmount / 2n + const positionAmount = (positionsAmount / 2n) as TokenAmount await initPosition( invariant, diff --git a/test/contract/unit/clamm.test.ts b/test/contract/unit/clamm.test.ts index d493e73..6fca64a 100644 --- a/test/contract/unit/clamm.test.ts +++ b/test/contract/unit/clamm.test.ts @@ -36,6 +36,8 @@ import { SQRT_PRICE_DENOMINATOR, VMError } from '../../../src/consts' +import { FeeGrowth, Liquidity, Percentage, SqrtPrice, TokenAmount } from '../../../src/types' +import { toFeeGrowth, toLiquidity, toPercentage, toSqrtPrice } from '../../../src/math' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -49,26 +51,26 @@ describe('clamm tests', () => { test('fee growth from fee', async () => { const clamm = await deployCLAMM(sender) { - const liquidity = 10n ** 5n - const amount = 1n + const liquidity = toLiquidity(1n) + const amount = 1n as TokenAmount const result = await feeGrowthFromFee(clamm, liquidity, amount) expect(result).toStrictEqual(10000000000000000000000000000n) } { - const liquidity = 2n * 10n ** 5n - const amount = 1n + const liquidity = toLiquidity(2n) + const amount = 1n as TokenAmount const result = await feeGrowthFromFee(clamm, liquidity, amount) expect(result).toStrictEqual(5n * 10n ** 27n) } { - const liquidity = ((1n << 64n) - 1n) * 10n ** 5n - const amount = 1n + const liquidity = toLiquidity((1n << 64n) - 1n) + const amount = 1n as TokenAmount const result = await feeGrowthFromFee(clamm, liquidity, amount) expect(result).toStrictEqual(542101086n) } { - const liquidity = 100n * 10n ** 5n - const amount = 1000000n + const liquidity = toLiquidity(100n) + const amount = 1000000n as TokenAmount const result = await feeGrowthFromFee(clamm, liquidity, amount) expect(result).toStrictEqual(10000n * 10n ** 28n) } @@ -85,9 +87,10 @@ describe('clamm tests', () => { const sqrtPriceLower = await calculateSqrtPrice(clamm, sqrtPriceLowerIndex) const maxDeltaSqrtPrice = sqrtPriceUpper - sqrtPriceLower - const maxLiquidity = (1n << 256n) - 1n - const maxToken = - (maxLiquidity * maxDeltaSqrtPrice) / LIQUIDITY_DENOMINATOR / SQRT_PRICE_DENOMINATOR + const maxLiquidity = ((1n << 256n) - 1n) as Liquidity + const maxToken = ((maxLiquidity * maxDeltaSqrtPrice) / + LIQUIDITY_DENOMINATOR / + SQRT_PRICE_DENOMINATOR) as TokenAmount const feeGrowth = await feeGrowthFromFee(clamm, maxLiquidity, maxToken) expect(feeGrowth).toStrictEqual(473129365723326089999999999999999n) @@ -96,12 +99,19 @@ describe('clamm tests', () => { { const basisPoint = 10000n const minToken = 1n - const maxLiquidity = minToken * FEE_GROWTH_DENOMINATOR * LIQUIDITY_DENOMINATOR * basisPoint - const feeGrowth = await feeGrowthFromFee(clamm, maxLiquidity, minToken + basisPoint) + const maxLiquidity = (minToken * + FEE_GROWTH_DENOMINATOR * + LIQUIDITY_DENOMINATOR * + basisPoint) as Liquidity + const feeGrowth = await feeGrowthFromFee( + clamm, + maxLiquidity, + (minToken + basisPoint) as TokenAmount + ) // outside of domain trigger overflow due to result not fit into FeeGrowth { - const liquidity = 1n - const fee = (1n << 256n) - 1n + const liquidity = 1n as Liquidity + const fee = ((1n << 256n) - 1n) as TokenAmount await expectError( ArithmeticError.CastOverflow, @@ -111,15 +121,15 @@ describe('clamm tests', () => { } // amount = 0 { - const liquidity = 1000n * 10n ** 5n - const fee = 0n + const liquidity = toLiquidity(1000n) + const fee = 0n as TokenAmount const feeGrowth = await feeGrowthFromFee(clamm, liquidity, fee) expect(feeGrowth).toStrictEqual(0n) } // L = 0 { - const liquidity = 0n - const fee = 1100n + const liquidity = 0n as Liquidity + const fee = 1100n as TokenAmount await expectError( ArithmeticError.MulNotPositiveDenominator, feeGrowthFromFee(clamm, liquidity, fee), @@ -133,17 +143,17 @@ describe('clamm tests', () => { // Equal { - const amount = 100n - const liquidity = 1000000n * 10n ** 5n + const amount = 100n as TokenAmount + const liquidity = toLiquidity(1000000n) const feeGrowth = await feeGrowthFromFee(clamm, liquidity, amount) const out = await toFee(clamm, liquidity, feeGrowth) expect(out).toStrictEqual(100n) } // Greater Liquidity { - const amount = 100n - const liquidityBefore = 1000000n * 10n ** 5n - const liquidityAfter = 10000000n * 10n ** 5n + const amount = 100n as TokenAmount + const liquidityBefore = toLiquidity(1000000n) + const liquidityAfter = toLiquidity(10000000n) const feeGrowth = await feeGrowthFromFee(clamm, liquidityBefore, amount) const out = await toFee(clamm, liquidityAfter, feeGrowth) @@ -151,8 +161,8 @@ describe('clamm tests', () => { } // huge liquidity { - const amount = 100000000000000n - const liquidity = (1n << 77n) * 10n ** 5n + const amount = 100000000000000n as TokenAmount + const liquidity = toLiquidity(1n << 77n) const feeGrowth = await feeGrowthFromFee(clamm, liquidity, amount) // real 6.61744490042422139897126953655970282852649688720703125 × 10^-10 // expected 6617444900424221398 @@ -167,8 +177,8 @@ describe('clamm tests', () => { const clamm = await deployCLAMM(sender) // overflowing mul { - const amount = 600000000000000000n - const liquidity = 10000000000000000000n * 10n ** 5n + const amount = 600000000000000000n as TokenAmount + const liquidity = toLiquidity(10000000000000000000n) const feeGrowth = await feeGrowthFromFee(clamm, liquidity, amount) expect(feeGrowth).toStrictEqual(600000000000000000000000000n) const out = await toFee(clamm, liquidity, feeGrowth) @@ -176,8 +186,8 @@ describe('clamm tests', () => { } // max value inside domain { - const liquidity = (1n << 256n) - 1n - const feeGrowth = 100000n * 10n ** 28n + const liquidity = ((1n << 256n) - 1n) as Liquidity + const feeGrowth = (100000n * 10n ** 28n) as FeeGrowth const out = await toFee(clamm, liquidity, feeGrowth) expect(out).toStrictEqual( 115792089237316195423570985008687907853269984665640564039457584007913129639935n @@ -185,21 +195,21 @@ describe('clamm tests', () => { } // Overflow { - const liquidity = (1n << 256n) - 1n - const feeGrowth = (1n << 256n) - 1n + const liquidity = ((1n << 256n) - 1n) as Liquidity + const feeGrowth = ((1n << 256n) - 1n) as FeeGrowth await expectError(ArithmeticError.CastOverflow, toFee(clamm, liquidity, feeGrowth), clamm) } // FeeGrowth = 0 { - const liquidity = 1000n * 10n ** 5n - const feeGrowth = 0n + const liquidity = toLiquidity(1000n) + const feeGrowth = 0n as FeeGrowth const out = await toFee(clamm, liquidity, feeGrowth) expect(out).toStrictEqual(0n) } // Liquidity = 0 { - const liquidity = 0n - const feeGrowth = 1000n * 10n ** 28n + const liquidity = 0n as Liquidity + const feeGrowth = toFeeGrowth(1000n) const out = await toFee(clamm, liquidity, feeGrowth) expect(out).toStrictEqual(0n) } @@ -207,7 +217,7 @@ describe('clamm tests', () => { test('tick from sqrt price', async () => { const clamm = await deployCLAMM(sender) { - const sqrtPrice = 999006987054867461743028n + const sqrtPrice = 999006987054867461743028n as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPrice, 10n) expect(result).toBe(-20n) } @@ -328,27 +338,27 @@ describe('clamm tests', () => { clamm = await deployCLAMM(sender) }) test('zero at zero liquidity', async () => { - const sqrtPriceA = 1n * 10n ** 24n - const sqrtPriceB = 2n * 10n ** 24n - const liquidity = 0n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(2n) + const liquidity = 0n as Liquidity const resultUp = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) expect(resultUp).toEqual(0n) expect(resultDown).toEqual(0n) }) test('equal at equal liquidity', async () => { - const sqrtPriceA = 1n * 10n ** 24n - const sqrtPriceB = 2n * 10n ** 24n - const liquidity = 2n * 10n ** 5n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(2n) + const liquidity = toLiquidity(2n) const resultUp = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) expect(resultUp).toEqual(1n) expect(resultDown).toEqual(1n) }) test('complex', async () => { - const sqrtPriceA = 234878324943782000000000000n - const sqrtPriceB = 87854456421658000000000000n - const liquidity = 983983249092n + const sqrtPriceA = 234878324943782000000000000n as SqrtPrice + const sqrtPriceB = 87854456421658000000000000n as SqrtPrice + const liquidity = 983983249092n as Liquidity const resultUp = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) // 7010.8199533068819376891841727789301497024557314488455622925765280 @@ -356,34 +366,34 @@ describe('clamm tests', () => { expect(resultDown).toEqual(70108n) }) test('big', async () => { - const sqrtPriceA = 1n * 10n ** 24n - const sqrtPriceB = 5n * 10n ** 23n - const liquidity = (2n ** 64n - 1n) * 10n ** 5n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(5n, 1n) + const liquidity = toLiquidity(2n ** 64n - 1n) const resultUp = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) expect(resultUp).toEqual(2n ** 64n - 1n) expect(resultDown).toEqual(2n ** 64n - 1n) }) test('shouldnt overflow in intermediate operations', async () => { - const sqrtPriceA = 1n * 10n ** 24n - const sqrtPriceB = 5n * 10n ** 23n - const liquidity = (1n << 256n) - 1n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(5n, 1n) + const liquidity = ((1n << 256n) - 1n) as Liquidity await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) }) test('huge liquidity', async () => { - const sqrtPriceA = 1n * 10n ** 24n - const sqrtPriceB = 1n * 10n ** 24n + 1000000n - const liquidity = (1n << 80n) * 10n ** 5n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = (toSqrtPrice(1n) + 1000000n) as SqrtPrice + const liquidity = toLiquidity(1n << 80n) await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) await getDeltaX(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) }) }) describe('get delta x - domain', () => { let clamm: CLAMMInstance - const almostMinSqrtPrice = 15259695000000000000n - const maxLiquidity = (1n << 256n) - 1n - const minLiquidity = 1n + const almostMinSqrtPrice = 15259695000000000000n as SqrtPrice + const maxLiquidity = ((1n << 256n) - 1n) as Liquidity + const minLiquidity = 1n as Liquidity beforeAll(async () => { clamm = await deployCLAMM(sender) @@ -511,8 +521,8 @@ describe('clamm tests', () => { ) }) test('minimal price difference', async () => { - const almostMaxSqrtPrice = MAX_SQRT_PRICE - 1n * 10n ** 24n - const almostMinSqrtPrice = MIN_SQRT_PRICE + 1n * 10n ** 24n + const almostMaxSqrtPrice = (MAX_SQRT_PRICE - toSqrtPrice(1n)) as SqrtPrice + const almostMinSqrtPrice = (MIN_SQRT_PRICE + toSqrtPrice(1n)) as SqrtPrice const paramsUpperBound = { sqrtPriceA: MAX_SQRT_PRICE, sqrtPriceB: almostMaxSqrtPrice, @@ -548,7 +558,7 @@ describe('clamm tests', () => { const params = { sqrtPriceA: MAX_SQRT_PRICE, sqrtPriceB: MIN_SQRT_PRICE, - liquidity: 0n + liquidity: 0n as Liquidity } const resultUp = await getDeltaX( clamm, @@ -577,27 +587,27 @@ describe('clamm tests', () => { }) test('zero at zero liquidity', async () => { - const sqrtPriceA = 1_000000000000000000000000n - const sqrtPriceB = 1_000000000000000000000000n - const liquidity = 0n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(1n) + const liquidity = 0n as Liquidity const result = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) expect(result).toEqual(0n) }) test('equal at equal liquidity', async () => { - const sqrtPriceA = 1_000000000000000000000000n - const sqrtPriceB = 2_000000000000000000000000n - const liquidity = 2_00000n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(2n) + const liquidity = toLiquidity(2n) const result = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) expect(result).toEqual(2n) }) test('big numbers', async () => { - const sqrtPriceA = 234_878324943782000000000000n - const sqrtPriceB = 87_854456421658000000000000n - const liquidity = 9839832_49092n + const sqrtPriceA = 234_878324943782000000000000n as SqrtPrice + const sqrtPriceB = 87_854456421658000000000000n as SqrtPrice + const liquidity = 9839832_49092n as Liquidity const resultUp = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) @@ -607,9 +617,9 @@ describe('clamm tests', () => { }) test('big', async () => { - const sqrtPriceA = 1_000000000000000000000000n - const sqrtPriceB = 2_000000000000000000000000n - const liquidity = (2n ** 64n - 1n) * 1_00000n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = toSqrtPrice(2n) + const liquidity = toLiquidity(2n ** 64n - 1n) const resultUp = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) @@ -619,9 +629,9 @@ describe('clamm tests', () => { }) test('overflow', async () => { - const sqrtPriceA = 1_000000000000000000000000n - const sqrtPriceB = 2n ** 256n - 1n - const liquidity = 2n ** 256n - 1n + const sqrtPriceA = toSqrtPrice(1n) + const sqrtPriceB = (2n ** 256n - 1n) as SqrtPrice + const liquidity = (2n ** 256n - 1n) as Liquidity await expectError( ArithmeticError.CastOverflow, @@ -636,9 +646,9 @@ describe('clamm tests', () => { }) test('huge liquidity', async () => { - const sqrtPriceA = 1_000000000000000000000000n - const sqrtPriceB = 1_000000000000000001000000n - const liquidity = 2n ** 256n - 1n + const sqrtPriceA = 1_000000000000000000000000n as SqrtPrice + const sqrtPriceB = 1_000000000000000001000000n as SqrtPrice + const liquidity = (2n ** 256n - 1n) as Liquidity const resultUp = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, true) const resultDown = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, liquidity, false) @@ -650,8 +660,8 @@ describe('clamm tests', () => { describe('get delta y - domain', () => { let clamm: CLAMMInstance - const minLiquidity = 1n - const maxLiquidity = 2n ** 256n - 1n + const minLiquidity = 1n as Liquidity + const maxLiquidity = (2n ** 256n - 1n) as Liquidity beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -673,7 +683,7 @@ describe('clamm tests', () => { const result = await getDeltaY( clamm, MAX_SQRT_PRICE, - MAX_SQRT_PRICE - 1n, + (MAX_SQRT_PRICE - 1n) as SqrtPrice, minLiquidity, false ) @@ -685,7 +695,7 @@ describe('clamm tests', () => { const sqrtPriceA = MAX_SQRT_PRICE const sqrtPriceB = MIN_SQRT_PRICE - const result = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, 0n, true) + const result = await getDeltaY(clamm, sqrtPriceA, sqrtPriceB, 0n as Liquidity, true) expect(result).toStrictEqual(0n) }) @@ -704,9 +714,9 @@ describe('clamm tests', () => { const clamm = await deployCLAMM(sender) { - const startingSqrtPrice = 1n * SQRT_PRICE_DENOMINATOR - const liquidity = 1n * LIQUIDITY_DENOMINATOR - const y = 1n + const startingSqrtPrice = SQRT_PRICE_DENOMINATOR + const liquidity = LIQUIDITY_DENOMINATOR + const y = 1n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -717,9 +727,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual(2n * SQRT_PRICE_DENOMINATOR) } { - const startingSqrtPrice = 1n * SQRT_PRICE_DENOMINATOR - const liquidity = 2n * LIQUIDITY_DENOMINATOR - const y = 3n + const startingSqrtPrice = SQRT_PRICE_DENOMINATOR + const liquidity = (2n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 3n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -730,9 +740,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual(25n * 10n ** 23n) } { - const startingSqrtPrice = 2n * SQRT_PRICE_DENOMINATOR - const liquidity = 3n * LIQUIDITY_DENOMINATOR - const y = 5n + const startingSqrtPrice = (2n * SQRT_PRICE_DENOMINATOR) as SqrtPrice + const liquidity = (3n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 5n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -743,9 +753,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual((11n * SQRT_PRICE_DENOMINATOR) / 3n) } { - const startingSqrtPrice = 24234n * SQRT_PRICE_DENOMINATOR - const liquidity = 3000n * LIQUIDITY_DENOMINATOR - const y = 5000n + const startingSqrtPrice = (24234n * SQRT_PRICE_DENOMINATOR) as SqrtPrice + const liquidity = (3000n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 5000n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -756,9 +766,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual((72707n * SQRT_PRICE_DENOMINATOR) / 3n) } { - const startingSqrtPrice = 1n * SQRT_PRICE_DENOMINATOR - const liquidity = 2n * LIQUIDITY_DENOMINATOR - const y = 1n + const startingSqrtPrice = (1n * SQRT_PRICE_DENOMINATOR) as SqrtPrice + const liquidity = (2n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 1n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -769,9 +779,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual(5n * 10n ** 23n) } { - const startingSqrtPrice = 100000n * SQRT_PRICE_DENOMINATOR - const liquidity = 500000000n * LIQUIDITY_DENOMINATOR - const y = 4000n + const startingSqrtPrice = (100000n * SQRT_PRICE_DENOMINATOR) as SqrtPrice + const liquidity = (500000000n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 4000n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -782,9 +792,9 @@ describe('clamm tests', () => { expect(nextSqrtPrice).toEqual(99999999992000000000000000000n) } { - const startingSqrtPrice = 3n * SQRT_PRICE_DENOMINATOR - const liquidity = 222n * LIQUIDITY_DENOMINATOR - const y = 37n + const startingSqrtPrice = (3n * SQRT_PRICE_DENOMINATOR) as SqrtPrice + const liquidity = (222n * LIQUIDITY_DENOMINATOR) as Liquidity + const y = 37n as TokenAmount const nextSqrtPrice = await getNextSqrtPriceYDown( clamm, startingSqrtPrice, @@ -798,17 +808,15 @@ describe('clamm tests', () => { test('get next sqrt price y down - domain', async () => { const clamm = await deployCLAMM(sender) - const minY = 1n - const maxY = (1n << 256n) - 1n - const MAX_SQRT_PRICE = 65535383934512647000000000000n - const MIN_SQRT_PRICE = 15258932000000000000n - const almostMinSqrtPrice = MIN_SQRT_PRICE + 1n - const almostMaxSqrtPrice = MAX_SQRT_PRICE - 1n - const minSqrtPriceOutsideDomain = 1n - const minLiquidity = 1n - const maxLiquidity = (1n << 256n) - 1n + const minY = 1n as TokenAmount + const maxY = ((1n << 256n) - 1n) as TokenAmount + const almostMinSqrtPrice = (MIN_SQRT_PRICE + 1n) as SqrtPrice + const almostMaxSqrtPrice = (MAX_SQRT_PRICE - 1n) as SqrtPrice + const minSqrtPriceOutsideDomain = 1n as SqrtPrice + const minLiquidity = 1n as Liquidity + const maxLiquidity = ((1n << 256n) - 1n) as Liquidity const minOverflowTokenY = 115792089237316195423570985008687907853269984665575031n - const oneLiquidity = 1n * 10n ** 5n + const oneLiquidity = toLiquidity(1n) // Min value inside domain { @@ -817,7 +825,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, liquidity: maxLiquidity, - y: minY + (1n << 128n) * (1n << 32n), + y: (minY + (1n << 128n) * (1n << 32n)) as TokenAmount, addY: true } const nextSqrtPrice = await getNextSqrtPriceYDown( @@ -854,7 +862,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MAX_SQRT_PRICE, liquidity: maxLiquidity, - y: minY + (1n << 128n) * (1n << 32n), + y: (minY + (1n << 128n) * (1n << 32n)) as TokenAmount, addY: false } const nextSqrtPrice = await getNextSqrtPriceYDown( @@ -871,7 +879,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMaxSqrtPrice, liquidity: maxLiquidity, - y: minY + 600000000n, + y: (minY + 600000000n) as TokenAmount, addY: true } const nextSqrtPrice = await getNextSqrtPriceYDown( @@ -919,7 +927,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MAX_SQRT_PRICE, liquidity: oneLiquidity, - y: minOverflowTokenY - 2n, + y: (minOverflowTokenY - 2n) as TokenAmount, addY: true } @@ -932,7 +940,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: minSqrtPriceOutsideDomain, liquidity: oneLiquidity, - y: minOverflowTokenY - 2n, + y: (minOverflowTokenY - 2n) as TokenAmount, addY: false } await expectVMError( @@ -943,8 +951,8 @@ describe('clamm tests', () => { } // Quotient overflow { - const minYOverflowDecimalExtension = 1n << 225n - const irrelevantSqrtPrice = 1n + const minYOverflowDecimalExtension = (1n << 225n) as TokenAmount + const irrelevantSqrtPrice = 1n as SqrtPrice const irrelevantLiquidity = oneLiquidity { const params = { @@ -994,7 +1002,7 @@ describe('clamm tests', () => { { const params = { startingSqrtPrice: MIN_SQRT_PRICE, - liquidity: 0n, + liquidity: 0n as Liquidity, y: minY, addY: true } @@ -1009,7 +1017,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, liquidity: maxLiquidity, - y: 0n, + y: 0n as TokenAmount, addY: true } const nextSqrtPrice = await getNextSqrtPriceYDown( @@ -1059,71 +1067,71 @@ describe('clamm tests', () => { const clamm = await deployCLAMM(sender) // 0% fee { - const expectedAmountOut = 100n - const slippage = 0n + const expectedAmountOut = 100n as TokenAmount + const slippage = 0n as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(100n) } // 0.1% fee { - const expectedAmountOut = 100n - const slippage = 10n ** 9n + const expectedAmountOut = 100n as TokenAmount + const slippage = (10n ** 9n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(100n) } // 0.9% fee { - const expectedAmountOut = 123n - const slippage = 9n * 10n ** 9n + const expectedAmountOut = 123n as TokenAmount + const slippage = (9n * 10n ** 9n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(122n) } // 1% fee { - const expectedAmountOut = 100n - const slippage = 10n ** 10n + const expectedAmountOut = 100n as TokenAmount + const slippage = (10n ** 10n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(99n) } // 3% fee { - const expectedAmountOut = 100n - const slippage = 3n * 10n ** 10n + const expectedAmountOut = 100n as TokenAmount + const slippage = (3n * 10n ** 10n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(97n) } // 5% fee { - const expectedAmountOut = 100n - const slippage = 5n * 10n ** 10n + const expectedAmountOut = 100n as TokenAmount + const slippage = (5n * 10n ** 10n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(95n) } // 10% fee { - const expectedAmountOut = 100n - const slippage = 10n ** 11n + const expectedAmountOut = 100n as TokenAmount + const slippage = (10n ** 11n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(90n) } // 20% fee { - const expectedAmountOut = 100n - const slippage = 2n * 10n ** 11n + const expectedAmountOut = 100n as TokenAmount + const slippage = (2n * 10n ** 11n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(80n) } // 50% fee { - const expectedAmountOut = 100n - const slippage = 5n * 10n ** 11n + const expectedAmountOut = 100n as TokenAmount + const slippage = (5n * 10n ** 11n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(50n) } // 100% fee { - const expectedAmountOut = 100n - const slippage = 10n ** 12n + const expectedAmountOut = 100n as TokenAmount + const slippage = (10n ** 12n) as Percentage const result = await calculateMinAmountOut(clamm, expectedAmountOut, slippage) expect(result).toEqual(0n) } @@ -1131,10 +1139,10 @@ describe('clamm tests', () => { test('calculate min amount out - domain', async () => { const clamm = await deployCLAMM(sender) - const minAmount = 0n - const maxAmount = (1n << 256n) - 1n - const minFee = 0n - const maxFee = 10n ** 12n + const minAmount = 0n as TokenAmount + const maxAmount = ((1n << 256n) - 1n) as TokenAmount + const minFee = 0n as Percentage + const maxFee = (10n ** 12n) as Percentage // min amount min fee { const expectedAmountOut = minAmount @@ -1169,12 +1177,12 @@ describe('clamm tests', () => { test('is enough amount to change price - domain', async () => { const clamm = await deployCLAMM(sender) - const zeroLiquidity = 0n - const maxFee = 10n ** 12n - const maxAmount = (1n << 256n) - 1n - const minAmount = 1n - const minLiquidity = 1n - const minFee = 0n + const zeroLiquidity = 0n as Liquidity + const maxFee = (10n ** 12n) as Percentage + const maxAmount = ((1n << 256n) - 1n) as TokenAmount + const minAmount = 1n as TokenAmount + const minLiquidity = 1n as Liquidity + const minFee = 0n as Percentage // max fee { const params = { @@ -1270,16 +1278,16 @@ describe('clamm tests', () => { describe('calculate fee growth inside', () => { let clamm: CLAMMInstance - const globalFeeGrowthX = 15_0000000000000000000000000000n - const globalFeeGrowthY = 15_0000000000000000000000000000n + const globalFeeGrowthX = toFeeGrowth(15n) + const globalFeeGrowthY = toFeeGrowth(15n) const tickLowerIndex = -2n - const tickLowerFeeGrowthOutsideX = 0n - const tickLowerFeeGrowthOutsideY = 0n + const tickLowerFeeGrowthOutsideX = 0n as FeeGrowth + const tickLowerFeeGrowthOutsideY = 0n as FeeGrowth const tickUpperIndex = 2n - const tickUpperFeeGrowthOutsideX = 0n - const tickUpperFeeGrowthOutsideY = 0n + const tickUpperFeeGrowthOutsideX = 0n as FeeGrowth + const tickUpperFeeGrowthOutsideY = 0n as FeeGrowth beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -1377,11 +1385,11 @@ describe('clamm tests', () => { test('sqrt price above ticks, liquidity outside upper tick', async () => { const tickCurrent = 3n - const tickUpperFeeGrowthOutsideX = 1n - const tickUpperFeeGrowthOutsideY = 2n + const tickUpperFeeGrowthOutsideX = 1n as FeeGrowth + const tickUpperFeeGrowthOutsideY = 2n as FeeGrowth - const globalFeeGrowthX = 5_0000000000000000000000000000n - const globalFeeGrowthY = 5_0000000000000000000000000000n + const globalFeeGrowthX = toFeeGrowth(5n) + const globalFeeGrowthY = toFeeGrowth(5n) // current tick upper range // lower upper current @@ -1408,8 +1416,8 @@ describe('clamm tests', () => { test('sqrt price in between ticks, liquidity outside upper tick', async () => { const tickCurrent = 0n - const tickUpperFeeGrowthOutsideX = 2_0000000000000000000000000000n - const tickUpperFeeGrowthOutsideY = 3_0000000000000000000000000000n + const tickUpperFeeGrowthOutsideX = toFeeGrowth(2n) + const tickUpperFeeGrowthOutsideY = toFeeGrowth(3n) // current tick inside range // lower current upper @@ -1436,8 +1444,8 @@ describe('clamm tests', () => { test('sqrt price in between ticks, liquidity outside lower tick', async () => { const tickCurrent = 0n - const tickLowerFeeGrowthOutsideX = 2_0000000000000000000000000000n - const tickLowerFeeGrowthOutsideY = 3_0000000000000000000000000000n + const tickLowerFeeGrowthOutsideX = toFeeGrowth(2n) + const tickLowerFeeGrowthOutsideY = toFeeGrowth(3n) // current tick inside range // lower current upper @@ -1466,16 +1474,16 @@ describe('clamm tests', () => { let clamm: CLAMMInstance const tickCurrent = 0n - const globalFeeGrowthX = 20_0000000000000000000000000000n - const globalFeeGrowthY = 20_0000000000000000000000000000n + const globalFeeGrowthX = toFeeGrowth(20n) + const globalFeeGrowthY = toFeeGrowth(20n) const tickLowerIndex = -20n - const tickLowerFeeGrowthOutsideX = 20_0000000000000000000000000000n - const tickLowerFeeGrowthOutsideY = 20_0000000000000000000000000000n + const tickLowerFeeGrowthOutsideX = toFeeGrowth(20n) + const tickLowerFeeGrowthOutsideY = toFeeGrowth(20n) const tickUpperIndex = -10n - const tickUpperFeeGrowthOutsideX = 15_0000000000000000000000000000n - const tickUpperFeeGrowthOutsideY = 15_0000000000000000000000000000n + const tickUpperFeeGrowthOutsideX = toFeeGrowth(15n) + const tickUpperFeeGrowthOutsideY = toFeeGrowth(15n) beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -1568,8 +1576,8 @@ describe('clamm tests', () => { test('current tick between lower tick and upper tick', async () => { const currentTickIndex = 2n - const currentSqrtPrice = 1_000140000000000000000000n - const liquidityDelta = 5000000_00000n + const currentSqrtPrice = 1_000140000000000000000000n as SqrtPrice + const liquidityDelta = toLiquidity(5000000n) const liquiditySign = true const upperTick = 3n const lowerTick = 0n @@ -1588,8 +1596,8 @@ describe('clamm tests', () => { test('current tick in the middle between lower tick and upper tick', async () => { const currentTickIndex = 2n - const currentSqrtPrice = 1_000140000000000000000000n - const liquidityDelta = 5000000_00000n + const currentSqrtPrice = 1_000140000000000000000000n as SqrtPrice + const liquidityDelta = toLiquidity(5000000n) const liquiditySign = true const upperTick = 4n const lowerTick = 0n @@ -1608,8 +1616,8 @@ describe('clamm tests', () => { test('current tick smaller than lower tick', async () => { const currentTickIndex = 0n - const currentSqrtPrice = 1_000000000000000000000000n - const liquidityDelta = 10_00000n + const currentSqrtPrice = toSqrtPrice(1n) + const liquidityDelta = toLiquidity(10n) const liquiditySign = true const upperTick = 4n const lowerTick = 2n @@ -1628,8 +1636,8 @@ describe('clamm tests', () => { test('current tick greater than upper tick', async () => { const currentTickIndex = 6n - const currentSqrtPrice = 1_000000000000000000000000n - const liquidityDelta = 10_00000n + const currentSqrtPrice = toSqrtPrice(1n) + const liquidityDelta = toLiquidity(10n) const liquiditySign = true const upperTick = 4n const lowerTick = 2n @@ -1649,7 +1657,7 @@ describe('clamm tests', () => { describe('calculate amount delta - domain', () => { let clamm: CLAMMInstance - let maxLiquidity = MAX_U256 + let maxLiquidity = MAX_U256 as Liquidity beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -1657,7 +1665,7 @@ describe('clamm tests', () => { test('max x', async () => { const currentTickIndex = GLOBAL_MIN_TICK - const currentSqrtPrice = 1_000000000000000000000000n + const currentSqrtPrice = toSqrtPrice(1n) const liquidityDelta = maxLiquidity const liquiditySign = true const upperTick = GLOBAL_MAX_TICK @@ -1681,7 +1689,7 @@ describe('clamm tests', () => { test('max y', async () => { const currentTickIndex = GLOBAL_MAX_TICK - const currentSqrtPrice = 1_000000000000000000000000n + const currentSqrtPrice = toSqrtPrice(1n) const liquidityDelta = maxLiquidity const liquiditySign = true const upperTick = GLOBAL_MAX_TICK - 1n @@ -1705,8 +1713,8 @@ describe('clamm tests', () => { test('delta liquidity = 0', async () => { const currentTickIndex = 2n - const currentSqrtPrice = 1_000140000000000000000000n - const liquidityDelta = 0n + const currentSqrtPrice = 1_000140000000000000000000n as SqrtPrice + const liquidityDelta = 0n as Liquidity const liquiditySign = true const upperTick = 4n const lowerTick = 0n @@ -1725,8 +1733,8 @@ describe('clamm tests', () => { test('error handling', async () => { const currentTickIndex = 0n - const currentSqrtPrice = 1_000140000000000000000000n - const liquidityDelta = 0n + const currentSqrtPrice = 1_000140000000000000000000n as SqrtPrice + const liquidityDelta = 0n as Liquidity const liquiditySign = true const upperTick = 4n const lowerTick = 10n @@ -1748,8 +1756,8 @@ describe('clamm tests', () => { test('all max', async () => { const currentTickIndex = 0n - const currentSqrtPrice = MAX_U256 - const liquidityDelta = MAX_U256 + const currentSqrtPrice = MAX_U256 as SqrtPrice + const liquidityDelta = MAX_U256 as Liquidity const liquiditySign = true const upperTick = GLOBAL_MAX_TICK const lowerTick = GLOBAL_MIN_TICK @@ -1777,63 +1785,63 @@ describe('clamm tests', () => { }) test('add 1', async () => { - const startingSqrtPrice = 1_000000000000000000000000n - const liquidity = 1_00000n - const x = 1n + const startingSqrtPrice = toSqrtPrice(1n) + const liquidity = toLiquidity(1n) + const x = 1n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, true) expect(result).toEqual(500000000000000000000000n) }) test('add 2', async () => { - const startingSqrtPrice = 1_000000000000000000000000n - const liquidity = 2_00000n - const x = 3n + const startingSqrtPrice = toSqrtPrice(1n) + const liquidity = toLiquidity(2n) + const x = 3n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, true) expect(result).toEqual(400000000000000000000000n) }) test('add 3', async () => { - const startingSqrtPrice = 2_000000000000000000000000n - const liquidity = 3_00000n - const x = 5n + const startingSqrtPrice = toSqrtPrice(2n) + const liquidity = toLiquidity(3n) + const x = 5n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, true) expect(result).toEqual(461538461538461538461539n) }) test('add 4', async () => { - const startingSqrtPrice = 24234_000000000000000000000000n - const liquidity = 3000_00000n - const x = 5000n + const startingSqrtPrice = toSqrtPrice(24234n) + const liquidity = toLiquidity(3000n) + const x = 5000n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, true) expect(result).toEqual(599985145205615112277488n) }) test('sub 1', async () => { - const startingSqrtPrice = 1_000000000000000000000000n - const liquidity = 2_00000n - const x = 1n + const startingSqrtPrice = toSqrtPrice(1n) + const liquidity = toLiquidity(2n) + const x = 1n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, false) expect(result).toEqual(2_000000000000000000000000n) }) test('sub 2', async () => { - const startingSqrtPrice = 100000_000000000000000000000000n - const liquidity = 500000000_00000n - const x = 4000n + const startingSqrtPrice = toSqrtPrice(100000n) + const liquidity = toLiquidity(500000000n) + const x = 4000n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, false) expect(result).toEqual(500000_000000000000000000000000n) }) test('sub 3', async () => { - const startingSqrtPrice = 3_333333333333333333333333n - const liquidity = 222_22222n - const x = 37n + const startingSqrtPrice = 3_333333333333333333333333n as SqrtPrice + const liquidity = 222_22222n as Liquidity + const x = 37n as TokenAmount const result = await getNextSqrtPriceXUp(clamm, startingSqrtPrice, liquidity, x, false) expect(result).toEqual(7490636797542399944773031n) @@ -1842,12 +1850,12 @@ describe('clamm tests', () => { describe('get next sqrt price x up - domain', () => { let clamm: CLAMMInstance - const maxLiquidity = MAX_U256 - const minLiquidity = 1n - const maxX = MAX_U256 - const minX = 1n - const almostMinSqrtPrice = 15258932000000000001n - const almostMaxSqrtPrice = 65535383934512646999999999999n + const maxLiquidity = MAX_U256 as Liquidity + const minLiquidity = 1n as Liquidity + const maxX = MAX_U256 as TokenAmount + const minX = 1n as TokenAmount + const almostMinSqrtPrice = 15258932000000000001n as SqrtPrice + const almostMaxSqrtPrice = 65535383934512646999999999999n as SqrtPrice beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -1857,7 +1865,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, liquidity: maxLiquidity, - x: 600000000n, + x: 600000000n as TokenAmount, addX: false } @@ -1875,7 +1883,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMinSqrtPrice, liquidity: maxLiquidity, - x: (2n ** 128n - 1n) * 2n ** 64n, + x: ((2n ** 128n - 1n) * 2n ** 64n) as TokenAmount, addX: true } const result = await getNextSqrtPriceXUp( @@ -1892,7 +1900,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MAX_SQRT_PRICE, liquidity: maxLiquidity, - x: 2n ** 128n - 1n, + x: (2n ** 128n - 1n) as TokenAmount, addX: true } const result = await getNextSqrtPriceXUp( @@ -1909,7 +1917,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMaxSqrtPrice, liquidity: maxLiquidity, - x: 2n ** 128n - 1n, + x: (2n ** 128n - 1n) as TokenAmount, addX: false } const result = await getNextSqrtPriceXUp( @@ -1979,7 +1987,7 @@ describe('clamm tests', () => { test('liquidity is zero', async () => { const params = { startingSqrtPrice: MAX_SQRT_PRICE, - liquidity: 0n, + liquidity: 0n as Liquidity, x: minX, addX: true } @@ -1997,7 +2005,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MAX_SQRT_PRICE, liquidity: maxLiquidity, - x: 0n, + x: 0n as TokenAmount, addX: true } const result = await getNextSqrtPriceXUp( @@ -2013,11 +2021,11 @@ describe('clamm tests', () => { describe('next sqrt price from input - domain', () => { let clamm: CLAMMInstance - const maxLiquidity = MAX_U256 - const minLiquidity = 1n - const maxAmount = MAX_U256 - const almostMaxSqrtPrice = MAX_SQRT_PRICE - 1n - const almostMinSqrtPrice = MIN_SQRT_PRICE + 1n + const maxLiquidity = MAX_U256 as Liquidity + const minLiquidity = 1n as Liquidity + const maxAmount = MAX_U256 as TokenAmount + const almostMaxSqrtPrice = (MAX_SQRT_PRICE - 1n) as SqrtPrice + const almostMinSqrtPrice = (MIN_SQRT_PRICE + 1n) as SqrtPrice beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -2027,7 +2035,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMaxSqrtPrice, liquidity: maxLiquidity, - amount: (2n ** 128n - 1n) * 10n ** 10n, + amount: ((2n ** 128n - 1n) * 10n ** 10n) as TokenAmount, xToY: false } const result = await getNextSqrtPriceFromInput( @@ -2044,7 +2052,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMinSqrtPrice, liquidity: maxLiquidity, - amount: (2n ** 128n - 1n) * 10n ** 20n, + amount: ((2n ** 128n - 1n) * 10n ** 20n) as TokenAmount, xToY: true } const result = await getNextSqrtPriceFromInput( @@ -2061,7 +2069,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, liquidity: maxLiquidity, - amount: 0n, + amount: 0n as TokenAmount, xToY: true } const result = await getNextSqrtPriceFromInput( @@ -2077,8 +2085,8 @@ describe('clamm tests', () => { test('liquidity = 0', async () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, - liquidity: 0n, - amount: 20n, + liquidity: 0n as Liquidity, + amount: 20n as TokenAmount, xToY: true } const result = await getNextSqrtPriceFromInput( @@ -2114,12 +2122,12 @@ describe('clamm tests', () => { describe('next sqrt price from output - domain', () => { let clamm: CLAMMInstance - const maxLiquidity = MAX_U256 - const minLiquidity = 1n - const maxAmount = MAX_U256 + const maxLiquidity = MAX_U256 as Liquidity + const minLiquidity = 1n as Liquidity + const maxAmount = MAX_U256 as TokenAmount - const almostMaxSqrtPrice = MAX_SQRT_PRICE - 1n - const almostMinSqrtPrice = MIN_SQRT_PRICE + 1n + const almostMaxSqrtPrice = (MAX_SQRT_PRICE - 1n) as SqrtPrice + const almostMinSqrtPrice = (MIN_SQRT_PRICE + 1n) as SqrtPrice beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -2129,7 +2137,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMaxSqrtPrice, liquidity: maxLiquidity, - amount: 1n, + amount: 1n as TokenAmount, xToY: false } const result = await getNextSqrtPriceFromOutput( @@ -2146,7 +2154,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: almostMinSqrtPrice, liquidity: maxLiquidity, - amount: 1n, + amount: 1n as TokenAmount, xToY: true } const result = await getNextSqrtPriceFromOutput( @@ -2163,7 +2171,7 @@ describe('clamm tests', () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, liquidity: maxLiquidity, - amount: 0n, + amount: 0n as TokenAmount, xToY: true } const result = await getNextSqrtPriceFromOutput( @@ -2179,8 +2187,8 @@ describe('clamm tests', () => { test('liquidity = 0', async () => { const params = { startingSqrtPrice: MIN_SQRT_PRICE, - liquidity: 0n, - amount: 20n, + liquidity: 0n as Liquidity, + amount: 20n as TokenAmount, xToY: true } await expectError( @@ -2225,11 +2233,11 @@ describe('clamm tests', () => { }) test('one token by amount in', async () => { - const currentSqrtPrice = 1_000000000000000000000000n - const targetSqrtPrice = 1_004987562112089027021926n - const liquidity = 2000_00000n - const amount = 1n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(1n) + const targetSqrtPrice = 1_004987562112089027021926n as SqrtPrice + const liquidity = toLiquidity(2000n) + const amount = 1n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2249,11 +2257,11 @@ describe('clamm tests', () => { }) test('amount out capped at target sqrt price', async () => { - const currentSqrtPrice = 1_000000000000000000000000n - const targetSqrtPrice = 1_004987562112089027021926n - const liquidity = 2000_00000n - const amount = 20n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(1n) + const targetSqrtPrice = 1_004987562112089027021926n as SqrtPrice + const liquidity = toLiquidity(2000n) + const amount = 20n as TokenAmount + const fee = 600000000n as Percentage const resultIn = await computeSwapStep( clamm, @@ -2288,11 +2296,11 @@ describe('clamm tests', () => { }) test('amount in not capped', async () => { - const currentSqrtPrice = 1_010000000000000000000000n - const targetSqrtPrice = 10_000000000000000000000000n - const liquidity = 300000000_00000n - const amount = 1000000n - const fee = 600000000n + const currentSqrtPrice = 1_010000000000000000000000n as SqrtPrice + const targetSqrtPrice = toSqrtPrice(10n) + const liquidity = toLiquidity(300000000n) + const amount = 1000000n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2312,11 +2320,11 @@ describe('clamm tests', () => { }) test('amount out not capped', async () => { - const currentSqrtPrice = 101_000000000000000000000000n - const targetSqrtPrice = 100_000000000000000000000000n - const liquidity = 5000000000000_00000n - const amount = 2000000n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(101n) + const targetSqrtPrice = toSqrtPrice(100n) + const liquidity = toLiquidity(5000000000000n) + const amount = 2000000n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2336,11 +2344,11 @@ describe('clamm tests', () => { }) test('empty swap step when sqrt price is at tick', async () => { - const currentSqrtPrice = 999500149965000000000000n - const targetSqrtPrice = 999500149965000000000000n - const liquidity = 200060000_00000n - const amount = 1000000n - const fee = 600000000n + const currentSqrtPrice = 999500149965000000000000n as SqrtPrice + const targetSqrtPrice = 999500149965000000000000n as SqrtPrice + const liquidity = toLiquidity(200060000n) + const amount = 1000000n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2360,11 +2368,11 @@ describe('clamm tests', () => { }) test('if liquidity is high, small amount in should not push sqrt price', async () => { - const currentSqrtPrice = 999500149965000000000000n - const targetSqrtPrice = 1_999500149965000000000000n - const liquidity = 100000000000000000000000000_00000n - const amount = 10n - const fee = 600000000n + const currentSqrtPrice = 999500149965000000000000n as SqrtPrice + const targetSqrtPrice = 1_999500149965000000000000n as SqrtPrice + const liquidity = toLiquidity(100000000000000000000000000n) + const amount = 10n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2384,11 +2392,11 @@ describe('clamm tests', () => { }) test('amount in > u64 for swap to target sqrt price and when liquidity > 2^64', async () => { - const currentSqrtPrice = 1_000000000000000000000000n - const targetSqrtPrice = 1_000050000000000000000000n - const liquidity = 368944000000000000000000_00000n - const amount = 1n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(1n) + const targetSqrtPrice = 1_000050000000000000000000n as SqrtPrice + const liquidity = toLiquidity(368944000000000000000000n) + const amount = 1n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2408,11 +2416,11 @@ describe('clamm tests', () => { }) test('amount out > u64 for swap to target sqrt price and when liquidity > 2^64', async () => { - const currentSqrtPrice = 1_000000000000000000000000n - const targetSqrtPrice = 1_000050000000000000000000n - const liquidity = 368944000000000000000000_00000n - const amount = 1n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(1n) + const targetSqrtPrice = 1_000050000000000000000000n as SqrtPrice + const liquidity = toLiquidity(368944000000000000000000n) + const amount = 1n as TokenAmount + const fee = 600000000n as Percentage const result = await computeSwapStep( clamm, @@ -2432,11 +2440,11 @@ describe('clamm tests', () => { }) test('liquidity is zero and by amount in should skip to target sqrt price', async () => { - const currentSqrtPrice = 1_000000000000000000000000n - const targetSqrtPrice = 1_000050000000000000000000n - const liquidity = 0n - const amount = 100000n - const fee = 600000000n + const currentSqrtPrice = toSqrtPrice(1n) + const targetSqrtPrice = 1_000050000000000000000000n as SqrtPrice + const liquidity = 0n as Liquidity + const amount = 100000n as TokenAmount + const fee = 600000000n as Percentage const resultIn = await computeSwapStep( clamm, @@ -2471,11 +2479,11 @@ describe('clamm tests', () => { }) test('normal swap step but fee is set to 0', async () => { - const currentSqrtPrice = 999950000000000000000000n - const targetSqrtPrice = 1_000000000000000000000000n - const liquidity = 50000000_00000n - const amount = 1000n - const fee = 0n + const currentSqrtPrice = 999950000000000000000000n as SqrtPrice + const targetSqrtPrice = toSqrtPrice(1n) + const liquidity = toLiquidity(50000000n) + const amount = 1000n as TokenAmount + const fee = 0n as Percentage const result = await computeSwapStep( clamm, @@ -2497,13 +2505,13 @@ describe('clamm tests', () => { test('by amount out and x to y edge cases', async () => { const tickIndex = -10n const targetSqrtPrice = await calculateSqrtPrice(clamm, tickIndex) - const currentSqrtPrice = targetSqrtPrice + 1_000000000000000000000000n - const liquidity = 340282366920938463463374607_00000n - const oneToken = 1n - const tokensWithSameOutput = 85n - const zeroToken = 0n - const maxFee = 900000000000n - const minFee = 0n + const currentSqrtPrice = (targetSqrtPrice + toSqrtPrice(1n)) as SqrtPrice + const liquidity = toLiquidity(340282366920938463463374607n) + const oneToken = 1n as TokenAmount + const tokensWithSameOutput = 85n as TokenAmount + const zeroToken = 0n as TokenAmount + const maxFee = 900000000000n as Percentage + const minFee = 0n as Percentage const oneTokenResult = await computeSwapStep( clamm, @@ -2556,14 +2564,14 @@ describe('clamm tests', () => { describe('compute swap step - domain', () => { let clamm: CLAMMInstance - const oneSqrtPrice = 1_000000000000000000000000n - const twoSqrtPrice = 2_000000000000000000000000n - const oneLiquidity = 1_00000n - const maxLiquidity = MAX_U256 - const maxAmount = MAX_U256 - const maxAmountNotReachedTargetSqrtPrice = MAX_U256 - 1n - const maxFee = 1_000000000000n - const minFee = 0n + const oneSqrtPrice = toSqrtPrice(1n) + const twoSqrtPrice = toSqrtPrice(2n) + const oneLiquidity = toLiquidity(1n) + const maxLiquidity = MAX_U256 as Liquidity + const maxAmount = MAX_U256 as TokenAmount + const maxAmountNotReachedTargetSqrtPrice = (MAX_U256 - 1n) as TokenAmount + const maxFee = toPercentage(1n) + const minFee = 0n as Percentage beforeEach(async () => { clamm = await deployCLAMM(sender) @@ -2622,14 +2630,14 @@ describe('clamm tests', () => { }) test('by amount in == true || close to target sqrt price but not reached', async () => { - const bigLiquidity = 100000000000000_00000n - const amountPushingSqrtPriceToTarget = 100000000000000n + const bigLiquidity = 100000000000000_00000n as Liquidity + const amountPushingSqrtPriceToTarget = 100000000000000n as TokenAmount const params = { currentSqrtPrice: oneSqrtPrice, targetSqrtPrice: twoSqrtPrice, liquidity: bigLiquidity, - amount: amountPushingSqrtPriceToTarget - 1n, + amount: (amountPushingSqrtPriceToTarget - 1n) as TokenAmount, byAmountIn: true, fee: minFee } @@ -2655,9 +2663,9 @@ describe('clamm tests', () => { currentSqrtPrice: oneSqrtPrice, targetSqrtPrice: twoSqrtPrice, liquidity: maxLiquidity, - amount: MAX_U256, + amount: MAX_U256 as TokenAmount, byAmountIn: true, - fee: maxFee - 19n + fee: (maxFee - 19n) as Percentage } const result = await computeSwapStep( clamm, @@ -2729,12 +2737,12 @@ describe('clamm tests', () => { }) test('get next sqrt price from input -> get next sqrt price y down / big div - no possible to trigger from compute swap step', async () => { - const minOverflowTokenAmount = 340282366920939n + const minOverflowTokenAmount = 340282366920939n as TokenAmount const params = { currentSqrtPrice: MIN_SQRT_PRICE, targetSqrtPrice: MAX_SQRT_PRICE, - liquidity: oneLiquidity - 1n, - amount: minOverflowTokenAmount - 1n, + liquidity: (oneLiquidity - 1n) as Liquidity, + amount: (minOverflowTokenAmount - 1n) as TokenAmount, byAmountIn: true, fee: minFee } @@ -2758,10 +2766,10 @@ describe('clamm tests', () => { test('get next sqrt price from output -> get next sqrt price x up / min sqrt price different at maximum amount', async () => { const minDiff = 232826265438719159684n const params = { - currentSqrtPrice: MAX_SQRT_PRICE - minDiff, + currentSqrtPrice: (MAX_SQRT_PRICE - minDiff) as SqrtPrice, targetSqrtPrice: MAX_SQRT_PRICE, liquidity: maxLiquidity, - amount: MAX_U256 - 1n, + amount: (MAX_U256 - 1n) as TokenAmount, byAmountIn: false, fee: minFee } @@ -2786,8 +2794,8 @@ describe('clamm tests', () => { const params = { currentSqrtPrice: MIN_SQRT_PRICE, targetSqrtPrice: MAX_SQRT_PRICE, - liquidity: 281477613507675_00000n, - amount: MAX_U256 - 1n, + liquidity: 281477613507675_00000n as Liquidity, + amount: (MAX_U256 - 1n) as TokenAmount, byAmountIn: false, fee: minFee } @@ -2810,10 +2818,10 @@ describe('clamm tests', () => { test('get next sqrt price from output -> get next sqrt price x up / min token change', async () => { const params = { - currentSqrtPrice: MAX_SQRT_PRICE - 1_000000000000000000000000n, + currentSqrtPrice: (MAX_SQRT_PRICE - 1_000000000000000000000000n) as SqrtPrice, targetSqrtPrice: MAX_SQRT_PRICE, - liquidity: 10000000000_00000n, - amount: 1n, + liquidity: toLiquidity(10000000000n), + amount: 1n as TokenAmount, byAmountIn: false, fee: minFee } diff --git a/test/contract/unit/log.test.ts b/test/contract/unit/log.test.ts index 4aad959..dd9b2ad 100644 --- a/test/contract/unit/log.test.ts +++ b/test/contract/unit/log.test.ts @@ -4,7 +4,15 @@ import { PrivateKeyWallet } from '@alephium/web3-wallet' import { CLAMMInstance } from '../../../artifacts/ts' import { deployCLAMM } from '../../../src/utils' import { calculateSqrtPrice, expectError, getTickAtSqrtPrice } from '../../../src/testUtils' -import { DecimalError, GLOBAL_MAX_TICK, GLOBAL_MIN_TICK } from '../../../src/consts' +import { + DecimalError, + GLOBAL_MAX_TICK, + GLOBAL_MIN_TICK, + MAX_SQRT_PRICE, + MIN_SQRT_PRICE +} from '../../../src/consts' +import { SqrtPrice } from '../../../src/types' +import { toSqrtPrice } from '../../../src/math' const sqrtPriceToX32 = async (clamm: CLAMMInstance, val: bigint): Promise => { return ( @@ -89,16 +97,14 @@ describe('log tests', () => { }) test('log2 of sqrt(1.0001 ^ (-19_999)) - 1', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, -19999n) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, -19999n)) - 1n) as SqrtPrice const sqrtPriceX32 = await sqrtPriceToX32(clamm, sqrtPriceDecimal) const result = await log2IterativeApproximationX32(clamm, sqrtPriceX32) expect(result).toStrictEqual([false, 6195642368n]) }) test('log2 of sqrt(1.0001 ^ (-19_999)) + 1', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, 19999n) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, 19999n)) - 1n) as SqrtPrice const sqrtPriceX32 = await sqrtPriceToX32(clamm, sqrtPriceDecimal) const result = await log2IterativeApproximationX32(clamm, sqrtPriceX32) expect(result).toStrictEqual([true, 6195642368n]) @@ -107,19 +113,19 @@ describe('log tests', () => { describe('get tick at sqrt price', () => { test('around 0 tick / get tick at 1', async () => { - const sqrtPriceDecimal = 1_000000000000000000000000n + const sqrtPriceDecimal = toSqrtPrice(1n) const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(0n) }) test('around 0 tick / get tick slightly below 1', async () => { - const sqrtPriceDecimal = 1_000000000000000000000000n - 1n + const sqrtPriceDecimal = (1_000000000000000000000000n - 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-1n) }) test('around 0 tick / get tick slightly above 1', async () => { - const sqrtPriceDecimal = 1_000000000000000000000000n + 1n + const sqrtPriceDecimal = (1_000000000000000000000000n + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(0n) }) @@ -131,14 +137,14 @@ describe('log tests', () => { }) test('around 1 tick / get tick slightly below sqrt(1.0001)', async () => { - const sqrtPriceDecimal = await calculateSqrtPrice(clamm, 1n) - const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, 1n) + const sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, 1n)) - 1n) as SqrtPrice + const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(0n) }) test('around 1 tick / get tick slightly above sqrt(1.0001)', async () => { - const sqrtPriceDecimal = await calculateSqrtPrice(clamm, 1n) - const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, 1n) + const sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, 1n)) + 1n) as SqrtPrice + const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(1n) }) @@ -149,14 +155,14 @@ describe('log tests', () => { }) test('around -1 tick / get tick slightly below sqrt(1.0001 ^ (-1))', async () => { - const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -1n) - const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, 1n) + const sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, -1n)) - 1n) as SqrtPrice + const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-2n) }) test('around -1 tick / get tick slightly above sqrt(1.0001 ^ (-1))', async () => { - const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -1n) - const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, 1n) + const sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, -1n)) + 1n) as SqrtPrice + const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-1n) }) @@ -167,15 +173,15 @@ describe('log tests', () => { }) test('around max - 1 tick / get tick slightly below sqrt(1.0001 ^ (MAX_TICK - 1))', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, GLOBAL_MAX_TICK - 1n) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, GLOBAL_MAX_TICK - 1n)) - + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(221818n - 2n) }) test('around max - 1 tick / get tick slightly above sqrt(1.0001 ^ (MAX_TICK - 1))', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, GLOBAL_MAX_TICK - 1n) - sqrtPriceDecimal += 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, GLOBAL_MAX_TICK - 1n)) + + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(221818n - 1n) }) @@ -187,22 +193,21 @@ describe('log tests', () => { }) test('around min + 1 tick / get tick slightly below sqrt(1.0001 ^ (MAX_TICK - 1))', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, GLOBAL_MIN_TICK + 1n) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, GLOBAL_MIN_TICK + 1n)) - + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-221818n) }) test('around min + 1 tick / get tick slightly above sqrt(1.0001 ^ (MAX_TICK - 1))', async () => { - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, GLOBAL_MIN_TICK + 1n) - sqrtPriceDecimal += 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, GLOBAL_MIN_TICK + 1n)) + + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-(221818n - 1n)) }) test('get tick slightly below at max tick', async () => { - const maxSqrtPrice = 65535383934512647000000000000n - const sqrtPriceDecimal = maxSqrtPrice - 1n + const sqrtPriceDecimal = (MAX_SQRT_PRICE - 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(221818n - 1n) }) @@ -216,16 +221,14 @@ describe('log tests', () => { test('around 19999 tick / get tick slightly below sqrt(1.0001^19999)', async () => { const tickIndex = 19999n - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, tickIndex) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, tickIndex)) - 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(tickIndex - 1n) }) test('around 19999 tick / get tick slightly above sqrt(1.0001^19999)', async () => { const tickIndex = 19999n - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, tickIndex) - sqrtPriceDecimal += 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, tickIndex)) + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(tickIndex) }) @@ -250,23 +253,20 @@ describe('log tests', () => { test('around -19999 tick / get tick slightly below sqrt(1.0001^-19999)', async () => { const tickIndex = -19999n - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, tickIndex) - sqrtPriceDecimal -= 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, tickIndex)) - 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(tickIndex - 1n) }) test('around -19999 tick / get tick slightly above sqrt(1.0001^-19999)', async () => { const tickIndex = -19999n - let sqrtPriceDecimal = await calculateSqrtPrice(clamm, tickIndex) - sqrtPriceDecimal += 1n + let sqrtPriceDecimal = ((await calculateSqrtPrice(clamm, tickIndex)) + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(tickIndex) }) test('get tick slightly above at min tick', async () => { - const minSqrtPrice = await calculateSqrtPrice(clamm, -221818n) - const sqrtPriceDecimal = minSqrtPrice + 1n + const sqrtPriceDecimal = (MIN_SQRT_PRICE + 1n) as SqrtPrice const result = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) expect(result).toBe(-221818n) }) @@ -365,96 +365,112 @@ describe('log tests', () => { }) describe('all ticks', () => { - test('all positive ticks', async () => { - // for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { - // const sqrtPriceDecimal = await calculateSqrtPrice(clamm, i) - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) - // expect(tick).toBe(i) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, 1n) - // expect(tick).toBe(i - 1n) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, 1n) - // expect(tick).toBe(i) - // } - // } + test.skip('all positive ticks', async () => { + for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { + const sqrtPriceDecimal = await calculateSqrtPrice(clamm, i) + { + const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) + expect(tick).toBe(i) + } + { + const tick = await getTickAtSqrtPrice(clamm, (sqrtPriceDecimal - 1n) as SqrtPrice, 1n) + expect(tick).toBe(i - 1n) + } + { + const tick = await getTickAtSqrtPrice(clamm, (sqrtPriceDecimal + 1n) as SqrtPrice, 1n) + expect(tick).toBe(i) + } + } }, 3600000) - test('all negative ticks', async () => { - // for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { - // const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -i) - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) - // expect(tick).toBe(-i) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, 1n) - // expect(tick).toBe(-i - 1n) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, 1n) - // expect(tick).toBe(-i) - // } - // } + test.skip('all negative ticks', async () => { + for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { + const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -i) + { + const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, 1n) + expect(tick).toBe(-i) + } + { + const tick = await getTickAtSqrtPrice(clamm, (sqrtPriceDecimal - 1n) as SqrtPrice, 1n) + expect(tick).toBe(-i - 1n) + } + { + const tick = await getTickAtSqrtPrice(clamm, (sqrtPriceDecimal + 1n) as SqrtPrice, 1n) + expect(tick).toBe(-i) + } + } }, 3600000) - test('all positive ticks, tick spacing greater than 1', async () => { - // const tickSpacing = 3n - // for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { - // const sqrtPriceDecimal = await calculateSqrtPrice(clamm, i) - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, tickSpacing) - // const expectedTick = ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: i, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, tickSpacing) - // const expectedTick = ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: i - 1n, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, tickSpacing) - // const expectedTick = ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: i, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // } + test.skip('all positive ticks, tick spacing greater than 1', async () => { + const tickSpacing = 3n + for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { + const sqrtPriceDecimal = await calculateSqrtPrice(clamm, i) + { + const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, tickSpacing) + const expectedTick = ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: i, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + { + const tick = await getTickAtSqrtPrice( + clamm, + (sqrtPriceDecimal - 1n) as SqrtPrice, + tickSpacing + ) + const expectedTick = ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: i - 1n, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + { + const tick = await getTickAtSqrtPrice( + clamm, + (sqrtPriceDecimal + 1n) as SqrtPrice, + tickSpacing + ) + const expectedTick = ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: i, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + } }, 3600000) - test('all negative ticks, tick spacing greater than 1', async () => { - // const tickSpacing = 4n - // for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { - // const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -i) - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, tickSpacing) - // const expectedTick = ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: -i, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal - 1n, tickSpacing) - // const expectedTick = await ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: -i - 1n, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // { - // const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal + 1n, tickSpacing) - // const expectedTick = ( - // await clamm.view.alignTickToSpacing({ args: { accurateTick: -i, tickSpacing } }) - // ).returns - // expect(tick).toBe(expectedTick) - // } - // } + test.skip('all negative ticks, tick spacing greater than 1', async () => { + const tickSpacing = 4n + for (let i = 0n; i < GLOBAL_MAX_TICK; i++) { + const sqrtPriceDecimal = await calculateSqrtPrice(clamm, -i) + { + const tick = await getTickAtSqrtPrice(clamm, sqrtPriceDecimal, tickSpacing) + const expectedTick = ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: -i, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + { + const tick = await getTickAtSqrtPrice( + clamm, + (sqrtPriceDecimal - 1n) as SqrtPrice, + tickSpacing + ) + const expectedTick = await ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: -i - 1n, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + { + const tick = await getTickAtSqrtPrice( + clamm, + (sqrtPriceDecimal + 1n) as SqrtPrice, + tickSpacing + ) + const expectedTick = ( + await clamm.view.alignTickToSpacing({ args: { accurateTick: -i, tickSpacing } }) + ).returns + expect(tick).toBe(expectedTick) + } + } }, 3600000) }) }) diff --git a/test/contract/unit/reserve.test.ts b/test/contract/unit/reserve.test.ts index cc3f96f..3b93c21 100644 --- a/test/contract/unit/reserve.test.ts +++ b/test/contract/unit/reserve.test.ts @@ -15,18 +15,19 @@ import { import { expectError, expectVMError, initTokensXY, withdrawTokens } from '../../../src/testUtils' import { balanceOf, waitTxConfirmed } from '../../../src/utils' import { RESERVE_ASSET_CAPACITY, ReserveError, VMError } from '../../../src/consts' +import { TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('reserve tests', () => { + const supply = 1000n as TokenAmount test('deposit single asset', async () => { const depositor = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n const [tokenX] = await initTokensXY(depositor, supply) const reserve = await deployReserveWithAuthority(depositor) await withdrawTokens(depositor, [tokenX, supply]) - const deposit = 50n + const deposit = 50n as TokenAmount await depositSingleAsset(reserve, depositor, tokenX, deposit) const reserveBalance = await balanceOf(tokenX.contractId, reserve.address) @@ -35,12 +36,11 @@ describe('reserve tests', () => { test('deposit two assets', async () => { const depositor = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n const [tokenX, tokenY] = await initTokensXY(depositor, supply) const reserve = await deployReserveWithAuthority(depositor) await withdrawTokens(depositor, [tokenX, supply], [tokenY, supply]) - const deposit = 75n + const deposit = 75n as TokenAmount await depositTwoAssets(reserve, depositor, tokenX, deposit, tokenY, deposit) const reserveBalance = { @@ -55,12 +55,11 @@ describe('reserve tests', () => { test('withdraw single asset', async () => { const withdrawer = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n const [tokenX] = await initTokensXY(withdrawer, supply) const reserve = await deployReserveWithAuthority(withdrawer) await withdrawTokens(withdrawer, [tokenX, supply]) - const deposit = 50n + const deposit = 50n as TokenAmount await depositSingleAsset(reserve, withdrawer, tokenX, deposit) const withdraw = 25n @@ -75,7 +74,6 @@ describe('reserve tests', () => { test('withdraw two assets', async () => { const withdrawer = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n const [tokenX, tokenY] = await initTokensXY(withdrawer, supply) const reserve = await deployReserveWithAuthority(withdrawer) await withdrawTokens(withdrawer, [tokenX, supply], [tokenY, supply]) @@ -107,8 +105,7 @@ describe('reserve tests', () => { test('swap assets', async () => { const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n - const deposit = 75n + const deposit = 75n as TokenAmount const [tokenX, tokenY] = await initTokensXY(swapper, supply) const reserve = await deployReserveWithAuthority(swapper) @@ -116,7 +113,7 @@ describe('reserve tests', () => { await depositTwoAssets(reserve, swapper, tokenX, deposit, tokenY, deposit) - const amountIn = 10n + const amountIn = 10n as TokenAmount const outAmount = 20n await withdrawTokens(swapper, [tokenX, amountIn]) @@ -149,8 +146,7 @@ describe('reserve tests', () => { test('reserve panics when storing more than RESERVE_ASSET_CAPACITY assets', async () => { const depositor = await getSigner(ONE_ALPH * 1000n, 0) const reserve = await deployReserveWithAuthority(depositor) - const supply = 1000n - const deposit = 75n + const deposit = 75n as TokenAmount for (let i = 0; i < RESERVE_ASSET_CAPACITY / 2n; i++) { const [tokenX, tokenY] = await initTokensXY(depositor, supply) @@ -180,14 +176,13 @@ describe('reserve tests', () => { test('entrypoints prevent an unauthorized user to perform a transfers', async () => { const reserveOwner = await getSigner(ONE_ALPH * 1000n, 0) const unauthorizedUser = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 1000n const reserve = await deployReserveWithAuthority(reserveOwner) // deposits { const [tokenX, tokenY] = await initTokensXY(reserveOwner, supply) - const deposit = 75n + const deposit = 75n as TokenAmount await withdrawTokens(unauthorizedUser, [tokenX, deposit], [tokenY, deposit]) await expectError( ReserveError.NotInvariant, @@ -202,7 +197,7 @@ describe('reserve tests', () => { { const [tokenX, tokenY] = await initTokensXY(reserveOwner, supply) - const deposit = 75n + const deposit = 75n as TokenAmount await withdrawTokens(reserveOwner, [tokenX, deposit], [tokenY, deposit]) await depositTwoAssets(reserve, reserveOwner, tokenX, deposit, tokenY, deposit) @@ -219,12 +214,12 @@ describe('reserve tests', () => { { const [tokenX, tokenY] = await initTokensXY(reserveOwner, supply) - const deposit = 75n + const deposit = 75n as TokenAmount await withdrawTokens(reserveOwner, [tokenX, deposit], [tokenY, deposit]) await depositTwoAssets(reserve, reserveOwner, tokenX, deposit, tokenY, deposit) - const amountIn = 10n - const amountOut = 20n + const amountIn = 10n as TokenAmount + const amountOut = 20n as TokenAmount await withdrawTokens(unauthorizedUser, [tokenX, amountIn], [tokenY, amountOut]) await expectError( diff --git a/test/contract/unit/tickmap.test.ts b/test/contract/unit/tickmap.test.ts index 9ca620b..9fec073 100644 --- a/test/contract/unit/tickmap.test.ts +++ b/test/contract/unit/tickmap.test.ts @@ -5,7 +5,7 @@ import { Flip, InitializeChunk, InvariantInstance } from '../../../artifacts/ts' import { deployInvariant, deployTokenFaucet, newFeeTier, newPoolKey } from '../../../src/utils' import { GLOBAL_MIN_TICK, GLOBAL_MAX_TICK } from '../../../src/consts' -import { PoolKey, wrapPoolKey } from '../../../src/types' +import { Percentage, PoolKey, TokenAmount, wrapPoolKey } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let sender: PrivateKeyWallet @@ -89,12 +89,14 @@ const nextInitialized = async ( } const TICK_SEARCH_RANGE = 256n -const protocolFee = 100n +const protocolFee = 100n as Percentage describe('tickmap tests', () => { beforeAll(async () => { sender = await getSigner(ONE_ALPH * 1000n, 0) - token0Addr = (await deployTokenFaucet(sender, '', '', 0n, 0n)).contractInstance.address - token1Addr = (await deployTokenFaucet(sender, '', '', 0n, 0n)).contractInstance.address + token0Addr = (await deployTokenFaucet(sender, '', '', 0n, 0n as TokenAmount)).contractInstance + .address + token1Addr = (await deployTokenFaucet(sender, '', '', 0n, 0n as TokenAmount)).contractInstance + .address }) test('flip bit', async () => { @@ -108,7 +110,7 @@ describe('tickmap tests', () => { { tickSpacing: 100n, tick: 20000n } ] for (const { tick, tickSpacing } of params) { - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -131,7 +133,7 @@ describe('tickmap tests', () => { const tick = 5n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -149,7 +151,7 @@ describe('tickmap tests', () => { const tick50 = 50n const tick100 = 100n const tickSpacing = 10n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) { @@ -180,7 +182,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 10n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -196,7 +198,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -218,7 +220,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -234,7 +236,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MAX_TICK - 10n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -250,7 +252,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MAX_TICK - 22n const tickSpacing = 4n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [isSome] = await nextInitialized(invariant, tick, tickSpacing, poolKey) @@ -260,7 +262,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MAX_TICK - 2n const tickSpacing = 4n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [isSome] = await nextInitialized(invariant, tick, tickSpacing, poolKey) @@ -270,7 +272,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MAX_TICK - 255n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -292,7 +294,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = -5n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -310,7 +312,7 @@ describe('tickmap tests', () => { const tick50 = -50n const tick100 = -100n const tickSpacing = 10n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) { const [chunkIndex] = await tickToPosition(invariant, tick50, tickSpacing) @@ -341,7 +343,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 10n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -358,7 +360,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 10n const tickSpacing = 10n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -374,7 +376,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -396,7 +398,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = 0n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -412,7 +414,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MIN_TICK + 1n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -428,7 +430,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MIN_TICK + 255n const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -450,7 +452,7 @@ describe('tickmap tests', () => { const invariant = await deployInvariant(sender, protocolFee) const tick = GLOBAL_MIN_TICK const tickSpacing = 1n - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const [chunkIndex] = await tickToPosition(invariant, tick, tickSpacing) @@ -527,7 +529,7 @@ describe('tickmap tests', () => { test('test next and prev intialized', async () => { // initialized edges for (let tickSpacing = 1n; tickSpacing <= 10n; tickSpacing++) { - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const invariant = await deployInvariant(sender, protocolFee) @@ -569,7 +571,7 @@ describe('tickmap tests', () => { } } for (let tickSpacing = 1n; tickSpacing <= 10n; tickSpacing++) { - const feeTier = await newFeeTier(0n, tickSpacing) + const feeTier = await newFeeTier(0n as Percentage, tickSpacing) const poolKey = await newPoolKey(token0Addr, token1Addr, feeTier) const invariant = await deployInvariant(sender, protocolFee) diff --git a/test/contract/unit/token.test.ts b/test/contract/unit/token.test.ts index 0084ee2..379d6ea 100644 --- a/test/contract/unit/token.test.ts +++ b/test/contract/unit/token.test.ts @@ -3,6 +3,7 @@ import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { Withdraw } from '../../../artifacts/ts' import { balanceOf, deployTokenFaucet } from '../../../src/utils' +import { TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') let sender: PrivateKeyWallet @@ -13,7 +14,7 @@ describe('token tests', () => { }) test('withdraw', async () => { - let initAmount = 100n + let initAmount = 100n as TokenAmount let amount = 25n const result = await deployTokenFaucet(sender, '', '', 0n, initAmount) diff --git a/test/sdk/e2e/fungible-token.test.ts b/test/sdk/e2e/fungible-token.test.ts index 43b28ca..da6d836 100644 --- a/test/sdk/e2e/fungible-token.test.ts +++ b/test/sdk/e2e/fungible-token.test.ts @@ -3,6 +3,7 @@ import { getSigner } from '@alephium/web3-test' import { Network } from '../../../src/network' import { FungibleToken } from '../../../src/fungible-token' import { PrivateKeyWallet } from '@alephium/web3-wallet' +import { TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -14,7 +15,7 @@ describe('fungible token tests', () => { beforeAll(async () => { admin = await getSigner(ONE_ALPH * 1000n, 0) token = await FungibleToken.load(Network.Local) - token0 = await FungibleToken.deploy(admin, 1000n, 'Coin', 'COIN', 12n) + token0 = await FungibleToken.deploy(admin, 1000n as TokenAmount, 'Coin', 'COIN', 12n) }) test('set metadata', async () => { @@ -24,26 +25,32 @@ describe('fungible token tests', () => { }) test('mint tokens', async () => { - await token.mint(admin, 500n, token0) + await token.mint(admin, 500n as TokenAmount, token0) expect(await token.getBalanceOf(admin.address, token0)).toBe(1500n) }) test('change instance', async () => { - const secondToken = await FungibleToken.deploy(admin, 1000n, 'SecondCoin', 'SCOIN', 12n) + const secondToken = await FungibleToken.deploy( + admin, + 1000n as TokenAmount, + 'SecondCoin', + 'SCOIN', + 12n + ) const tokenName = await token.getTokenName(secondToken) expect(tokenName).toBe('SecondCoin') }) test('get all balances', async () => { - const token0 = await FungibleToken.deploy(admin, 0n, 'Coin', 'COIN', 12n) - const token1 = await FungibleToken.deploy(admin, 0n, 'Coin', 'COIN', 12n) - const token2 = await FungibleToken.deploy(admin, 0n, 'Coin', 'COIN', 12n) - const token3 = await FungibleToken.deploy(admin, 0n, 'Coin', 'COIN', 12n) + const token0 = await FungibleToken.deploy(admin, 0n as TokenAmount, 'Coin', 'COIN', 12n) + const token1 = await FungibleToken.deploy(admin, 0n as TokenAmount, 'Coin', 'COIN', 12n) + const token2 = await FungibleToken.deploy(admin, 0n as TokenAmount, 'Coin', 'COIN', 12n) + const token3 = await FungibleToken.deploy(admin, 0n as TokenAmount, 'Coin', 'COIN', 12n) - await token.mint(admin, 100n, token0) - await token.mint(admin, 200n, token1) - await token.mint(admin, 300n, token2) - await token.mint(admin, 400n, token3) + await token.mint(admin, 100n as TokenAmount, token0) + await token.mint(admin, 200n as TokenAmount, token1) + await token.mint(admin, 300n as TokenAmount, token2) + await token.mint(admin, 400n as TokenAmount, token3) const balances = await token.getAllBalances([token0, token1, token2, token3], admin.address) @@ -56,10 +63,10 @@ describe('fungible token tests', () => { test('get metadata for all tokens', async () => { const tokenAddresses = [ - await FungibleToken.deploy(admin, 0n, 'CoinONE', 'COIN1', 12n), - await FungibleToken.deploy(admin, 0n, 'CoinTWO', 'COIN2', 13n), - await FungibleToken.deploy(admin, 0n, 'CoinTHREE', 'COIN3', 14n), - await FungibleToken.deploy(admin, 0n, 'CoinFOUR', 'COIN4', 15n) + await FungibleToken.deploy(admin, 0n as TokenAmount, 'CoinONE', 'COIN1', 12n), + await FungibleToken.deploy(admin, 0n as TokenAmount, 'CoinTWO', 'COIN2', 13n), + await FungibleToken.deploy(admin, 0n as TokenAmount, 'CoinTHREE', 'COIN3', 14n), + await FungibleToken.deploy(admin, 0n as TokenAmount, 'CoinFOUR', 'COIN4', 15n) ] const metadata = await token.getTokenMetaDataMulti(tokenAddresses) diff --git a/test/sdk/e2e/get-all-pool-keys.test.ts b/test/sdk/e2e/get-all-pool-keys.test.ts index 3c1a56f..a36a0c6 100644 --- a/test/sdk/e2e/get-all-pool-keys.test.ts +++ b/test/sdk/e2e/get-all-pool-keys.test.ts @@ -7,7 +7,8 @@ import { TokenFaucetInstance } from '../../../artifacts/ts' import { expectVMError, initTokensXY, withdrawTokens } from '../../../src/testUtils' import { newFeeTier, newPoolKey } from '../../../src/utils' import { MAX_POOL_KEYS_QUERIED, VMError } from '../../../src/consts' -import { PoolKey } from '../../../src/types' +import { Percentage, PoolKey, TokenAmount } from '../../../src/types' +import { toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -18,10 +19,10 @@ let tokenX: TokenFaucetInstance let tokenY: TokenFaucetInstance describe('get pool keys test', () => { - const initialFee = 0n + const initialFee = 0n as Percentage - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 10n) as TokenAmount beforeEach(async () => { deployer = await getSigner(ONE_ALPH * 1000n, 0) @@ -37,7 +38,9 @@ describe('get pool keys test', () => { }) test('get all pool keys', async () => { const feeTiers = await Promise.all( - Array.from(Array(10).keys()).map(async i => await newFeeTier(BigInt(i + 1), BigInt(i + 1))) + Array.from(Array(10).keys()).map( + async i => await newFeeTier(BigInt(i + 1) as Percentage, BigInt(i + 1)) + ) ) const expectedPoolKeys: PoolKey[] = [] for (const feeTier of feeTiers) { @@ -62,7 +65,7 @@ describe('get pool keys test', () => { }) }) test('find max query limit', async () => { - const feeTier = await newFeeTier(1n, 1n) + const feeTier = await newFeeTier(1n as Percentage, 1n) await invariant.addFeeTier(deployer, feeTier) const expectedPoolKeys: PoolKey[] = [] for (let i = 0n; i < MAX_POOL_KEYS_QUERIED; i++) { @@ -83,7 +86,7 @@ describe('get pool keys test', () => { }) test('runs out of gas over the limit for single query, querying all passes', async () => { const overSingleLimit = MAX_POOL_KEYS_QUERIED + 1n - const feeTier = await newFeeTier(1n, 1n) + const feeTier = await newFeeTier(1n as Percentage, 1n) await invariant.addFeeTier(deployer, feeTier) const expectedPoolKeys: PoolKey[] = [] diff --git a/test/sdk/e2e/get-all-positions.test.ts b/test/sdk/e2e/get-all-positions.test.ts index 93cc55f..5764a77 100644 --- a/test/sdk/e2e/get-all-positions.test.ts +++ b/test/sdk/e2e/get-all-positions.test.ts @@ -8,7 +8,8 @@ import { TokenFaucetInstance } from '../../../artifacts/ts' import { initTokensXY, withdrawTokens } from '../../../src/testUtils' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' import { MAX_POSITIONS_QUERIED } from '../../../src/consts' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Liquidity, Percentage, PoolKey, TokenAmount } from '../../../src/types' +import { toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -21,11 +22,11 @@ let feeTier: FeeTier let poolKey: PoolKey describe('get all positions test', () => { - const initialFee = 0n + const initialFee = 0n as Percentage const [fee, tickSpacing] = getBasicFeeTickSpacing() - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n - const liquidityDelta = 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = 10n ** 10n as TokenAmount + const liquidityDelta = 10n as Liquidity beforeEach(async () => { deployer = await getSigner(ONE_ALPH * 1000n, 0) diff --git a/test/sdk/e2e/get-liquidity-ticks.test.ts b/test/sdk/e2e/get-liquidity-ticks.test.ts index 3e71769..cf55593 100644 --- a/test/sdk/e2e/get-liquidity-ticks.test.ts +++ b/test/sdk/e2e/get-liquidity-ticks.test.ts @@ -8,7 +8,8 @@ import { TokenFaucetInstance } from '../../../artifacts/ts' import { expectVMError, initTokensXY, withdrawTokens } from '../../../src/testUtils' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' import { MAX_LIQUIDITY_TICKS_QUERIED, VMError } from '../../../src/consts' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Liquidity, Percentage, PoolKey, TokenAmount } from '../../../src/types' +import { toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -21,11 +22,11 @@ let feeTier: FeeTier let poolKey: PoolKey describe('query liquidity ticks tests', () => { - const initialFee = 0n + const initialFee = 0n as Percentage const [fee] = getBasicFeeTickSpacing() const tickSpacing = 1n - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 10n) as TokenAmount beforeEach(async () => { deployer = await getSigner(ONE_ALPH * 1000n, 0) @@ -56,7 +57,7 @@ describe('query liquidity ticks tests', () => { poolKey, lowerTickIndex, upperTickIndex, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -117,7 +118,7 @@ describe('query liquidity ticks tests', () => { poolKey2TS, lowerTickIndex, upperTickIndex, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -150,7 +151,7 @@ describe('query liquidity ticks tests', () => { poolKey10TS, lowerTickIndex, upperTickIndex, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -191,7 +192,7 @@ describe('query liquidity ticks tests', () => { poolKey, lowerTick, upperTick, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -228,7 +229,7 @@ describe('query liquidity ticks tests', () => { poolKey, lowerTick, upperTick, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -247,7 +248,7 @@ describe('query liquidity ticks tests', () => { poolKey, 0n, upperTick, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -278,7 +279,7 @@ describe('query liquidity ticks tests', () => { poolKey, lowerTick, upperTick, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, diff --git a/test/sdk/e2e/get-position-with-associates.test.ts b/test/sdk/e2e/get-position-with-associates.test.ts index 3edf408..a1ffcb6 100644 --- a/test/sdk/e2e/get-position-with-associates.test.ts +++ b/test/sdk/e2e/get-position-with-associates.test.ts @@ -6,6 +6,7 @@ import { Network } from '../../../src/network' import { Invariant } from '../../../src/invariant' import { FungibleToken } from '../../../src/fungible-token' import { toSqrtPrice } from '../../../src/math' +import { Liquidity, Percentage, TokenAmount } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -16,11 +17,11 @@ describe('get position with associates tests', () => { }) test('get position with associates', async () => { const deployer = await getSigner(ONE_ALPH * 1000n, 0) - const initialFee = 0n + const initialFee = 0n as Percentage const invariant = await Invariant.deploy(deployer, Network.Local, initialFee) - const token0 = await FungibleToken.deploy(deployer, 0n, 'Token0', 'TK0') - const token1 = await FungibleToken.deploy(deployer, 0n, 'Token1', 'TK1') + const token0 = await FungibleToken.deploy(deployer, 0n as TokenAmount, 'Token0', 'TK0') + const token1 = await FungibleToken.deploy(deployer, 0n as TokenAmount, 'Token1', 'TK1') const feeTier = await newFeeTier(...getBasicFeeTickSpacing()) const poolKey = await newPoolKey(token0, token1, feeTier) @@ -28,7 +29,7 @@ describe('get position with associates tests', () => { await invariant.addFeeTier(deployer, feeTier) const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const supply = 10n ** 10n + const supply = (10n ** 10n) as TokenAmount await token.mint(positionOwner, supply, token0) await token.mint(positionOwner, supply, token1) @@ -44,7 +45,7 @@ describe('get position with associates tests', () => { poolKey, lowerTickIndex, upperTickIndex, - 10n, + 10n as Liquidity, supply, supply, sqrtPrice, diff --git a/test/sdk/e2e/get-positions.test.ts b/test/sdk/e2e/get-positions.test.ts index 11496b4..a20063e 100644 --- a/test/sdk/e2e/get-positions.test.ts +++ b/test/sdk/e2e/get-positions.test.ts @@ -7,7 +7,8 @@ import { getBasicFeeTickSpacing } from '../../../src/snippets' import { TokenFaucetInstance } from '../../../artifacts/ts' import { initTokensXY, withdrawTokens } from '../../../src/testUtils' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Liquidity, Percentage, PoolKey, TokenAmount } from '../../../src/types' +import { toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -20,12 +21,12 @@ let feeTier: FeeTier let poolKey: PoolKey describe('get positions test', () => { - const initialFee = 0n + const initialFee = 0n as Percentage const [fee] = getBasicFeeTickSpacing() const tickSpacing = 1n - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n - const liquidityDelta = 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 10n) as TokenAmount + const liquidityDelta = 10n as Liquidity beforeEach(async () => { deployer = await getSigner(ONE_ALPH * 1000n, 0) diff --git a/test/sdk/e2e/get-tickmap.test.ts b/test/sdk/e2e/get-tickmap.test.ts index d158606..1b05391 100644 --- a/test/sdk/e2e/get-tickmap.test.ts +++ b/test/sdk/e2e/get-tickmap.test.ts @@ -8,9 +8,9 @@ import { TokenFaucetInstance } from '../../../artifacts/ts' import { initTokensXY, withdrawTokens } from '../../../src/testUtils' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' import { GLOBAL_MAX_TICK, GLOBAL_MIN_TICK } from '../../../src' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Liquidity, Percentage, PoolKey, TokenAmount } from '../../../src/types' import { CHUNK_SIZE, CHUNKS_PER_BATCH } from '../../../src/consts' -import { getMaxChunk, getMaxTick, getMinTick, toLiquidity } from '../../../src/math' +import { getMaxChunk, getMaxTick, getMinTick, toLiquidity, toSqrtPrice } from '../../../src/math' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -23,11 +23,11 @@ let feeTier: FeeTier let poolKey: PoolKey describe('query tickmap tests', () => { - const initialFee = 0n + const initialFee = 0n as Percentage const [fee] = getBasicFeeTickSpacing() const tickSpacing = 1n - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 10n) as TokenAmount const lowerTickIndex = GLOBAL_MIN_TICK const upperTickIndex = GLOBAL_MAX_TICK const ticks = [-221818n, -221817n, -58n, 5n, 221817n, 221818n] @@ -77,7 +77,7 @@ describe('query tickmap tests', () => { poolKey, i, i + 1n, - 10n, + 10n as Liquidity, approveX, approveY, pool.sqrtPrice, @@ -92,7 +92,7 @@ describe('query tickmap tests', () => { poolKey, i + 2n, i + 3n, - 10n, + 10n as Liquidity, approveX, approveY, pool.sqrtPrice, @@ -117,7 +117,7 @@ describe('query tickmap tests', () => { poolKey, ticks[2], ticks[3], - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -143,7 +143,7 @@ describe('query tickmap tests', () => { poolKey, ticks[0], ticks[1], - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -158,7 +158,7 @@ describe('query tickmap tests', () => { poolKey, ticks[4], ticks[5], - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -194,7 +194,7 @@ describe('query tickmap tests', () => { poolKey, await getMinTick(tickSpacing), (await getMinTick(tickSpacing)) + tickSpacing, - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, @@ -209,7 +209,7 @@ describe('query tickmap tests', () => { poolKey, (await getMaxTick(tickSpacing)) - tickSpacing, await getMaxTick(tickSpacing), - 10n, + 10n as Liquidity, approveX, approveY, sqrtPrice, diff --git a/test/sdk/e2e/invariant.test.ts b/test/sdk/e2e/invariant.test.ts index 27877be..62bb34c 100644 --- a/test/sdk/e2e/invariant.test.ts +++ b/test/sdk/e2e/invariant.test.ts @@ -4,19 +4,20 @@ import { Invariant } from '../../../src/invariant' import { Network } from '../../../src/network' import { getBasicFeeTickSpacing } from '../../../src/snippets' import { newFeeTier } from '../../../src/utils' +import { Percentage } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('invariant tests', () => { test('deploy', async () => { - const initialFee = 0n + const initialFee = 0n as Percentage const deployer = await getSigner(ONE_ALPH * 1000n, 0) const invariant = await Invariant.deploy(deployer, Network.Local, initialFee) const protocolFee = await invariant.getProtocolFee() expect(protocolFee).toBe(0n) }) test('load from address', async () => { - const initialFee = 0n + const initialFee = 0n as Percentage const deployer = await getSigner(ONE_ALPH * 1000n, 0) const invariant = await Invariant.deploy(deployer, Network.Local, initialFee) @@ -25,7 +26,7 @@ describe('invariant tests', () => { expect(protocolFee).toBe(0n) }) test('deploy and add a fee tier', async () => { - const initialFee = 0n + const initialFee = 0n as Percentage const deployer = await getSigner(ONE_ALPH * 1000n, 0) const invariant = await Invariant.deploy(deployer, Network.Local, initialFee) const [fee, tickSpacing] = getBasicFeeTickSpacing() diff --git a/test/sdk/e2e/pool-with-alph.test.ts b/test/sdk/e2e/pool-with-alph.test.ts index a04a664..c213e1d 100644 --- a/test/sdk/e2e/pool-with-alph.test.ts +++ b/test/sdk/e2e/pool-with-alph.test.ts @@ -2,25 +2,25 @@ import { ALPH_TOKEN_ID, ONE_ALPH, web3 } from '@alephium/web3' import { getSigner } from '@alephium/web3-test' import { PrivateKeyWallet } from '@alephium/web3-wallet' import { balanceOf, newFeeTier, newPoolKey } from '../../../src/utils' -import { MIN_SQRT_PRICE, PERCENTAGE_SCALE } from '../../../src/consts' +import { MIN_SQRT_PRICE } from '../../../src/consts' import { initTokensXY, withdrawTokens } from '../../../src/testUtils' import { TokenFaucetInstance } from '../../../artifacts/ts' import { Invariant } from '../../../src/invariant' import { Network } from '../../../src/network' import { getBasicFeeTickSpacing } from '../../../src/snippets' -import { toLiquidity } from '../../../src/math' -import { FeeTier, PoolKey } from '../../../src/types' +import { toLiquidity, toPercentage, toSqrtPrice } from '../../../src/math' +import { FeeTier, PoolKey, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('create pool with ALP token as swappable asset tests', () => { - const protocolFee = 10n ** (PERCENTAGE_SCALE - 2n) + const protocolFee = toPercentage(1n, 2n) const [fee, tickSpacing] = getBasicFeeTickSpacing() - const positionOwnerMint = 3000n - const swapperMint = 10n ** 15n - const supply = positionOwnerMint + swapperMint + const positionOwnerMint = 3000n as TokenAmount + const swapperMint = (10n ** 15n) as TokenAmount + const supply = (positionOwnerMint + swapperMint) as TokenAmount const initTick = 0n - const initSqrtPrice = 10n ** 24n + const initSqrtPrice = toSqrtPrice(1n) const lowerTick = -20n const upperTick = 10n const liquidityDelta = toLiquidity(1000000n) @@ -81,7 +81,7 @@ describe('create pool with ALP token as swappable asset tests', () => { lowerTick, upperTick, liquidityDelta, - 1000n, + 1000n as TokenAmount, tokenYBalance, sqrtPrice, sqrtPrice @@ -91,7 +91,7 @@ describe('create pool with ALP token as swappable asset tests', () => { expect(pool.liquidity).toBe(liquidityDelta) }) test('swap alph token', async () => { - const swapAmount = 1000n + const swapAmount = 1000n as TokenAmount const swapperBalanceBefore = { alph: await balanceOf(poolKey.tokenX, swapper.address), diff --git a/test/sdk/e2e/query-on-pair.test.ts b/test/sdk/e2e/query-on-pair.test.ts index 2d9bf7d..0b81ac1 100644 --- a/test/sdk/e2e/query-on-pair.test.ts +++ b/test/sdk/e2e/query-on-pair.test.ts @@ -5,14 +5,15 @@ import { Network } from '../../../src/network' import { initTokensXY } from '../../../src/testUtils' import { getBasicFeeTickSpacing } from '../../../src/snippets' import { newFeeTier, newPoolKey } from '../../../src/utils' +import { Percentage, TokenAmount, toSqrtPrice } from '../../../src' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('query on token pair tests', () => { - const initialFee = 0n + const initialFee = 0n as Percentage const [fee] = getBasicFeeTickSpacing() - const initSqrtPrice = 10n ** 24n - const supply = 10n ** 10n + const initSqrtPrice = toSqrtPrice(1n) + const supply = (10n ** 10n) as TokenAmount test('query on pools', async () => { const deployer = await getSigner(ONE_ALPH * 1000n, 0) diff --git a/test/sdk/e2e/simulate-invariant-swap.test.ts b/test/sdk/e2e/simulate-invariant-swap.test.ts index 52084a6..fc941de 100644 --- a/test/sdk/e2e/simulate-invariant-swap.test.ts +++ b/test/sdk/e2e/simulate-invariant-swap.test.ts @@ -30,7 +30,7 @@ import { VMError } from '../../../src/consts' import { PrivateKeyWallet } from '@alephium/web3-wallet' -import { FeeTier, PoolKey } from '../../../src/types' +import { FeeTier, Percentage, PoolKey, TokenAmount } from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') @@ -45,7 +45,7 @@ let poolKey: PoolKey describe('simulateInvariantSwap tests', () => { const protocolFee = toPercentage(1n, 2n) - const suppliedAmount = 1000000000n + const suppliedAmount = 1000000000n as TokenAmount beforeEach(async () => { deployer = await getSigner(ONE_ALPH * 1000n, 0) @@ -61,14 +61,15 @@ describe('simulateInvariantSwap tests', () => { await invariant.createPool(deployer, token0, token1, feeTier, toSqrtPrice(1n)) poolKey = await newPoolKey(token0, token1, feeTier) + const positionAmount = (suppliedAmount / 2n) as TokenAmount await invariant.createPosition( deployer, poolKey, -10n, 10n, toLiquidity(10000000n), - suppliedAmount / 2n, - suppliedAmount / 2n, + positionAmount, + positionAmount, toSqrtPrice(1n), toSqrtPrice(1n) ) @@ -81,7 +82,7 @@ describe('simulateInvariantSwap tests', () => { pool.currentTickIndex - feeTier.tickSpacing * SEARCH_RANGE * MAX_SWAP_STEPS ) - const amountIn = 6000n + const amountIn = 6000n as TokenAmount const byAmountIn = true const xToY = true @@ -129,7 +130,7 @@ describe('simulateInvariantSwap tests', () => { const sqrtPriceLimit = await calculateSqrtPrice( pool.currentTickIndex + feeTier.tickSpacing * SEARCH_RANGE * MAX_SWAP_STEPS ) - const amountIn = 6000n + const amountIn = 6000n as TokenAmount const byAmountIn = true const xToY = false @@ -176,7 +177,7 @@ describe('simulateInvariantSwap tests', () => { const sqrtPriceLimit = await calculateSqrtPrice( pool.currentTickIndex + feeTier.tickSpacing * SEARCH_RANGE * MAX_SWAP_STEPS ) - const amountIn = 5000n + const amountIn = 5000n as TokenAmount const byAmountIn = false const xToY = false const tickmap = await filterTickmap( @@ -222,7 +223,7 @@ describe('simulateInvariantSwap tests', () => { const sqrtPriceLimit = await calculateSqrtPrice( pool.currentTickIndex - feeTier.tickSpacing * SEARCH_RANGE * MAX_SWAP_STEPS ) - const amountIn = 5000n + const amountIn = 5000n as TokenAmount const byAmountIn = false const xToY = true @@ -269,7 +270,7 @@ describe('simulateInvariantSwap tests', () => { test('X to Y by amount in', async () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMinSqrtPrice(feeTier.tickSpacing) - const amountIn = 4999n + const amountIn = 4999n as TokenAmount const byAmountIn = true const xToY = true const tickmap = await filterTickmap( @@ -323,7 +324,7 @@ describe('simulateInvariantSwap tests', () => { test('Y to X by amount in', async () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMaxSqrtPrice(feeTier.tickSpacing) - const amountIn = 4999n + const amountIn = 4999n as TokenAmount const byAmountIn = true const xToY = false const tickmap = await filterTickmap( @@ -377,7 +378,7 @@ describe('simulateInvariantSwap tests', () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMaxSqrtPrice(feeTier.tickSpacing) - const amountOut = 4888n + const amountOut = 4888n as TokenAmount const byAmountIn = false const xToY = false @@ -403,7 +404,7 @@ describe('simulateInvariantSwap tests', () => { ) const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const amountMinted = amountOut * 2n + const amountMinted = (amountOut * 2n) as TokenAmount await token.mint(swapper, amountMinted, poolKey.tokenY) const { sqrtPrice: startSqrtPrice } = await invariant.getPool(poolKey) @@ -438,7 +439,7 @@ describe('simulateInvariantSwap tests', () => { test('X to Y', async () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMinSqrtPrice(feeTier.tickSpacing) - const amountOut = 4888n + const amountOut = 4888n as TokenAmount const byAmountIn = false const xToY = true const tickmap = await filterTickmap( @@ -463,7 +464,7 @@ describe('simulateInvariantSwap tests', () => { ) const swapper = await getSigner(ONE_ALPH * 1000n, 0) - const amountMinted = amountOut * 2n + const amountMinted = (amountOut * 2n) as TokenAmount await token.mint(swapper, amountMinted, poolKey.tokenX) const { sqrtPrice: startSqrtPrice } = await invariant.getPool(poolKey) @@ -502,12 +503,12 @@ describe('simulateInvariantSwap tests', () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMaxSqrtPrice(feeTier.tickSpacing) - const amountIn = 6000n + const amountIn = 6000n as TokenAmount const byAmountIn = true const xToY = false const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const suppliedAmount = 1000000n + const suppliedAmount = 1000000n as TokenAmount await token.mint(positionOwner, suppliedAmount, poolKey.tokenX) await token.mint(positionOwner, suppliedAmount, poolKey.tokenY) await invariant.createPosition( @@ -555,7 +556,7 @@ describe('simulateInvariantSwap tests', () => { const pool = await invariant.getPool(poolKey) const sqrtPriceLimit = await getMaxSqrtPrice(feeTier.tickSpacing) - const amountIn = 6000n + const amountIn = 6000n as TokenAmount const byAmountIn = true const xToY = false @@ -567,7 +568,7 @@ describe('simulateInvariantSwap tests', () => { ) const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const suppliedAmount = 1000000n + const suppliedAmount = 1000000n as TokenAmount await token.mint(positionOwner, suppliedAmount, poolKey.tokenX) await token.mint(positionOwner, suppliedAmount, poolKey.tokenY) await invariant.createPosition( @@ -606,12 +607,12 @@ describe('simulateInvariantSwap tests', () => { test('ticks', async () => { const sqrtPriceLimit = await getMinSqrtPrice(feeTier.tickSpacing) - const amountIn = 20000n + const amountIn = 20000n as TokenAmount const byAmountIn = true const xToY = true const positionOwner = await getSigner(ONE_ALPH * 1000n, 0) - const suppliedAmount = 1000000n + const suppliedAmount = 1000000n as TokenAmount await token.mint(positionOwner, suppliedAmount, poolKey.tokenX) await token.mint(positionOwner, suppliedAmount, poolKey.tokenY) await invariant.createPosition( @@ -660,11 +661,11 @@ describe('simulateInvariantSwap tests', () => { }) it('max ticks crossed', async function () { const sqrtPriceLimit = await getMinSqrtPrice(feeTier.tickSpacing) - const amountIn = 1000000n + const amountIn = 1000000n as TokenAmount const byAmountIn = true const xToY = true - const mintAmount = 1n << 120n + const mintAmount = (1n << 120n) as TokenAmount await token.mint(deployer, mintAmount, token0) await token.mint(deployer, mintAmount, token1) @@ -724,7 +725,7 @@ describe('simulateInvariantSwap tests', () => { test('X to Y by amount in', async () => { const pool = await invariant.getPool(poolKey) - const amountIn = MAX_U256 + const amountIn = MAX_U256 as TokenAmount const byAmountIn = true const xToY = true @@ -769,7 +770,7 @@ describe('simulateInvariantSwap tests', () => { test('X to Y by amount out', async () => { const pool = await invariant.getPool(poolKey) - const amountIn = MAX_U256 + const amountIn = MAX_U256 as TokenAmount const byAmountIn = false const xToY = true @@ -812,7 +813,7 @@ describe('simulateInvariantSwap tests', () => { test('Y to X by amount in', async () => { const pool = await invariant.getPool(poolKey) - const amountIn = MAX_U256 + const amountIn = MAX_U256 as TokenAmount const byAmountIn = true const xToY = false @@ -857,7 +858,7 @@ describe('simulateInvariantSwap tests', () => { it('Y to X by amount out', async () => { const pool = await invariant.getPool(poolKey) - const amountIn = MAX_U256 + const amountIn = MAX_U256 as TokenAmount const byAmountIn = false const xToY = false diff --git a/test/sdk/unit/math.test.ts b/test/sdk/unit/math.test.ts index 5a7d948..afca86a 100644 --- a/test/sdk/unit/math.test.ts +++ b/test/sdk/unit/math.test.ts @@ -13,14 +13,23 @@ import { expectError } from '../../../src/testUtils' import { UtilsError } from '../../../src/consts' import { newFeeTier, newPoolKey } from '../../../src/utils' import { getBasicFeeTickSpacing } from '../../../src/snippets' -import { Pool, Position, Tick, wrapPoolKey } from '../../../src/types' +import { + FeeGrowth, + Liquidity, + Pool, + Position, + SqrtPrice, + Tick, + TokenAmount, + wrapPoolKey +} from '../../../src/types' web3.setCurrentNodeProvider('http://127.0.0.1:22973') describe('math spec', () => { describe('get liquidity by tests', () => { test('by x', async () => { - const x = 430000n + const x = 430000n as TokenAmount const currentSqrtPrice = await calculateSqrtPrice(100n) // Bellow current tick @@ -61,7 +70,7 @@ describe('math spec', () => { } }) test('by y', async () => { - const y = 47600000000n + const y = 47600000000n as TokenAmount const currentSqrtPrice = await calculateSqrtPrice(-20000n) // Below current tick { @@ -107,12 +116,12 @@ describe('math spec', () => { } }) test('get liquidity', async () => { - const y = 47600000000n + const y = 47600000000n as TokenAmount const currentSqrtPrice = await calculateSqrtPrice(-20000n) // Below current tick { const expectedL = 278905227910392327n - const expectedX = 0n + const expectedX = 0n as TokenAmount const lowerTick = -22000n const upperTick = -21000n const expectedResult = { l: expectedL, x: expectedX, y } @@ -139,8 +148,8 @@ describe('math spec', () => { } // In current tick { - const expectedXUp = 77539808126n - const expectedXDown = 77539808125n + const expectedXUp = 77539808126n as TokenAmount + const expectedXDown = 77539808125n as TokenAmount const expectedLUp = 58494529055434693n const expectedLDown = 58494529055291192n const lowerTick = -25000n @@ -173,8 +182,8 @@ describe('math spec', () => { const lowerTick = 150n const upperTick = 800n - const x = 430000000n - const expectedY = 0n + const x = 430000000n as TokenAmount + const expectedY = 0n as TokenAmount const expectedResult = { l: 1354882631162385n, y: expectedY } const resultUp = await getLiquidity( @@ -211,13 +220,13 @@ describe('math spec', () => { ) const pool: Pool = { poolKey, - liquidity: 10000000000000n, - sqrtPrice: 999505344804856076727628n, + liquidity: 10000000000000n as Liquidity, + sqrtPrice: 999505344804856076727628n as SqrtPrice, currentTickIndex: -10n, - feeGrowthGlobalX: 49000000000000000000000n, - feeGrowthGlobalY: 0n, - feeProtocolTokenX: 1n, - feeProtocolTokenY: 0n, + feeGrowthGlobalX: 49000000000000000000000n as FeeGrowth, + feeGrowthGlobalY: 0n as FeeGrowth, + feeProtocolTokenX: 1n as TokenAmount, + feeProtocolTokenY: 0n as TokenAmount, startTimestamp: 1720687408546n, lastTimestamp: 1720687408644n, feeReceiver: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', @@ -226,34 +235,34 @@ describe('math spec', () => { } const position: Position = { poolKey, - liquidity: 10000000000000n, + liquidity: 10000000000000n as Liquidity, lowerTickIndex: -10n, upperTickIndex: 10n, - feeGrowthInsideX: 0n, - feeGrowthInsideY: 0n, + feeGrowthInsideX: 0n as FeeGrowth, + feeGrowthInsideY: 0n as FeeGrowth, lastBlockNumber: 51n, - tokensOwedX: 0n, - tokensOwedY: 0n, + tokensOwedX: 0n as TokenAmount, + tokensOwedY: 0n as TokenAmount, owner: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' } const lowerTick: Tick = { index: -10n, sign: true, - liquidityChange: 10000000000000n, - liquidityGross: 10000000000000n, - sqrtPrice: 999500149965000000000000n, - feeGrowthOutsideX: 0n, - feeGrowthOutsideY: 0n, + liquidityChange: 10000000000000n as Liquidity, + liquidityGross: 10000000000000n as Liquidity, + sqrtPrice: 999500149965000000000000n as SqrtPrice, + feeGrowthOutsideX: 0n as FeeGrowth, + feeGrowthOutsideY: 0n as FeeGrowth, secondsOutside: 98n } const upperTick: Tick = { index: 10n, sign: false, - liquidityChange: 10000000000000n, - liquidityGross: 10000000000000n, - sqrtPrice: 1000500100010000000000000n, - feeGrowthOutsideX: 0n, - feeGrowthOutsideY: 0n, + liquidityChange: 10000000000000n as Liquidity, + liquidityGross: 10000000000000n as Liquidity, + sqrtPrice: 1000500100010000000000000n as SqrtPrice, + feeGrowthOutsideX: 0n as FeeGrowth, + feeGrowthOutsideY: 0n as FeeGrowth, secondsOutside: 0n } const [x, y] = await calculateFee(pool, position, lowerTick, upperTick)