repo_id
stringclasses 279
values | file_path
stringlengths 43
179
| content
stringlengths 1
4.18M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/update_fees_and_rewards.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { PositionData } from "../../src";
import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { sleep, TickSpacing, ZERO_BN } from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import { WhirlpoolTestFixture } from "../utils/fixture";
import { initTestPool } from "../utils/init-utils";
describe("update_fees_and_rewards", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
it("successfully updates fees and rewards", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair },
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const positionBefore = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionBefore.feeGrowthCheckpointA.eq(ZERO_BN));
assert.ok(positionBefore.feeGrowthCheckpointB.eq(ZERO_BN));
assert.ok(positionBefore.rewardInfos[0].amountOwed.eq(ZERO_BN));
assert.ok(positionBefore.rewardInfos[0].growthInsideCheckpoint.eq(ZERO_BN));
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(100_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
await sleep(2_000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const positionAfter = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionAfter.feeOwedA.gt(positionBefore.feeOwedA));
assert.ok(positionAfter.feeOwedB.eq(ZERO_BN));
assert.ok(
positionAfter.feeGrowthCheckpointA.gt(
positionBefore.feeGrowthCheckpointA,
),
);
assert.ok(
positionAfter.feeGrowthCheckpointB.eq(
positionBefore.feeGrowthCheckpointB,
),
);
assert.ok(
positionAfter.rewardInfos[0].amountOwed.gt(
positionBefore.rewardInfos[0].amountOwed,
),
);
assert.ok(
positionAfter.rewardInfos[0].growthInsideCheckpoint.gt(
positionBefore.rewardInfos[0].growthInsideCheckpoint,
),
);
assert.ok(positionAfter.liquidity.eq(positionBefore.liquidity));
});
it("fails when position has zero liquidity", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const {
poolInitInfo: { whirlpoolPda },
} = await initTestPool(ctx, tickSpacing);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const other = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
});
const { positions: otherPositions } = other.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: otherPositions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fails when tick arrays do not match position", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
0,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fails when tick arrays do not match whirlpool", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
const {
poolInitInfo: { whirlpoolPda: otherWhirlpoolPda },
} = await initTestPool(ctx, tickSpacing);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
otherWhirlpoolPda.publicKey,
22528,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/increase_liquidity.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { PositionData, TickArrayData, WhirlpoolData } from "../../src";
import {
PDAUtil,
PriceMath,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { PoolUtil, toTokenAmount } from "../../src/utils/public/pool-utils";
import {
MAX_U64,
TickSpacing,
ZERO_BN,
approveToken,
assertTick,
createAndMintToTokenAccount,
createMint,
createTokenAccount,
getTokenBalance,
sleep,
transferToken,
} from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import { WhirlpoolTestFixture } from "../utils/fixture";
import { initTestPool, initTickArray, openPosition } from "../utils/init-utils";
import {
generateDefaultInitTickArrayParams,
generateDefaultOpenPositionParams,
} from "../utils/test-builders";
describe("increase_liquidity", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
it("increase liquidity of a position spanning two tick arrays", async () => {
const currTick = 0;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(167_000, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// To check if rewardLastUpdatedTimestamp is updated
await sleep(1200);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gt(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.ok(poolAfter.liquidity.eq(new anchor.BN(liquidityAmount)));
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("increase liquidity of a position contained in one tick array", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(tickArray.ticks[56], true, expectedLiquidity, expectedLiquidity);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("initialize and increase liquidity of a position in a single transaction", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const { whirlpoolPda, tickSpacing } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const { params, mint } = await generateDefaultOpenPositionParams(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
ctx.wallet.publicKey,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing),
).publicKey;
await new TransactionBuilder(
ctx.provider.connection,
ctx.provider.wallet,
ctx.txBuilderOpts,
)
// TODO: create a ComputeBudgetInstruction to request more compute
.addInstruction(
WhirlpoolIx.initTickArrayIx(
ctx.program,
generateDefaultInitTickArrayParams(
ctx,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
),
),
)
// .addInstruction(
// buildtoTx(ctx, WhirlpoolIx.initTickArrayIx(generateDefaultInitTickArrayParams(
// ctx,
// whirlpoolPda.publicKey,
// getStartTickIndex(pos[0].tickLowerIndex + TICK_ARRAY_SIZE * tickSpacing, tickSpacing),
// ))
// )
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, params))
// .addInstruction(
// buildWhirlpoolIx.openPositionWithMetadataIx(ctx.program, params)
// )
.addSigner(mint)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: params.positionPda.publicKey,
positionTokenAccount: params.positionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLower,
tickArrayUpper: tickArrayUpper,
}),
)
.buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
params.positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(tickArray.ticks[56], true, expectedLiquidity, expectedLiquidity);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("increase liquidity of a position with an approved position authority delegate", async () => {
const currTick = 1300;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(0, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.equal(poolAfter.liquidity, 0);
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("add maximum amount of liquidity near minimum price", async () => {
const currTick = -443621;
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(currTick),
);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
const tokenAccountA = await createAndMintToTokenAccount(
provider,
tokenMintA,
MAX_U64,
);
const tokenAccountB = await createAndMintToTokenAccount(
provider,
tokenMintB,
MAX_U64,
);
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, -444224);
const tickLowerIndex = -443632;
const tickUpperIndex = -443624;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("add maximum amount of liquidity near maximum price", async () => {
const currTick = 443635;
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(currTick),
);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
const tokenAccountA = await createAndMintToTokenAccount(
provider,
tokenMintA,
MAX_U64,
);
const tokenAccountB = await createAndMintToTokenAccount(
provider,
tokenMintB,
MAX_U64,
);
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 436480);
const tickLowerIndex = 436488;
const tickUpperIndex = 436496;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("fails with zero liquidity amount", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: ZERO_BN,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when token max a exceeded", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(999_999_999),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when token max b exceeded", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(999_999_999),
tokenMaxB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when position account does not have exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const newPositionTokenAccount = await createTokenAccount(
provider,
positionInitInfo.mintKeypair.publicKey,
provider.wallet.publicKey,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
// Send position token to other position token account
await transferToken(
provider,
positionInitInfo.tokenAccount,
newPositionTokenAccount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position token account mint does not match position mint", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const invalidPositionTokenAccount = await createAndMintToTokenAccount(
provider,
tokenMintA,
1,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // A raw constraint was violated
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN }],
});
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const { poolInitInfo: poolInitInfo2 } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const positionInitInfo = await openPosition(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const { positionPda, positionTokenAccount: positionTokenAccountAddress } =
positionInitInfo.params;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has_one constraint was violated
);
});
it("fails when token vaults do not match whirlpool vaults", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const fakeVaultA = await createAndMintToTokenAccount(
provider,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccount(
provider,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const invalidMint = await createMint(provider);
const invalidTokenAccount = await createAndMintToTokenAccount(
provider,
invalidMint,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: invalidTokenAccount,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccount,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
0,
);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority was not a signer", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveToken(provider, tokenAccountA, delegate.publicKey, 1_000_000);
await approveToken(provider, tokenAccountB, delegate.publicKey, 1_000_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when position authority is not approved for token owner accounts", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveToken(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x4/, // owner does not match
);
});
it("fails when tick arrays do not match the position", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 22528);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x1779/, // TicKNotFound
);
});
it("fails when the tick arrays are for a different whirlpool", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const { poolInitInfo: poolInitInfo2 } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, -11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has one constraint was violated
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/swap.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import type { PDA } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { InitPoolParams, SwapParams, TickArrayData } from "../../src";
import {
MAX_SQRT_PRICE,
MAX_SQRT_PRICE_BN,
MIN_SQRT_PRICE,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteByOutputToken,
toTx,
} from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { MAX_U64, TickSpacing, ZERO_BN, getTokenBalance } from "../utils";
import { defaultConfirmOptions } from "../utils/const";
import type { FundedPositionParams } from "../utils/init-utils";
import {
fundPositions,
initTestPool,
initTestPoolWithLiquidity,
initTestPoolWithTokens,
initTickArrayRange,
withdrawPositions,
} from "../utils/init-utils";
import type { PublicKey } from "@solana/web3.js";
describe("swap", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
it("fail on token vault mint a does not match whirlpool token a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: anotherPoolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token vault mint b does not match whirlpool token b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: anotherPoolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token owner account a does not match vault a mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { tokenAccountA: anotherTokenAccountA } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: anotherTokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fail on token owner account b does not match vault b mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { tokenAccountB: anotherTokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: anotherTokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails to swap with incorrect token authority", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const otherTokenAuthority = web3.Keypair.generate();
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: otherTokenAuthority.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
)
.addSigner(otherTokenAuthority)
.buildAndExecute(),
/0x4/, // OwnerMismatch
);
});
it("fails on passing in the wrong tick-array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
ctx,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(0.0242).sqrt()),
); // Negative Tick
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(-50000),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fails on passing in the wrong whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails on passing in the tick-arrays from another whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// This test case violates the constraint on vault (before tickarray)
/0x7d3/, // ConstraintRaw
);
});
it("fails on passing in the tick-arrays from another whirlpool (tickarray only)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherTickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// invalid tickArrays[0]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: anotherTickArrays[0].publicKey, // invalid
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// sparse-swap changes error code (has_one constraint -> check in the handler)
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
// invalid tickArrays[1]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: anotherTickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
// invalid tickArrays[2]
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: anotherTickArrays[2].publicKey, // invalid
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fails on passing in an account of another type for the oracle", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: tickArrays[0].publicKey,
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fails on passing in an incorrectly hashed oracle PDA", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherOraclePda = PDAUtil.getOracle(
ctx.program.programId,
anotherPoolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: anotherOraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fail on passing in zero tradable amount", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
// sparse-swap: We didn't provide valid initialized tick arrays.
// The current pool tick index is 32190, so we need to provide tick array with start_tick_index 22528.
// Using sparse-swap, the validity of provided tick arrays will be evaluated before evaluating trade amount.
22528,
3,
TickSpacing.Standard,
true,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(0),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount
);
});
it("swaps across one tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const tokenVaultABefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const tokenVaultBBefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(100000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenVaultABefore.sub(quote.estimatedAmountOut).toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenVaultBBefore.add(quote.estimatedAmountIn).toString(),
);
});
it("swaps aToB across initialized tick with no movement", async () => {
const startingTick = 91720;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable, startSqrtPrice);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionParams[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
let whirlpoolData = whirlpool.getData();
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionParams[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 2,
tickUpperIndex: startingTick,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will decrement since it
// is an aToB swap ending on initialized tick, and since the tick is crossed,
// the liquidity will be added
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remaing the same, the starting tick will not decrement
// since it is an aToB swap ending on an uninitialized tick, no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
});
it("swaps aToB with small remainder across initialized tick", async () => {
const startingTick = 91728;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Stable, startSqrtPrice);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionParams[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
let whirlpoolData = whirlpool.getData();
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionParams[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 3,
tickUpperIndex: startingTick - tickSpacing,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will stay the same since it
// is an aToB swap ending on initialized tick and no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(43),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
whirlpoolData = whirlpool.getData();
// After the above swap, there will be a small amount remaining that crosses
// an initialized tick index, but isn't enough to move the sqrt price.
assert.equal(
whirlpoolData.tickCurrentIndex,
startingTick - tickSpacing - 1,
);
assert.ok(
whirlpoolData.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(startingTick - tickSpacing),
),
);
assert.ok(
whirlpoolData.liquidity.eq(initialLiquidity.add(additionalLiquidity)),
);
});
it("swaps across three tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 28160, 28864
5,
TickSpacing.Stable,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27456,
tickUpperIndex: 27840,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 28864,
tickUpperIndex: 28928,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 28928,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1977429",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"869058",
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(7051000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(28500),
amountSpecifiedIsInput: true,
aToB: aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1535201",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"7920058",
);
// TODO: Verify fees and other whirlpool params
});
/* using sparse-swap, we can handle uninitialized tick-array. so this test is no longer needed.
it("Error on passing in uninitialized tick-array", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const uninitializedTickArrayPda = PDAUtil.getTickArray(ctx.program.programId, whirlpool, 0);
const oraclePda = PDAUtil.getOracle(ctx.program.programId, poolInitInfo.whirlpoolPda.publicKey);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: uninitializedTickArrayPda.publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(ctx, WhirlpoolIx.swapIx(ctx.program, params)).buildAndExecute();
assert.fail("should fail if a tick-array is uninitialized");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0xbbf/); // AccountOwnedByWrongProgram
}
});
*/
it("Error if sqrt_price_limit exceeds max", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price exceeds maximum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if sqrt_price_limit subceed min", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidity(ctx);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapParams = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price subceeds minimum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if a to b swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if b to a swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if a to b swap above maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("Error if b to a swap below maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(ctx, TickSpacing.Standard);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("swaps across ten tick arrays", async () => {
const {
poolInitInfo,
configKeypairs,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokens(
ctx,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 30528
3,
TickSpacing.Stable,
aToB,
);
// tick array range: 27658 to 29386
// tick arrays: (27456, 28152), (28160, 28856), (28864, 29,560)
// current tick: 27727
// initialized ticks:
// 27712, 27736, 27840, 28288, 28296, 28304, 28416, 28576, 28736, 29112, 29120, 29240, 29360
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 29360,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27736,
tickUpperIndex: 29240,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27840,
tickUpperIndex: 29120,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28416,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 28304,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28296,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28576,
tickUpperIndex: 28736,
},
];
const positionInfos = await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await withdrawPositions(ctx, positionInfos, tokenAccountA, tokenAccountB);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick, index) => {
if (!tick.initialized) {
return;
}
console.info(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString(),
);
});
});
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesIx(ctx.program, {
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
configKeypairs.collectProtocolFeesAuthorityKeypair.publicKey,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(configKeypairs.collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
console.info(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
});
describe("partial fill, b to a", () => {
const tickSpacing = 128;
const aToB = false;
let poolInitInfo: InitPoolParams;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokens(
ctx,
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(439296 + 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
439296, // right most TickArray
1,
tickSpacing,
aToB,
);
// a: 1 (round up)
// b: 223379095563402706 (to get 1, need >= 223379095563402706)
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: 439424,
tickUpperIndex: 439552,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
});
describe("partial fill, a to b", () => {
const tickSpacing = 128;
const aToB = true;
let poolInitInfo: InitPoolParams;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokens(
ctx,
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
-450560, // left most TickArray
1,
tickSpacing,
aToB,
);
// a: 223379098170764880 (to get 1, need >= 223379098170764880)
// b: 1 (round up)
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: -439552,
tickUpperIndex: -439424,
},
];
await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MIN_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/initialize_reward_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import type { WhirlpoolData } from "../../../src";
import {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { ONE_SOL, systemTransferTx, TickSpacing } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
initTestPoolV2,
initializeRewardV2,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
createMintV2,
} from "../../utils/v2/token-2022";
import { TEST_TOKEN_2022_PROGRAM_ID, TEST_TOKEN_PROGRAM_ID } from "../../utils";
import { AccountState } from "@solana/spl-token";
import { Keypair } from "@solana/web3.js";
describe("initialize_reward_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully initializes reward at index 0", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const { params } = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
const whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(whirlpool.rewardInfos[0].mint.equals(params.rewardMint));
assert.ok(
whirlpool.rewardInfos[0].vault.equals(
params.rewardVaultKeypair.publicKey,
),
);
await assert.rejects(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
/custom program error: 0x178a/, // InvalidRewardIndex
);
const { params: params2 } = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
1,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
const whirlpool2 = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(whirlpool2.rewardInfos[0].mint.equals(params.rewardMint));
assert.ok(
whirlpool2.rewardInfos[0].vault.equals(
params.rewardVaultKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool2.rewardInfos[0].vault,
tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool2.rewardInfos[1].mint.equals(params2.rewardMint));
assert.ok(
whirlpool2.rewardInfos[1].vault.equals(
params2.rewardVaultKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool2.rewardInfos[1].vault,
tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(
whirlpool2.rewardInfos[2].mint.equals(
anchor.web3.PublicKey.default,
),
);
assert.ok(
whirlpool2.rewardInfos[2].vault.equals(
anchor.web3.PublicKey.default,
),
);
});
it("succeeds when funder is different than account paying for transaction fee", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
0,
funderKeypair,
);
});
it("fails to initialize reward at index 1", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
await assert.rejects(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
1,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
/custom program error: 0x178a/, // InvalidRewardIndex
);
});
it("fails to initialize reward at out-of-bound index", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
await assert.rejects(
initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
3,
configExtension.configExtensionKeypairs
.tokenBadgeAuthorityKeypair,
),
);
});
it("fails to initialize if authority signature is missing", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardMint = await createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
).buildAndExecute(),
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed reward_token_program is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: false });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed reward_token_program is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: true });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: TEST_TOKEN_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed reward_token_program is token_metadata", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, { isToken2022: true });
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
rewardMint,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardTokenProgram: METADATA_PROGRAM_ADDRESS,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
describe("invalid badge account", () => {
it("fails when reward_token_badge address invalid (uninitialized)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const fakeAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when reward_token_badge address invalid (initialized, same config / different mint)", async () => {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const anotherMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
// initialize another badge
const config = poolInitInfo.whirlpoolsConfig;
const configExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
);
const anotherMintTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
anotherMint,
);
const tokenBadgeAuthority =
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair;
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension: configExtensionPda.publicKey,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: tokenBadgeAuthority.publicKey,
tokenBadgePda: anotherMintTokenBadgePda,
tokenMint: anotherMint,
}),
)
.addSigner(tokenBadgeAuthority)
.buildAndExecute();
const badge = fetcher.getTokenBadge(
anotherMintTokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(badge !== null);
const fakeAddress = anotherMintTokenBadgePda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when reward_token_badge address invalid (initialized, account owned by WhirlpoolProgram)", async () => {
const { poolInitInfo, configKeypairs } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const rewardMint = await createMintV2(provider, {
isToken2022: true,
hasPermanentDelegate: true,
});
const fakeAddress = poolInitInfo.whirlpoolPda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint,
rewardTokenBadge: fakeAddress,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
});
});
describe("Supported Tokens", () => {
async function runTest(params: {
supported: boolean;
createTokenBadge: boolean;
tokenTrait: TokenTrait;
anchorPatch?: boolean;
}) {
const { poolInitInfo, configKeypairs, configExtension } =
await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const config = poolInitInfo.whirlpoolsConfig;
const rewardToken = await createMintV2(provider, params.tokenTrait);
const tokenProgram = (await provider.connection.getAccountInfo(
rewardToken,
))!.owner;
// create token badge if wanted
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
rewardToken,
);
if (params.createTokenBadge) {
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension:
configExtension.configExtensionInitInfo
.whirlpoolsConfigExtensionPda.publicKey,
funder: provider.wallet.publicKey,
tokenBadgeAuthority:
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair
.publicKey,
tokenBadgePda,
tokenMint: rewardToken,
}),
)
.addSigner(
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
)
.buildAndExecute();
}
// try to initialize reward
const promise = toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, {
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardMint: rewardToken,
rewardTokenBadge: tokenBadgePda.publicKey,
rewardTokenProgram: tokenProgram,
rewardVaultKeypair: anchor.web3.Keypair.generate(),
rewardIndex: 0,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
if (params.supported) {
await promise;
const whirlpoolData = await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpoolData!.rewardInfos[0].mint.equals(rewardToken));
} else {
await assert.rejects(
promise,
!params.anchorPatch
? /0x179f/ // UnsupportedTokenMint
: /invalid account data for instruction/, // Anchor v0.29 doesn't recognize some new extensions (GroupPointer, Group, MemberPointer, Member)
);
}
}
it("Token: mint without FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
},
});
});
it("Token: mint with FreezeAuthority", async () => {
// not good, but allowed for compatibility to initialize_pool
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
hasFreezeAuthority: true,
},
});
});
it("Token: native mint (WSOL)", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
isNativeMint: true,
},
});
});
it("Token-2022: with TransferFeeConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
},
});
});
it("Token-2022: with InterestBearingConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasInterestBearingExtension: true,
},
});
});
it("Token-2022: with MetadataPointer & TokenMetadata", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTokenMetadataExtension: true,
hasMetadataPointerExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
});
});
it("Token-2022: with TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: with TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: with TokenBadge with TransferHook", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: with TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: with TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] with TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with TransferHook", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] with/without TokenBadge, native mint (WSOL-2022)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
isNativeMint: true,
},
});
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
isNativeMint: true,
},
});
});
// [11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Group", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Group
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with GroupPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize GroupPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Member", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Member
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with MemberPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize MemberPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with NonTransferable", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasNonTransferableExtension: true,
};
await runTest({ supported: false, createTokenBadge: true, tokenTrait });
await runTest({ supported: false, createTokenBadge: false, tokenTrait });
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/increase_liquidity_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder } from "@orca-so/common-sdk";
import * as assert from "assert";
import { BN } from "bn.js";
import Decimal from "decimal.js";
import type { PositionData, TickArrayData, WhirlpoolData } from "../../../src";
import {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
PriceMath,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { PoolUtil, toTokenAmount } from "../../../src/utils/public/pool-utils";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
approveToken as approveTokenForPosition,
assertTick,
getTokenBalance,
sleep,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { initTickArray, openPosition } from "../../utils/init-utils";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createMintV2,
createAndMintToTokenAccountV2,
approveTokenV2,
} from "../../utils/v2/token-2022";
import {
createTokenAccount as createTokenAccountForPosition,
createAndMintToTokenAccount as createAndMintToTokenAccountForPosition,
} from "../../utils/token";
import {
generateDefaultInitTickArrayParams,
generateDefaultOpenPositionParams,
} from "../../utils/test-builders";
describe("increase_liquidity_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("increase liquidity of a position spanning two tick arrays", async () => {
const currTick = 0;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(167_000, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// To check if rewardLastUpdatedTimestamp is updated
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gt(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.ok(poolAfter.liquidity.eq(new anchor.BN(liquidityAmount)));
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("increase liquidity of a position contained in one tick array", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArray.ticks[56],
true,
expectedLiquidity,
expectedLiquidity,
);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("initialize and increase liquidity of a position in a single transaction", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tickSpacing } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const { params, mint } = await generateDefaultOpenPositionParams(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
ctx.wallet.publicKey,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing),
).publicKey;
await new TransactionBuilder(
ctx.provider.connection,
ctx.provider.wallet,
ctx.txBuilderOpts,
)
// TODO: create a ComputeBudgetInstruction to request more compute
.addInstruction(
WhirlpoolIx.initTickArrayIx(
ctx.program,
generateDefaultInitTickArrayParams(
ctx,
whirlpoolPda.publicKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
),
),
)
// .addInstruction(
// buildtoTx(ctx, WhirlpoolIx.initTickArrayIx(generateDefaultInitTickArrayParams(
// ctx,
// whirlpoolPda.publicKey,
// getStartTickIndex(pos[0].tickLowerIndex + TICK_ARRAY_SIZE * tickSpacing, tickSpacing),
// ))
// )
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, params))
// .addInstruction(
// buildWhirlpoolIx.openPositionWithMetadataIx(ctx.program, params)
// )
.addSigner(mint)
.addInstruction(
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: params.positionPda.publicKey,
positionTokenAccount: params.positionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLower,
tickArrayUpper: tickArrayUpper,
}),
)
.buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
const expectedLiquidity = new anchor.BN(liquidityAmount);
const position = (await fetcher.getPosition(
params.positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(expectedLiquidity));
const tickArray = (await fetcher.getTickArray(
tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArray.ticks[56],
true,
expectedLiquidity,
expectedLiquidity,
);
assertTick(
tickArray.ticks[70],
true,
expectedLiquidity,
expectedLiquidity.neg(),
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(poolAfter.liquidity, 0);
});
it("increase liquidity of a position with an approved position authority delegate", async () => {
const currTick = 1300;
const tickLowerIndex = -1280,
tickUpperIndex = 1280;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const tokenAmount = toTokenAmount(0, 167_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute();
const position = (await fetcher.getPosition(
positionInitInfo.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(liquidityAmount));
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenAmount.tokenA.toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenAmount.tokenB.toString(),
);
assert.equal(poolAfter.liquidity, 0);
const tickArrayLower = (await fetcher.getTickArray(
positionInitInfo.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
liquidityAmount,
liquidityAmount,
);
const tickArrayUpper = (await fetcher.getTickArray(
positionInitInfo.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
liquidityAmount,
liquidityAmount.neg(),
);
});
it("add maximum amount of liquidity near minimum price", async () => {
const currTick = -443621;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Stable,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
mintAmount: MAX_U64,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, -444224);
const tickLowerIndex = -443632;
const tickUpperIndex = -443624;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("add maximum amount of liquidity near maximum price", async () => {
const currTick = 443635;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Stable,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
mintAmount: MAX_U64,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 436480);
const tickLowerIndex = 436488;
const tickUpperIndex = 436496;
const positionInfo = await openPosition(
ctx,
whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInfo.params;
const tokenAmount = {
tokenA: new BN(0),
tokenB: MAX_U64,
};
const estLiquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: estLiquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const position = (await fetcher.getPosition(
positionPda.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(position.liquidity.eq(estLiquidityAmount));
});
it("fails with zero liquidity amount", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: ZERO_BN,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when token max a exceeded", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(999_999_999),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when token max b exceeded", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(999_999_999),
tokenMaxB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
});
it("fails when position account does not have exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const newPositionTokenAccount = await createTokenAccountForPosition(
provider,
positionInitInfo.mintKeypair.publicKey,
provider.wallet.publicKey,
);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
// Send position token to other position token account
await transferToken(
provider,
positionInitInfo.tokenAccount,
newPositionTokenAccount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position token account mint does not match position mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
// Create a position token account that contains 0 tokens
const fakeMint = await createMintV2(provider, { isToken2022: false });
const invalidPositionTokenAccount =
await createAndMintToTokenAccountForPosition(provider, fakeMint, 1);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // A raw constraint was violated
);
});
it("fails when position does not match whirlpool", async () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
const positionInitInfo = await openPosition(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
tickLowerIndex,
tickUpperIndex,
);
const {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
} = positionInitInfo.params;
const {
params: { tickArrayPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(6_500_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has_one constraint was violated
);
});
it("fails when token vaults do not match whirlpool vaults", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const fakeVaultA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: 7168,
tickUpperIndex: 8960,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const liquidityAmount = new anchor.BN(6_500_000);
const invalidMintA = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const invalidTokenAccountA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
invalidMintA,
1_000_000,
);
const invalidMintB = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const invalidTokenAccountB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
invalidMintB,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: invalidTokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly 1 token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
0,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority was not a signer", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when position authority is not approved for token owner accounts", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const delegate = anchor.web3.Keypair.generate();
const liquidityAmount = new anchor.BN(1_250_000);
await approveTokenForPosition(
provider,
positionInitInfo.tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x4/, // owner does not match
);
});
it("fails when tick arrays do not match the position", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 22528);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x1779/, // TicKNotFound
);
});
it("fails when the tick arrays are for a different whirlpool", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
-11264,
);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
const liquidityAmount = new anchor.BN(1_250_000);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: new BN(0),
tokenMaxB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has one constraint was violated
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const currTick = 500;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 0);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.increaseLiquidityV2(
liquidityAmount,
tokenAmount.tokenA, // maxA
tokenAmount.tokenB, // maxB
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_reward_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type { WhirlpoolData } from "../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
METADATA_PROGRAM_ADDRESS,
NUM_REWARDS,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
approveToken,
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
transferToken,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createTokenAccountV2, createMintV2 } from "../../utils/v2/token-2022";
import { createTokenAccount as createTokenAccountForPosition } from "../../utils/token";
import { NATIVE_MINT } from "@solana/spl-token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("collect_reward_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully collect rewards", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
// Lock the collectRewards quote to the last time we called updateFeesAndRewards
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
// Perform collect rewards tx
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[i].rewardMint,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const collectedBalance = parseInt(
await getTokenBalance(provider, rewardOwnerAccount),
);
assert.equal(
collectedBalance,
expectation.rewardOwed[i]?.toNumber(),
);
const vaultBalance = parseInt(
await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
),
);
assert.equal(vaultStartBalance - collectedBalance, vaultBalance);
const position = await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
assert.equal(position?.rewardInfos[i].amountOwed, 0);
assert.ok(
position?.rewardInfos[i].growthInsideCheckpoint.gte(ZERO_BN),
);
}
});
it("successfully collect reward with a position authority delegate", async () => {
const vaultStartBalance = 1_000_000;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
)
.addSigner(delegate)
.buildAndExecute();
});
it("successfully collect reward with transferred position token", async () => {
const vaultStartBalance = 1_000_000;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
const delegatePositionAccount = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
delegate.publicKey,
);
await transferToken(
provider,
positions[0].tokenAccount,
delegatePositionAccount,
1,
);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: delegatePositionAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
)
.addSigner(delegate)
.buildAndExecute();
});
it("successfully collect reward with owner even when there is a delegate", async () => {
const vaultStartBalance = 1_000_000;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute();
});
it("fails when reward index references an uninitialized reward", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const fakeRewardMint = await createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
fakeRewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: fakeRewardMint,
rewardTokenProgram: tokenTraits.tokenTraitR.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
rewardOwnerAccount,
rewardVault: anchor.web3.PublicKey.default,
rewardIndex: 0,
}),
).buildAndExecute(),
/0xbbf/, // AccountNotInitialized
);
});
it("fails when position does not match whirlpool", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const { positions, rewards } = fixture.getInfos();
// accrue rewards
await sleep(1200);
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
});
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("fails when position token account does not have exactly one token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const otherPositionAcount = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await transferToken(
provider,
positions[0].tokenAccount,
otherPositionAcount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position token account mint does not match position mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const fakePositionTokenAccount = await createTokenAccountForPosition(
provider,
NATIVE_MINT,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: fakePositionTokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly one token", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
2,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority was not a signer", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when reward vault does not match whirlpool reward vault", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewardOwnerAccount,
rewardIndex: 0,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when reward owner account mint does not match whirlpool reward mint", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const fakeMint = await createMintV2(
provider,
tokenTraits.tokenTraitR,
);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
fakeMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 0,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when reward index is out of bounds", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitAB,
tokenTraitB: tokenTraits.tokenTraitAB,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(2)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(1200);
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewards[0].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[0].rewardMint,
rewardTokenProgram: rewards[0].tokenProgram,
rewardOwnerAccount,
rewardVault: rewards[0].rewardVaultKeypair.publicKey,
rewardIndex: 4,
}),
).buildAndExecute(),
/Program failed to complete/, // index out of bounds
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed reward_mint does not match whirlpool's reward_infos", async () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
{ isToken2022: true },
];
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: tokenTraits[0],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits[1],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits[2],
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
tokenTraits[i],
rewards[i].rewardMint,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: otherTokenPublicKey, // invalid
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is not token program (token-2022 is passed)", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: false },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: TEST_TOKEN_2022_PROGRAM_ID, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is not token-2022 program (token is passed)", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: true },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: TEST_TOKEN_PROGRAM_ID, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
}
});
it("fails when passed token_program is token_metadata", async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardOwnerAccount = await createTokenAccountV2(
provider,
{ isToken2022: true },
rewards[i].rewardMint,
provider.wallet.publicKey,
);
assert.ok(rewards[i].tokenProgram.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: METADATA_PROGRAM_ADDRESS, // invalid
rewardOwnerAccount: rewardOwnerAccount,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
}
});
it("fails when passed memo_program is token_metadata", async () => {});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_fees_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type { PositionData, TickArrayData, WhirlpoolData } from "../../../src";
import {
collectFeesQuote,
METADATA_PROGRAM_ADDRESS,
PDAUtil,
TickArrayUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
approveToken,
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
transferToken,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createMintV2, createTokenAccountV2 } from "../../utils/v2/token-2022";
import { createTokenAccount as createTokenAccountForPosition } from "../../utils/token";
import { NATIVE_MINT } from "@solana/spl-token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("collect_fees_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully collect fees", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const positionBeforeSwap = (await fetcher.getPosition(
positions[0].publicKey,
)) as PositionData;
assert.ok(positionBeforeSwap.feeOwedA.eq(ZERO_BN));
assert.ok(positionBeforeSwap.feeOwedB.eq(ZERO_BN));
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionBeforeCollect.feeOwedA.eq(new BN(581)));
assert.ok(positionBeforeCollect.feeOwedB.eq(new BN(581)));
const feeAccountA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const feeAccountB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
// Generate collect fees expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const tickArrayData = (await fetcher.getTickArray(
tickArrayPda.publicKey,
)) as TickArrayData;
const lowerTick = TickArrayUtil.getTickFromArray(
tickArrayData,
tickLowerIndex,
tickSpacing,
);
const upperTick = TickArrayUtil.getTickFromArray(
tickArrayData,
tickUpperIndex,
tickSpacing,
);
const expectation = collectFeesQuote({
whirlpool: whirlpoolData,
position: positionBeforeCollect,
tickLower: lowerTick,
tickUpper: upperTick,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Perform collect fees tx
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const positionAfter = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.equal(feeBalanceA, expectation.feeOwedA);
assert.equal(feeBalanceB, expectation.feeOwedB);
assert.ok(positionAfter.feeOwedA.eq(ZERO_BN));
assert.ok(positionAfter.feeOwedB.eq(ZERO_BN));
// Assert out of range position values
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[1].publicKey,
tickArrayLower: positions[1].tickArrayLower,
tickArrayUpper: positions[1].tickArrayUpper,
}),
).buildAndExecute();
const outOfRangePosition = await fetcher.getPosition(
positions[1].publicKey,
IGNORE_CACHE,
);
assert.ok(outOfRangePosition?.feeOwedA.eq(ZERO_BN));
assert.ok(outOfRangePosition?.feeOwedB.eq(ZERO_BN));
});
it("successfully collect fees with approved delegate", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
position.tokenAccount,
delegate.publicKey,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
)
.addSigner(delegate)
.buildAndExecute();
});
it("successfully collect fees with owner even if there is approved delegate", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
position.tokenAccount,
delegate.publicKey,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
});
it("successfully collect fees with transferred position token", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const position = positions[0];
const newOwner = anchor.web3.Keypair.generate();
const newOwnerPositionTokenAccount =
await createTokenAccountForPosition(
provider,
position.mintKeypair.publicKey,
newOwner.publicKey,
);
await transferToken(
provider,
position.tokenAccount,
newOwnerPositionTokenAccount,
1,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: newOwner.publicKey,
position: position.publicKey,
positionTokenAccount: newOwnerPositionTokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
)
.addSigner(newOwner)
.buildAndExecute();
});
it("fails when position does not match whirlpool", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("fails when position token account does not contain exactly one token", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const positionTokenAccount2 = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positionTokenAccount2,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await transferToken(
provider,
positions[0].tokenAccount,
positionTokenAccount2,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const delegate = anchor.web3.Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized to transfer exactly one token", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
2,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority is not a signer", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const delegate = anchor.web3.Keypair.generate();
await approveToken(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when position token account mint does not equal position mint", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const fakePositionTokenAccount = await createTokenAccountForPosition(
provider,
NATIVE_MINT,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: fakePositionTokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when token vault does not match whirlpool token vault", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const fakeVaultA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const fakeVaultB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const invalidOwnerAccountA = await createTokenAccountV2(
provider,
// invalid token trait & mint
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
const invalidOwnerAccountB = await createTokenAccountV2(
provider,
// invalid token trait & mint
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: invalidOwnerAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidOwnerAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
//tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
//tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.collectFeesV2(
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenProgramA,
tokenProgramB,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/two_hop_swap_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage, U64_MAX } from "@orca-so/common-sdk";
import { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import { BN } from "bn.js";
import type { InitPoolParams, WhirlpoolData } from "../../../src";
import {
buildWhirlpoolClient,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
SwapUtils,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import type {
InitPoolV2Params,
TwoHopSwapV2Params,
} from "../../../src/instructions";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { InitAquariumV2Params } from "../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../utils/v2/aquarium-v2";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
createMintV2,
} from "../../utils/v2/token-2022";
import {
NO_TOKEN_EXTENSION_CONTEXT,
TokenExtensionUtil,
} from "../../../src/utils/public/token-extension-util";
describe("two_hop_swap_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
// 8 patterns for tokenTraitA, tokenTraitB, tokenTraitC
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tokenTraitC: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitC: ${tokenTraits.tokenTraitC.isToken2022 ? "Token2022" : "Token"}`, () => {
let aqConfig: InitAquariumV2Params;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
});
describe("fails [2] with two-hop swap, invalid accounts", () => {
let baseIxParams: TwoHopSwapV2Params;
beforeEach(async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[0],
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[1],
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertOwnerProgram(
ctx.provider,
mintKeys[2],
tokenTraits.tokenTraitC.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo =
whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
it("fails invalid whirlpool", async () => {
await rejectParams(
{
...baseIxParams,
whirlpoolOne: baseIxParams.whirlpoolTwo,
},
///0x7d3/ // ConstraintRaw
// V2 has token_mint_one_a and it has address constraint
/0x7dc/, // ConstraintAddress
);
});
it("fails invalid token account", async () => {
await rejectParams(
{
...baseIxParams,
tokenOwnerAccountInput: baseIxParams.tokenOwnerAccountOutput,
},
/0x7d3/, // ConstraintRaw
);
await rejectParams(
{
...baseIxParams,
tokenOwnerAccountOutput: baseIxParams.tokenOwnerAccountInput,
},
/0x7d3/, // ConstraintRaw
);
});
it("fails invalid token vault", async () => {
await rejectParams(
{
...baseIxParams,
tokenVaultOneInput: baseIxParams.tokenVaultOneIntermediate,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultOneIntermediate: baseIxParams.tokenVaultOneInput,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultTwoIntermediate: baseIxParams.tokenVaultTwoOutput,
},
/0x7dc/, // ConstraintAddress
);
await rejectParams(
{
...baseIxParams,
tokenVaultTwoOutput: baseIxParams.tokenVaultTwoIntermediate,
},
/0x7dc/, // ConstraintAddress
);
});
it("fails invalid oracle one address", async () => {
await rejectParams(
{
...baseIxParams,
oracleOne: PublicKey.unique(),
},
/0x7d6/, // Constraint Seeds
);
});
it("fails invalid oracle two address", async () => {
await rejectParams(
{
...baseIxParams,
oracleTwo: PublicKey.unique(),
},
/0x7d6/, // Constraint Seeds
);
});
it("fails invalid tick array one", async () => {
await rejectParams(
{
...baseIxParams,
// sparse-swap can accept completely uninitialized account as candidate for uninitialized tick arrays.
// so now we use token account as clearly invalid account.
tickArrayOne0: baseIxParams.tokenVaultOneInput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayOne1: baseIxParams.tokenVaultOneInput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayOne2: baseIxParams.tokenVaultOneInput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fails invalid tick array two", async () => {
await rejectParams(
{
...baseIxParams,
// sparse-swap can accept completely uninitialized account as candidate for uninitialized tick arrays.
// so now we use token account as clearly invalid account.
tickArrayTwo0: baseIxParams.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayTwo1: baseIxParams.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
await rejectParams(
{
...baseIxParams,
tickArrayTwo2: baseIxParams.tokenVaultTwoOutput,
},
/0xbbf/, // AccountOwnedByWrongProgram
);
});
});
it("swaps [2] with two-hop swap, amountSpecifiedIsInput=true", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
let tokenBalances = await getTokenBalances(
tokenAccounts.map((acc) => acc.account),
);
const tokenVaultBalances = await getTokenBalancesForVaults(pools);
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
assert.deepEqual(await getTokenBalancesForVaults(pools), [
tokenVaultBalances[0].add(quote.estimatedAmountIn),
tokenVaultBalances[1].sub(quote.estimatedAmountOut),
tokenVaultBalances[2].add(quote2.estimatedAmountIn),
tokenVaultBalances[3].sub(quote2.estimatedAmountOut),
]);
const prevTbs = [...tokenBalances];
tokenBalances = await getTokenBalances(
tokenAccounts.map((acc) => acc.account),
);
assert.deepEqual(tokenBalances, [
prevTbs[0].sub(quote.estimatedAmountIn),
prevTbs[1],
prevTbs[2].add(quote2.estimatedAmountOut),
]);
//whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
});
it("swaps [2] with two-hop swap, amountSpecifiedIsInput=true, A->B->A", async () => {
// Add another mint and update pool so there is no overlapping mint
aqConfig.initFeeTierParams.push({
tickSpacing: TickSpacing.ThirtyTwo,
});
aqConfig.initPoolParams[1] = {
mintIndices: [0, 1],
tickSpacing: TickSpacing.ThirtyTwo,
feeTierIndex: 1,
};
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 12,
aToB: true,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 12,
aToB: false,
});
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
let tokenBalances = await getTokenBalances(
tokenAccounts.map((acc) => acc.account),
);
const tokenVaultBalances = await getTokenBalancesForVaults(pools);
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [tokenA, tokenB, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
tokenA,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
tokenB,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(tokenA);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(tokenB);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
assert.deepEqual(await getTokenBalancesForVaults(pools), [
tokenVaultBalances[0].add(quote.estimatedAmountIn),
tokenVaultBalances[1].sub(quote.estimatedAmountOut),
tokenVaultBalances[2].sub(quote2.estimatedAmountOut),
tokenVaultBalances[3].add(quote2.estimatedAmountIn),
]);
const prevTbs = [...tokenBalances];
tokenBalances = await getTokenBalances(
tokenAccounts.map((acc) => acc.account),
);
assert.deepEqual(tokenBalances, [
prevTbs[0]
.sub(quote.estimatedAmountIn)
.add(quote2.estimatedAmountOut),
prevTbs[1]
.add(quote.estimatedAmountOut)
.sub(quote2.estimatedAmountIn),
prevTbs[2],
]);
});
it("fails swaps [2] with top-hop swap, amountSpecifiedIsInput=true, slippage", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
otherAmountThreshold: new BN(613309),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1794/, // Above Out Below Minimum
);
});
it("swaps [2] with two-hop swap, amountSpecifiedIsInput=false", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const preSwapBalances = await getTokenBalances(
tokenAccounts.map((acc) => acc.account),
);
const tokenVaultBalances = await getTokenBalancesForVaults(pools);
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quote2.estimatedAmountIn,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
assert.deepEqual(await getTokenBalancesForVaults(pools), [
tokenVaultBalances[0].add(quote.estimatedAmountIn),
tokenVaultBalances[1].sub(quote.estimatedAmountOut),
tokenVaultBalances[2].add(quote2.estimatedAmountIn),
tokenVaultBalances[3].sub(quote2.estimatedAmountOut),
]);
assert.deepEqual(
await getTokenBalances(tokenAccounts.map((acc) => acc.account)),
[
preSwapBalances[0].sub(quote.estimatedAmountIn),
preSwapBalances[1],
preSwapBalances[2].add(quote2.estimatedAmountOut),
],
);
});
it("fails swaps [2] with two-hop swap, amountSpecifiedIsInput=false slippage", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
/*
const quote2 = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quote2.estimatedAmountIn,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
otherAmountThreshold: new BN(2),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1795/, // Above In Above Maximum
);
});
it("fails swaps [2] with two-hop swap, no overlapping mints", async () => {
// Add another mint and update pool so there is no overlapping mint
aqConfig.initMintParams.push({ tokenTrait: { isToken2022: true } });
aqConfig.initTokenAccParams.push({ mintIndex: 3 });
aqConfig.initPoolParams[1].mintIndices = [2, 3];
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//const whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//const whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quote2.estimatedAmountIn,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1799/, // Invalid intermediary mint
);
});
it("swaps [2] with two-hop swap, amount_specified_is_input=true, first swap price limit", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is less than the 1% slippage threshold,
// which will allow the swap to go through
quote.sqrtPriceLimit = quote.estimatedEndSqrtPrice.add(
whirlpoolDataOne.sqrtPrice
.sub(quote.estimatedEndSqrtPrice)
.mul(new anchor.BN("5"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postWhirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
//const postWhirlpoolDataTwo = await fetcher.getPool(whirlpoolTwoKey, IGNORE_CACHE) as WhirlpoolData;
assert.equal(
postWhirlpoolDataOne.sqrtPrice.eq(quote.sqrtPriceLimit),
true,
);
});
it("fails: swaps [2] with two-hop swap, amount_specified_is_input=true, second swap price limit", async () => {
// ATTENTION: v1 and v2 are different
// v2 use vault to vault transfer, so the output of first swap MUST be equal to the input of the second swap.
// So not-full-filled swap will be rejected.
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/*
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is less than the 1% slippage threshold,
// which will result non-full-filled second swap
quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add(
whirlpoolDataTwo.sqrtPrice
.sub(quote2.estimatedEndSqrtPrice)
.mul(new anchor.BN("5"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
});
it("fails: swaps [2] with two-hop swap, amount_specified_is_input=false, first swap price limit", async () => {
// ATTENTION: v1 and v2 are different
// v2 use vault to vault transfer, so the output of first swap MUST be equal to the input of the second swap.
// So not-full-filled swap will be rejected.
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(intermediaryToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: quote2.estimatedAmountIn,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// add sqrtPriceLimit on quote
quote.sqrtPriceLimit = aToBOne
? quote.estimatedEndSqrtPrice.addn(1)
: quote.estimatedEndSqrtPrice.subn(1);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
});
it("fails swaps [2] with two-hop swap, amount_specified_is_input=true, first swap price limit", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/*
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is less than the 1% slippage threshold,
// which will allow the swap to go through
quote.sqrtPriceLimit = quote.estimatedEndSqrtPrice.add(
whirlpoolDataOne.sqrtPrice
.sub(quote.estimatedEndSqrtPrice)
.mul(new anchor.BN("15"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
);
});
it("fails swaps [2] with two-hop swap, amount_specified_is_input=true, second swap price limit", async () => {
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
//let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
//let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1000),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
const quote2 = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quote.estimatedAmountOut,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
// Set a price limit that is greater than the 1% slippage threshold,
// which will cause the swap to fail
quote2.sqrtPriceLimit = quote2.estimatedEndSqrtPrice.add(
whirlpoolDataTwo.sqrtPrice
.sub(quote2.estimatedEndSqrtPrice)
.mul(new anchor.BN("15"))
.div(new anchor.BN("1000")),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
);
});
});
});
});
describe("v2 specific accounts", () => {
describe("with Token-2022", () => {
const tokenTraits = {
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitC: { isToken2022: true },
};
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let otherTokenPublicKey: PublicKey;
beforeEach(async () => {
otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
describe("fails when passed token_mint_* does not match whirlpool's token_mint_*_*", () => {
it("token_mint_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintInput: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_mint_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintIntermediate: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_mint_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenMintOutput: otherTokenPublicKey,
},
/0x7dc/, // ConstraintAddress
);
});
});
describe("fails when passed token_program_* is not token-2022 program (token is passed)", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: TEST_TOKEN_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
});
describe("fails when passed token_program_*_* is token_metadata", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: METADATA_PROGRAM_ADDRESS,
},
/0xbc0/, // InvalidProgramId
);
});
});
it("fails when passed memo_program is token_metadata", async () => {
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
{ slices: [] },
{
accounts: {
...baseIxParams,
memoProgram: METADATA_PROGRAM_ADDRESS,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
describe("with Token", () => {
const tokenTraits = {
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitC: { isToken2022: false },
};
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
beforeEach(async () => {
await createMintV2(provider, {
isToken2022: false,
});
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: tokenTraits.tokenTraitA },
{ tokenTrait: tokenTraits.tokenTraitB },
{ tokenTrait: tokenTraits.tokenTraitC },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
...getParamsFromPools(
[pools[0], pools[1]],
[twoHopQuote.aToBOne, twoHopQuote.aToBTwo],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
};
});
describe("fails when passed token_program_* is not token program (token-2022 is passed)", () => {
it("token_program_input", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_intermediate", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
it("token_program_output", async () => {
await rejectParams(
{
...baseIxParams,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
},
/0x7dc/, // ConstraintAddress
);
});
});
});
});
describe("partial fill", () => {
const client = buildWhirlpoolClient(ctx);
const aqConfig = {
...getDefaultAquariumV2(),
initMintParams: [
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
],
initTokenAccParams: [
{ mintIndex: 0 },
{ mintIndex: 1 },
{ mintIndex: 2 },
],
initPoolParams: [
{ mintIndices: [0, 1] as [number, number], tickSpacing: 128 },
{ mintIndices: [1, 2] as [number, number], tickSpacing: 128 },
],
};
// Partial fill on second swap in ExactOut is allowed
// |--***T**-S-| --> |--***T,limit**-S-| (where *: liquidity, S: start, T: end)
it("ExactOut, partial fill on second swap", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: aqConfig.initFeeTierParams,
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [_inputToken, intermediaryToken, _outputToken] = mintKeys;
const quoteParams = {
amountSpecifiedIsInput: false,
aToB: true,
otherAmountThreshold: U64_MAX,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolTwo.getData().tickCurrentIndex,
whirlpoolTwo.getData().tickSpacing,
true,
ctx.program.programId,
whirlpoolTwoKey,
ctx.fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
whirlpoolData: whirlpoolOne.getData(),
tokenAmount: new BN(1_000_000),
};
// 906251 --> 1000000 (end tick: 1004)
const quoteSecondWithoutLimit = swapQuoteWithParams(
{
...quoteParams,
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex < 1008);
// 762627 --> 841645 (end tick: 1008)
const quoteSecondWithLimit = swapQuoteWithParams(
{
...quoteParams,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(1008),
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteSecondWithLimit.estimatedEndTickIndex == 1008);
assert.ok(
quoteSecondWithLimit.estimatedAmountOut.lt(
quoteSecondWithoutLimit.estimatedAmountOut,
),
);
assert.ok(
quoteSecondWithLimit.estimatedAmountIn.lt(
quoteSecondWithoutLimit.estimatedAmountIn,
),
);
// 821218 --> 906251
const quoteFirstWithoutLimit = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quoteSecondWithoutLimit.estimatedAmountIn,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// 690975 --> 762627
const quoteFirstWithLimit = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quoteSecondWithLimit.estimatedAmountIn,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// build without limit
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirstWithoutLimit,
quoteSecondWithoutLimit,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
amount: quoteSecondWithoutLimit.estimatedAmountOut,
sqrtPriceLimitOne: new BN(0), // partial fill on second swap is NOT allowd
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1008), // partial fill is allowed
// -1 to check input amount
otherAmountThreshold: quoteFirstWithLimit.estimatedAmountIn.subn(1),
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum.
);
assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
amount: quoteSecondWithoutLimit.estimatedAmountOut,
sqrtPriceLimitOne: new BN(0), // partial fill on second swap is NOT allowd
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1008), // partial fill is allowed
otherAmountThreshold: quoteFirstWithLimit.estimatedAmountIn,
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
});
// Reject partial fill result
// |--***T**-S-| --> |-min,T----**-S-| (where *: liquidity, S: start, T: end)
it("fails ExactOut, partial fill on second swap, sqrt_price_limit_two == 0", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: aqConfig.initFeeTierParams,
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: -450560,
arrayCount: 1,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: -512,
tickUpperIndex: -128,
liquidityAmount: new BN(5_000_000_000_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: -439296 - 256,
tickUpperIndex: -439296 - 128,
liquidityAmount: new BN(1_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
const quoteSecond = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const quoteFirst = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quoteSecond.estimatedAmountIn,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirst,
quoteSecond,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed
sqrtPriceLimitTwo: new BN(0), // Partial fill is NOT allowed
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed
sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
});
// Reject partial fill on the first swap by sqrt_price_limit_one = 0
// |-min,T----**-S-| --> |--***T**-S-| (where *: liquidity, S: start, T: end)
it("fails ExactOut, partial fill on first swap, sqrt_price_limit_one == 0", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: [{ tickSpacing: 128, feeRate: 0 }], // to realize input = 1 on second swap
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: -450560,
arrayCount: 1,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: -439296 - 256,
tickUpperIndex: -439296 - 128,
liquidityAmount: new BN(1_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(5_000_000_000_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
// 1 --> 1
const quoteSecond = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// 22337909818 --> 0 (not round up)
const quoteFirst = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quoteSecond.estimatedAmountIn,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirst,
quoteSecond,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: new BN(0), // Partial fill is NOT allowed
sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// Reject partial fill on the first swap by the constraint that first output must be equal to the second input
// This case must be rejected due to vault to vault transfer
// |-min,T----**-S-| --> |--***T**-S-| (where *: liquidity, S: start, T: end)
it("fails ExactOut, partial fill on first swap, sqrt_price_limit_one != 0", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: [{ tickSpacing: 128, feeRate: 0 }], // to realize input = 1 on second swap
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: -450560,
arrayCount: 1,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: -439296 - 256,
tickUpperIndex: -439296 - 128,
liquidityAmount: new BN(1_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(5_000_000_000_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [_inputToken, intermediaryToken, outputToken] = mintKeys;
// 1 --> 1
const quoteSecond = await swapQuoteByOutputToken(
whirlpoolTwo,
outputToken,
new BN(1),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// 22337909818 --> 0 (not round up)
const quoteFirst = await swapQuoteByOutputToken(
whirlpoolOne,
intermediaryToken,
quoteSecond.estimatedAmountIn,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirst,
quoteSecond,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed
sqrtPriceLimitTwo: MIN_SQRT_PRICE_BN, // Partial fill is allowed
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
});
// Partial fill on the first swap in ExactIn is allowed.
// |--***T,limit**-S-| -> |--***T**-S--| (where *: liquidity, S: start, T: end)
it("ExactIn, partial fill on first swap", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: aqConfig.initFeeTierParams,
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [_inputToken, intermediaryToken, _outputToken] = mintKeys;
const quoteParams = {
amountSpecifiedIsInput: true,
aToB: true,
otherAmountThreshold: new BN(0),
tickArrays: await SwapUtils.getTickArrays(
whirlpoolOne.getData().tickCurrentIndex,
whirlpoolOne.getData().tickSpacing,
true,
ctx.program.programId,
whirlpoolOneKey,
ctx.fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
whirlpoolData: whirlpoolOne.getData(),
tokenAmount: new BN(1_000_000),
};
// 1000000 --> 1103339
const quoteFirstWithoutLimit = swapQuoteWithParams(
{
...quoteParams,
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteFirstWithoutLimit.estimatedEndTickIndex < 1010);
// 667266 --> 736476
const quoteFirstWithLimit = swapQuoteWithParams(
{
...quoteParams,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(1010),
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteFirstWithLimit.estimatedEndTickIndex == 1010);
assert.ok(
quoteFirstWithLimit.estimatedAmountIn.lt(
quoteFirstWithoutLimit.estimatedAmountIn,
),
);
assert.ok(
quoteFirstWithLimit.estimatedAmountOut.lt(
quoteFirstWithoutLimit.estimatedAmountOut,
),
);
// 1103339 --> 1217224
const quoteSecondWithoutLimit = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quoteFirstWithoutLimit.estimatedAmountOut,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// 736476 --> 812807
const quoteSecondWithLimit = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quoteFirstWithLimit.estimatedAmountOut,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// build without limit
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirstWithoutLimit,
quoteSecondWithoutLimit,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
amount: quoteFirstWithoutLimit.estimatedAmountIn,
sqrtPriceLimitOne: PriceMath.tickIndexToSqrtPriceX64(1010), // partial fill is allowed
sqrtPriceLimitTwo: new BN(0), // partial fill on second swap is NOT allowd
// +1 to check output amount
otherAmountThreshold:
quoteSecondWithLimit.estimatedAmountOut.addn(1),
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
assert.ok(quoteSecondWithoutLimit.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
amount: quoteFirstWithoutLimit.estimatedAmountIn,
sqrtPriceLimitOne: PriceMath.tickIndexToSqrtPriceX64(1010), // partial fill is allowed
sqrtPriceLimitTwo: new BN(0), // partial fill on second swap is NOT allowd
otherAmountThreshold: quoteSecondWithLimit.estimatedAmountOut,
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
});
// Reject partial fill on the second swap by the constraint that second output must be equal to the first input
// Pools and owner are safe, but owner will receive unconsumed intermediate tokens
// |--***T**-S-| -> |--***T,limit**-S--| (where *: liquidity, S: start, T: end)
it("fails ExactIn, partial fill on second swap", async () => {
const aquarium = (
await buildTestAquariumsV2(ctx, [
{
configParams: aqConfig.configParams,
initFeeTierParams: aqConfig.initFeeTierParams,
initMintParams: aqConfig.initMintParams,
initTokenAccParams: [
{ mintIndex: 0, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 1, mintAmount: new BN(1_000_000_000_000_000) },
{ mintIndex: 2, mintAmount: new BN(1_000_000_000_000_000) },
],
initPoolParams: [
{
...aqConfig.initPoolParams[0],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
{
...aqConfig.initPoolParams[1],
tickSpacing: 128,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1024 + 1),
},
],
initTickArrayRangeParams: [
{
poolIndex: 0,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
{
poolIndex: 1,
startTickIndex: 0,
arrayCount: 3,
aToB: true,
},
],
initPositionParams: [
{
poolIndex: 0,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
{
poolIndex: 1,
fundParams: [
{
tickLowerIndex: 512,
tickUpperIndex: 1024,
liquidityAmount: new BN(1_000_000_000),
},
],
},
],
},
])
)[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
let whirlpoolOne = await client.getPool(whirlpoolOneKey, IGNORE_CACHE);
let whirlpoolTwo = await client.getPool(whirlpoolTwoKey, IGNORE_CACHE);
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
// 1000000 --> 1103339
const quoteFirst = await swapQuoteByInputToken(
whirlpoolOne,
inputToken,
new BN(1_000_000),
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// 1103339 1217224
const quoteSecond = await swapQuoteByInputToken(
whirlpoolTwo,
intermediaryToken,
quoteFirst.estimatedAmountOut,
Percentage.fromFraction(0, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(
quoteFirst,
quoteSecond,
);
assert.ok(quoteSecond.estimatedEndTickIndex < 1002);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitOne: MIN_SQRT_PRICE_BN, // Partial fill is allowed
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(1002), // Partial fill
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute(),
/0x17a3/, // IntermediateTokenAmountMismatch
);
assert.ok(quoteSecond.estimatedEndTickIndex > 999);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...twoHopQuote,
sqrtPriceLimitTwo: PriceMath.tickIndexToSqrtPriceX64(999),
...getParamsFromPools(
[pools[0], pools[1]],
[true, true],
tokenAccounts,
),
tokenAuthority: ctx.wallet.publicKey,
}),
).buildAndExecute();
});
});
async function rejectParams(
params: TwoHopSwapV2Params,
error: assert.AssertPredicate,
) {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, params),
).buildAndExecute(),
error,
);
}
function getParamsFromPools(
pools: [InitPoolV2Params, InitPoolV2Params],
aToBs: boolean[],
tokenAccounts: {
mint: PublicKey;
account: PublicKey;
tokenTrait: TokenTrait;
}[],
) {
const [aToBOne, aToBTwo] = aToBs;
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const whirlpoolOne = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwo = pools[1].whirlpoolPda.publicKey;
const tokenMintOneA = pools[0].tokenMintA;
const tokenMintOneB = pools[0].tokenMintB;
const tokenMintTwoA = pools[1].tokenMintA;
const tokenMintTwoB = pools[1].tokenMintB;
const tokenProgramOneA = pools[0].tokenProgramA;
const tokenProgramOneB = pools[0].tokenProgramB;
const tokenProgramTwoA = pools[1].tokenProgramA;
const tokenProgramTwoB = pools[1].tokenProgramB;
const oracleOne = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOne,
).publicKey;
const oracleTwo = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwo,
).publicKey;
return {
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
oracleOne,
oracleTwo,
// mints
tokenMintInput: aToBOne ? tokenMintOneA : tokenMintOneB,
tokenMintIntermediate: aToBOne ? tokenMintOneB : tokenMintOneA,
tokenMintOutput: aToBTwo ? tokenMintTwoB : tokenMintTwoA,
// token programs
tokenProgramInput: aToBOne ? tokenProgramOneA : tokenProgramOneB,
tokenProgramIntermediate: aToBOne ? tokenProgramOneB : tokenProgramOneA,
tokenProgramOutput: aToBTwo ? tokenProgramTwoB : tokenProgramTwoA,
// accounts
tokenOwnerAccountInput: aToBOne ? tokenAccKeys[0] : tokenAccKeys[1],
tokenVaultOneInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo ? tokenAccKeys[3] : tokenAccKeys[2],
};
}
async function getTokenBalancesForVaults(pools: InitPoolParams[]) {
const accs: PublicKey[] = [];
for (const pool of pools) {
accs.push(pool.tokenVaultAKeypair.publicKey);
accs.push(pool.tokenVaultBKeypair.publicKey);
}
return getTokenBalances(accs);
}
async function getTokenBalances(keys: PublicKey[]) {
return Promise.all(
keys.map(
async (key) => new anchor.BN(await getTokenBalance(provider, key)),
),
);
}
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/swap_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import type { PDA } from "@orca-so/common-sdk";
import * as assert from "assert";
import { BN } from "bn.js";
import Decimal from "decimal.js";
import type {
InitPoolV2Params,
SwapV2Params,
TickArrayData,
WhirlpoolData,
} from "../../../src";
import {
MAX_SQRT_PRICE,
MAX_SQRT_PRICE_BN,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE,
MIN_SQRT_PRICE_BN,
PDAUtil,
PriceMath,
SwapUtils,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
getTokenBalance,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { initTickArrayRange } from "../../utils/init-utils";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolV2,
initTestPoolWithLiquidityV2,
initTestPoolWithTokensV2,
withdrawPositionsV2,
} from "../../utils/v2/init-utils-v2";
import { createMintV2 } from "../../utils/v2/token-2022";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import type { PublicKey } from "@solana/web3.js";
describe("swap_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitR: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("fail on token vault mint a does not match whirlpool token a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: anotherPoolInitInfo.tokenVaultAKeypair.publicKey, // invalid
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token vault mint b does not match whirlpool token b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: anotherPoolInitInfo.tokenVaultBKeypair.publicKey, // invalid
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fail on token owner account a does not match vault a mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { tokenAccountA: anotherTokenAccountA } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: anotherTokenAccountA, // invalid
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fail on token owner account b does not match vault b mint", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { tokenAccountB: anotherTokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: anotherTokenAccountB, // invalid
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails to swap with incorrect token authority", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const otherTokenAuthority = web3.Keypair.generate();
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: otherTokenAuthority.publicKey, // invalid
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
)
.addSigner(otherTokenAuthority)
.buildAndExecute(),
/0x4/, // OwnerMismatch
);
});
it("fails on passing in the wrong tick-array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(0.0242).sqrt()),
); // Negative Tick
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(-50000),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fails on passing in the wrong whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: anotherPoolInitInfo.whirlpoolPda.publicKey, // invalid
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress at token_mint_a (V1: 0x7d3 (ConstraaintRaw) at token_owner_account_a)
);
});
it("fails on passing in the tick-arrays from another whirlpool", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
anotherPoolInitInfo.whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey, // invalid
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
// sparse-swap changes error code (has_one constraint -> check in the handler)
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fails on passing in an account of another type for the oracle", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: tickArrays[0].publicKey, // invalid
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fails on passing in an incorrectly hashed oracle PDA", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const { poolInitInfo: anotherPoolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const anotherOraclePda = PDAUtil.getOracle(
ctx.program.programId,
anotherPoolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: anotherOraclePda.publicKey, // invalid
}),
).buildAndExecute(),
/0x7d6/, // ConstraintSeeds
);
});
it("fail on passing in zero tradable amount", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
// sparse-swap: We didn't provide valid initialized tick arrays.
// The current pool tick index is 32190, so we need to provide tick array with start_tick_index 22528.
// Using sparse-swap, the validity of provided tick arrays will be evaluated before evaluating trade amount.
22528,
3,
TickSpacing.Standard,
true,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(0),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount
);
});
it("swaps across one tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const tokenVaultABefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const tokenVaultBBefore = new anchor.BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
/* replaceed by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(100000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
tokenVaultABefore.sub(quote.estimatedAmountOut).toString(),
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
tokenVaultBBefore.add(quote.estimatedAmountIn).toString(),
);
});
it("swaps aToB across initialized tick with no movement", async () => {
const startingTick = 91720;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
startSqrtPrice,
);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionV2Params[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionV2Params[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 2,
tickUpperIndex: startingTick,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will decrement since it
// is an aToB swap ending on initialized tick, and since the tick is crossed,
// the liquidity will be added
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remaing the same, the starting tick will not decrement
// since it is an aToB swap ending on an uninitialized tick, no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick - 1);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
});
it("swaps aToB with small remainder across initialized tick", async () => {
const startingTick = 91728;
const tickSpacing = TickSpacing.Stable;
const startingTickArrayStartIndex = TickUtil.getStartTickIndex(
startingTick,
tickSpacing,
);
const aToB = true;
const startSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(startingTick);
const initialLiquidity = new anchor.BN(10_000_000);
const additionalLiquidity = new anchor.BN(2_000_000);
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
startSqrtPrice,
);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
startingTickArrayStartIndex + TICK_ARRAY_SIZE * tickSpacing * 2,
5,
TickSpacing.Stable,
aToB,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const initialParams: FundedPositionV2Params[] = [
{
liquidityAmount: initialLiquidity,
tickLowerIndex: startingTickArrayStartIndex + tickSpacing,
tickUpperIndex:
startingTickArrayStartIndex +
TICK_ARRAY_SIZE * tickSpacing * 2 -
tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
initialParams,
);
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Position covers the current price, so liquidity should be equal to the initial funded position
assert.ok(whirlpoolData.liquidity.eq(new anchor.BN(10_000_000)));
const nextParams: FundedPositionV2Params[] = [
{
liquidityAmount: additionalLiquidity,
tickLowerIndex: startingTick - tickSpacing * 3,
tickUpperIndex: startingTick - tickSpacing,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
nextParams,
);
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// Whirlpool.currentTick is 91720, so the newly funded position's upper tick is not
// strictly less than 91720 so the liquidity is not added.
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(1),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, since the amount is so low, it is completely taken by fees
// thus, the sqrt price will remain the same, the starting tick will stay the same since it
// is an aToB swap ending on initialized tick and no tick is crossed
assert.equal(whirlpoolData.tickCurrentIndex, startingTick);
assert.ok(whirlpoolData.sqrtPrice.eq(startSqrtPrice));
assert.ok(whirlpoolData.liquidity.eq(initialLiquidity));
/* replaced by swapQuoteWithParams to avoid using whirlpool client
const quote2 = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(43),
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE
);
*/
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(43),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote2,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// After the above swap, there will be a small amount remaining that crosses
// an initialized tick index, but isn't enough to move the sqrt price.
assert.equal(
whirlpoolData.tickCurrentIndex,
startingTick - tickSpacing - 1,
);
assert.ok(
whirlpoolData.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(startingTick - tickSpacing),
),
);
assert.ok(
whirlpoolData.liquidity.eq(
initialLiquidity.add(additionalLiquidity),
),
);
});
it("swaps across three tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 28160, 28864
5,
TickSpacing.Stable,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27456,
tickUpperIndex: 27840,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 28864,
tickUpperIndex: 28928,
},
{
liquidityAmount: new anchor.BN(100_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 28928,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1977429",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"869058",
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(7051000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(28500),
amountSpecifiedIsInput: true,
aToB: aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
"1535201",
);
assert.equal(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
"7920058",
);
// TODO: Verify fees and other whirlpool params
});
/* using sparse-swap, we can handle uninitialized tick-array. so this test is no longer needed.
it("Error on passing in uninitialized tick-array", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const uninitializedTickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
0
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: uninitializedTickArrayPda.publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(ctx, WhirlpoolIx.swapV2Ix(ctx.program, params)).buildAndExecute();
assert.fail("should fail if a tick-array is uninitialized");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0xbbf/); // AccountOwnedByWrongProgram
}
});
*/
it("Error if sqrt_price_limit exceeds max", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price exceeds maximum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if sqrt_price_limit subceed min", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB, tickArrays } =
await initTestPoolWithLiquidityV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
);
const whirlpool = poolInitInfo.whirlpoolPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpool,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if sqrt_price subceeds minimum");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x177b/); // SqrtPriceOutOfBounds
}
});
it("Error if a to b swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if b to a swap below minimum output", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1794/); // AmountOutBelowMinimum
}
});
it("Error if a to b swap above maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MIN_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("Error if b to a swap below maximum input", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const params: SwapV2Params = {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: new anchor.BN(MAX_SQRT_PRICE),
amountSpecifiedIsInput: false,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
};
try {
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, params),
).buildAndExecute();
assert.fail("should fail if amount out is below threshold");
} catch (e) {
const error = e as Error;
assert.match(error.message, /0x1795/); // AmountInAboveMaximum
}
});
it("swaps across ten tick arrays", async () => {
const {
poolInitInfo,
configKeypairs,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokensV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
PriceMath.tickIndexToSqrtPriceX64(27500),
);
const aToB = false;
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
27456, // to 30528
3,
TickSpacing.Stable,
aToB,
);
// tick array range: 27658 to 29386
// tick arrays: (27456, 28152), (28160, 28856), (28864, 29,560)
// current tick: 27727
// initialized ticks:
// 27712, 27736, 27840, 28288, 28296, 28304, 28416, 28576, 28736, 29112, 29120, 29240, 29360
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27712,
tickUpperIndex: 29360,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27736,
tickUpperIndex: 29240,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 27840,
tickUpperIndex: 29120,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28416,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28288,
tickUpperIndex: 28304,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28296,
tickUpperIndex: 29112,
},
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 28576,
tickUpperIndex: 28736,
},
];
const positionInfos = await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Tick
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(829996),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(29240),
amountSpecifiedIsInput: false,
aToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[2].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(14538074),
otherAmountThreshold: MAX_U64,
sqrtPriceLimit: PriceMath.tickIndexToSqrtPriceX64(27712),
amountSpecifiedIsInput: false,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[2].publicKey,
tickArray1: tickArrays[1].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await withdrawPositionsV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
positionInfos,
tokenAccountA,
tokenAccountB,
);
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
(
await Promise.all(
tickArrays.map((tickArray) =>
fetcher.getTickArray(tickArray.publicKey),
),
)
).map((tickArray) => {
const ta = tickArray as TickArrayData;
ta.ticks.forEach((tick) => {
if (!tick.initialized) {
return;
}
/*
console.log(
ta.startTickIndex + index * TickSpacing.Stable,
tick.feeGrowthOutsideA.toString(),
tick.feeGrowthOutsideB.toString()
);
*/
});
});
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
configKeypairs.collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(configKeypairs.collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultAKeypair.publicKey));
//console.log(await getTokenBalance(provider, poolInitInfo.tokenVaultBKeypair.publicKey));
});
});
});
describe("partial fill, b to a", () => {
const tickSpacing = 128;
const aToB = false;
const client = buildWhirlpoolClient(ctx);
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(439296 + 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
439296, // right most TickArray
1,
tickSpacing,
aToB,
);
// a: 1 (round up)
// b: 223379095563402706 (to get 1, need >= 223379095563402706)
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: 439424,
tickUpperIndex: 439552,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[anchor.BN, anchor.BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379095563402706");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().gte(amount) && diffB.neg().lt(amount.muln(2))); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-S-***-------T,max----| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MAX_SQRT_PRICE
sqrtPriceLimit: MAX_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.isZero()); // no output (round up is not used to calculate output)
assert.ok(diffB.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(postWhirlpoolData.sqrtPrice.eq(MAX_SQRT_PRICE_BN)); // hit max
});
});
describe("partial fill, a to b", () => {
const tickSpacing = 128;
const aToB = true;
const client = buildWhirlpoolClient(ctx);
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let whirlpoolKey: PublicKey;
let oraclePda: PDA;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
tickSpacing,
PriceMath.tickIndexToSqrtPriceX64(-439296 - 1),
new BN("10000000000000000000000"),
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = poolInitInfo.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpoolKey);
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
-450560, // left most TickArray
1,
tickSpacing,
aToB,
);
// a: 223379098170764880 (to get 1, need >= 223379098170764880)
// b: 1 (round up)
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000_000),
tickLowerIndex: -439552,
tickUpperIndex: -439424,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
});
async function getTokenBalances(): Promise<[anchor.BN, anchor.BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactIn, sqrt_price_limit = MIN_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("223379098170764880");
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
amount.muln(2), // x2 input
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
otherAmountThreshold: new BN(0),
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().gte(amount) && diffA.neg().lt(amount.muln(2))); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("Fails ExactOut, sqrt_price_limit = 0", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = 0
sqrtPriceLimit: ZERO_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
});
// |-min,T---------***-S-| (*: liquidity, S: start, T: end)
it("ExactOut, sqrt_price_limit = MAX_SQRT_PRICE", async () => {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
const amount = new BN("1");
const quote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
amount,
Percentage.fromFraction(1, 100),
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const [preA, preB] = await getTokenBalances();
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: whirlpoolData.tokenMintA,
tokenMintB: whirlpoolData.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
// sqrt_price_limit = MIN_SQRT_PRICE
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
amount, // 1
otherAmountThreshold: quote.estimatedAmountIn,
}),
).buildAndExecute();
const postWhirlpoolData = await whirlpool.refreshData();
const [postA, postB] = await getTokenBalances();
const diffA = postA.sub(preA);
const diffB = postB.sub(preB);
assert.ok(diffA.neg().eq(quote.estimatedAmountIn)); // partial
assert.ok(diffB.isZero()); // no output (round up is not used to calculate output)
assert.ok(postWhirlpoolData.sqrtPrice.eq(MIN_SQRT_PRICE_BN)); // hit min
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(10),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4.95)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528,
3,
TickSpacing.Standard,
false,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.swapV2(
new BN(10), // amount
ZERO_BN, // otherAmountThreshold
MathUtil.toX64(new Decimal(4.95)), // sqrtPriceLimit
true, // amountSpecifiedIsInput
true, // aToB
{ slices: [] },
{
accounts: {
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrays[0].publicKey,
tickArray1: tickArrays[0].publicKey,
tickArray2: tickArrays[0].publicKey,
oracle: oraclePda.publicKey,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/initialize_pool_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type { InitPoolV2Params, WhirlpoolData } from "../../../src";
import {
IGNORE_CACHE,
MAX_SQRT_PRICE,
METADATA_PROGRAM_ADDRESS,
MIN_SQRT_PRICE,
PDAUtil,
PoolUtil,
PriceMath,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import {
ONE_SOL,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
systemTransferTx,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
buildTestPoolV2Params,
initTestPoolV2,
} from "../../utils/v2/init-utils-v2";
import {
asyncAssertOwnerProgram,
asyncAssertTokenVaultV2,
createMintV2,
initializeNativeMint2022Idempotent,
} from "../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import { AccountState, NATIVE_MINT, NATIVE_MINT_2022 } from "@solana/spl-token";
import { initFeeTier } from "../../utils/init-utils";
describe("initialize_pool_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully init a Standard account", async () => {
const price = MathUtil.toX64(new Decimal(5));
const { configInitInfo, poolInitInfo, feeTierParams } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
price,
);
const whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
)) as WhirlpoolData;
const expectedWhirlpoolPda = PDAUtil.getWhirlpool(
program.programId,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
TickSpacing.Standard,
);
assert.ok(
poolInitInfo.whirlpoolPda.publicKey.equals(
expectedWhirlpoolPda.publicKey,
),
);
assert.equal(expectedWhirlpoolPda.bump, whirlpool.whirlpoolBump[0]);
assert.ok(
whirlpool.whirlpoolsConfig.equals(poolInitInfo.whirlpoolsConfig),
);
assert.ok(whirlpool.tokenMintA.equals(poolInitInfo.tokenMintA));
assert.ok(
whirlpool.tokenVaultA.equals(
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintA,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB));
assert.ok(
whirlpool.tokenVaultB.equals(
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintB,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate);
assert.equal(
whirlpool.protocolFeeRate,
configInitInfo.defaultProtocolFeeRate,
);
assert.ok(
whirlpool.sqrtPrice.eq(
new anchor.BN(poolInitInfo.initSqrtPrice.toString()),
),
);
assert.ok(whirlpool.liquidity.eq(ZERO_BN));
assert.equal(
whirlpool.tickCurrentIndex,
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
);
assert.ok(whirlpool.protocolFeeOwedA.eq(ZERO_BN));
assert.ok(whirlpool.protocolFeeOwedB.eq(ZERO_BN));
assert.ok(whirlpool.feeGrowthGlobalA.eq(ZERO_BN));
assert.ok(whirlpool.feeGrowthGlobalB.eq(ZERO_BN));
assert.ok(whirlpool.tickSpacing === TickSpacing.Standard);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
whirlpool.rewardInfos.forEach((rewardInfo) => {
assert.equal(rewardInfo.emissionsPerSecondX64, 0);
assert.equal(rewardInfo.growthGlobalX64, 0);
assert.ok(
rewardInfo.authority.equals(
configInitInfo.rewardEmissionsSuperAuthority,
),
);
assert.ok(rewardInfo.mint.equals(anchor.web3.PublicKey.default));
assert.ok(rewardInfo.vault.equals(anchor.web3.PublicKey.default));
});
});
it("successfully init a Stable account", async () => {
const price = MathUtil.toX64(new Decimal(5));
const { configInitInfo, poolInitInfo, feeTierParams } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Stable,
price,
);
const whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
)) as WhirlpoolData;
assert.ok(
whirlpool.whirlpoolsConfig.equals(poolInitInfo.whirlpoolsConfig),
);
assert.ok(whirlpool.tokenMintA.equals(poolInitInfo.tokenMintA));
assert.ok(
whirlpool.tokenVaultA.equals(
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintA,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.ok(whirlpool.tokenMintB.equals(poolInitInfo.tokenMintB));
assert.ok(
whirlpool.tokenVaultB.equals(
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
await asyncAssertOwnerProgram(
provider,
whirlpool.tokenMintB,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
assert.equal(whirlpool.feeRate, feeTierParams.defaultFeeRate);
assert.equal(
whirlpool.protocolFeeRate,
configInitInfo.defaultProtocolFeeRate,
);
assert.ok(
whirlpool.sqrtPrice.eq(
new anchor.BN(poolInitInfo.initSqrtPrice.toString()),
),
);
assert.ok(whirlpool.liquidity.eq(ZERO_BN));
assert.equal(
whirlpool.tickCurrentIndex,
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
);
assert.ok(whirlpool.protocolFeeOwedA.eq(ZERO_BN));
assert.ok(whirlpool.protocolFeeOwedB.eq(ZERO_BN));
assert.ok(whirlpool.feeGrowthGlobalA.eq(ZERO_BN));
assert.ok(whirlpool.feeGrowthGlobalB.eq(ZERO_BN));
assert.ok(whirlpool.tickSpacing === TickSpacing.Stable);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
await asyncAssertTokenVaultV2(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.whirlpoolPda.publicKey,
tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
);
whirlpool.rewardInfos.forEach((rewardInfo) => {
assert.equal(rewardInfo.emissionsPerSecondX64, 0);
assert.equal(rewardInfo.growthGlobalX64, 0);
assert.ok(
rewardInfo.authority.equals(
configInitInfo.rewardEmissionsSuperAuthority,
),
);
assert.ok(rewardInfo.mint.equals(anchor.web3.PublicKey.default));
assert.ok(rewardInfo.vault.equals(anchor.web3.PublicKey.default));
});
});
it("succeeds when funder is different than account paying for transaction fee", async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
MathUtil.toX64(new Decimal(5)),
funderKeypair,
);
});
it("fails when tokenVaultA mint does not match tokenA mint", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const otherTokenPublicKey = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenMintA: otherTokenPublicKey,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when tokenVaultB mint does not match tokenB mint", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const otherTokenPublicKey = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenMintB: otherTokenPublicKey,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token mints are in the wrong order", async () => {
const { poolInitInfo, configInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda,
tickSpacing: TickSpacing.Standard,
tokenMintA: poolInitInfo.tokenMintB,
tokenBadgeA: poolInitInfo.tokenBadgeB,
tokenProgramA: tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
tokenMintB: poolInitInfo.tokenMintA,
tokenBadgeB: poolInitInfo.tokenBadgeA,
tokenProgramB: tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x1788/, // InvalidTokenMintOrder
);
});
it("fails when the same token mint is passed in", async () => {
const { poolInitInfo, configInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintA,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda,
tickSpacing: TickSpacing.Standard,
tokenMintB: poolInitInfo.tokenMintA,
tokenBadgeB: poolInitInfo.tokenBadgeA,
tokenProgramB: tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x1788/, // InvalidTokenMintOrder
);
});
it("fails when sqrt-price exceeds max", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
initSqrtPrice: new anchor.BN(MAX_SQRT_PRICE).add(new anchor.BN(1)),
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x177b/, // SqrtPriceOutOfBounds
);
});
it("fails when sqrt-price subceeds min", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
initSqrtPrice: new anchor.BN(MIN_SQRT_PRICE).sub(new anchor.BN(1)),
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/custom program error: 0x177b/, // SqrtPriceOutOfBounds
);
});
it("ignore passed bump", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
);
const whirlpoolPda = poolInitInfo.whirlpoolPda;
const validBump = whirlpoolPda.bump;
const invalidBump = (validBump + 1) % 256; // +1 shift mod 256
const modifiedWhirlpoolPda: PDA = {
publicKey: whirlpoolPda.publicKey,
bump: invalidBump,
};
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
whirlpoolPda: modifiedWhirlpoolPda,
};
await toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute();
// check if passed invalid bump was ignored
const whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
)) as WhirlpoolData;
assert.equal(whirlpool.whirlpoolBump, validBump);
assert.notEqual(whirlpool.whirlpoolBump, invalidBump);
});
});
});
});
it("fails when FeeTier and tick_spacing passed unmatch", async () => {
const { poolInitInfo, configInitInfo, configKeypairs } =
await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
// now FeeTier for TickSpacing.Standard is initialized, but not for TickSpacing.Stable
const config = poolInitInfo.whirlpoolsConfig;
const feeTierStandardPda = PDAUtil.getFeeTier(
ctx.program.programId,
config,
TickSpacing.Standard,
);
const feeTierStablePda = PDAUtil.getFeeTier(
ctx.program.programId,
config,
TickSpacing.Stable,
);
const feeTierStandard = await fetcher.getFeeTier(
feeTierStandardPda.publicKey,
IGNORE_CACHE,
);
const feeTierStable = await fetcher.getFeeTier(
feeTierStablePda.publicKey,
IGNORE_CACHE,
);
assert.ok(feeTierStandard !== null); // should be initialized
assert.ok(feeTierStable === null); // shoud be NOT initialized
const whirlpoolWithStableTickSpacing = PDAUtil.getWhirlpool(
ctx.program.programId,
config,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
TickSpacing.Stable,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...poolInitInfo,
whirlpoolPda: whirlpoolWithStableTickSpacing,
tickSpacing: TickSpacing.Stable,
feeTierKey: feeTierStandardPda.publicKey, // tickSpacing is Stable, but FeeTier is standard
}),
).buildAndExecute(),
/custom program error: 0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...poolInitInfo,
whirlpoolPda: whirlpoolWithStableTickSpacing,
tickSpacing: TickSpacing.Stable,
feeTierKey: feeTierStablePda.publicKey, // FeeTier is stable, but not initialized
}),
).buildAndExecute(),
/custom program error: 0xbc4/, // AccountNotInitialized
);
await initFeeTier(
ctx,
configInitInfo,
configKeypairs.feeAuthorityKeypair,
TickSpacing.Stable,
3000,
);
const feeTierStableAfterInit = await fetcher.getFeeTier(
feeTierStablePda.publicKey,
IGNORE_CACHE,
);
assert.ok(feeTierStableAfterInit !== null);
// Now it should work because FeeTier for stable have been initialized
await toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...poolInitInfo,
whirlpoolPda: whirlpoolWithStableTickSpacing,
tickSpacing: TickSpacing.Stable,
feeTierKey: feeTierStablePda.publicKey,
}),
).buildAndExecute();
});
describe("v2 specific accounts", () => {
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramA: METADATA_PROGRAM_ADDRESS,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: false },
{ isToken2022: false },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: TEST_TOKEN_PROGRAM_ID,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/incorrect program id for instruction/, // Anchor will try to create vault account
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const { poolInitInfo } = await buildTestPoolV2Params(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
const modifiedPoolInitInfo: InitPoolV2Params = {
...poolInitInfo,
tokenProgramB: METADATA_PROGRAM_ADDRESS,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, modifiedPoolInitInfo),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
describe("invalid badge account", () => {
let baseIxParams: InitPoolV2Params;
beforeEach(async () => {
// create tokens
const [tokenAKeypair, tokenBKeypair] = [
Keypair.generate(),
Keypair.generate(),
].sort((a, b) => PoolUtil.compareMints(a.publicKey, b.publicKey));
await createMintV2(
provider,
{ isToken2022: true, hasPermanentDelegate: true },
undefined,
tokenAKeypair,
);
await createMintV2(
provider,
{ isToken2022: true, hasPermanentDelegate: true },
undefined,
tokenBKeypair,
);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = TickSpacing.SixtyFour;
const feeTierPda = PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
);
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: feeTierPda,
}),
).buildAndExecute();
// create config extension
const configExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: configExtensionPda,
}),
).buildAndExecute();
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configKeypair.publicKey,
tokenAKeypair.publicKey,
tokenBKeypair.publicKey,
tickSpacing,
);
baseIxParams = {
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
funder: provider.wallet.publicKey,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tickSpacing,
tokenMintA: tokenAKeypair.publicKey,
tokenMintB: tokenBKeypair.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
feeTierKey: feeTierPda.publicKey,
tokenBadgeA: PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenAKeypair.publicKey,
).publicKey,
tokenBadgeB: PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenBKeypair.publicKey,
).publicKey,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID,
whirlpoolPda,
};
});
it("fails when token_badge_a/b address invalid (uninitialized)", async () => {
const fakeAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token_badge_a/b address invalid (initialized, same config / different mint)", async () => {
const config = baseIxParams.whirlpoolsConfig;
const anotherTokenKeypair = Keypair.generate();
await createMintV2(
provider,
{ isToken2022: true },
undefined,
anotherTokenKeypair,
);
// initialize another badge
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
anotherTokenKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: anotherTokenKeypair.publicKey,
}),
).buildAndExecute();
const badge = fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(badge !== null);
const fakeAddress = tokenBadgePda.publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
it("fails when token_badge_a/b address invalid (account owned by WhirlpoolProgram)", async () => {
// use Whirlpool address
const { poolInitInfo } = await initTestPoolV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
const fakeAddress = poolInitInfo.whirlpoolPda.publicKey;
const whirlpool = fetcher.getPool(fakeAddress);
assert.ok(whirlpool !== null);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeA: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
...baseIxParams,
tokenBadgeB: fakeAddress,
}),
).buildAndExecute(),
/custom program error: 0x7d6/, // ConstraintSeeds
);
});
});
});
describe("Supported Tokens", () => {
function generate3MintAddress(): [Keypair, Keypair, Keypair] {
const keypairs = [
Keypair.generate(),
Keypair.generate(),
Keypair.generate(),
].sort((a, b) => PoolUtil.compareMints(a.publicKey, b.publicKey));
return [keypairs[0], keypairs[1], keypairs[2]];
}
async function checkSupported(
supported: boolean,
whirlpoolsConfig: PublicKey,
tokenMintA: PublicKey,
tokenMintB: PublicKey,
tickSpacing: number,
anchorPatch: boolean = false,
) {
const tokenVaultAKeypair = Keypair.generate();
const tokenVaultBKeypair = Keypair.generate();
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
whirlpoolsConfig,
tokenMintA,
tokenMintB,
tickSpacing,
);
const feeTierKey = PDAUtil.getFeeTier(
ctx.program.programId,
whirlpoolsConfig,
tickSpacing,
).publicKey;
const tokenBadgeA = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfig,
tokenMintA,
).publicKey;
const tokenBadgeB = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfig,
tokenMintB,
).publicKey;
const tokenProgramA = (await provider.connection.getAccountInfo(
tokenMintA,
))!.owner;
const tokenProgramB = (await provider.connection.getAccountInfo(
tokenMintB,
))!.owner;
const promise = toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, {
tokenVaultAKeypair,
tokenVaultBKeypair,
funder: provider.wallet.publicKey,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tickSpacing,
tokenMintA,
tokenMintB,
whirlpoolsConfig,
feeTierKey,
tokenBadgeA,
tokenBadgeB,
tokenProgramA,
tokenProgramB,
whirlpoolPda,
}),
).buildAndExecute();
if (supported) {
await promise;
const whirlpoolData = await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpoolData!.tokenMintA.equals(tokenMintA));
assert.ok(whirlpoolData!.tokenMintB.equals(tokenMintB));
} else {
await assert.rejects(
promise,
!anchorPatch
? /0x179f/ // UnsupportedTokenMint
: /invalid account data for instruction/, // Anchor v0.29 doesn't recognize some new extensions (GroupPointer, Group, MemberPointer, Member)
);
}
}
async function runTest(params: {
supported: boolean;
createTokenBadge: boolean;
tokenTrait: TokenTrait;
anchorPatch?: boolean;
}) {
// create tokens
const [tokenA, tokenTarget, tokenB] = generate3MintAddress();
await createMintV2(provider, { isToken2022: false }, undefined, tokenA);
await createMintV2(provider, { isToken2022: false }, undefined, tokenB);
await createMintV2(provider, params.tokenTrait, undefined, tokenTarget);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = 64;
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
),
}),
).buildAndExecute();
// create token badge if wanted
if (params.createTokenBadge) {
const pda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: pda,
}),
).buildAndExecute();
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
tokenTarget.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: tokenTarget.publicKey,
}),
).buildAndExecute();
}
const isSupportedToken = await PoolUtil.isSupportedToken(
ctx,
configKeypair.publicKey,
tokenTarget.publicKey,
);
assert.equal(isSupportedToken, params.supported);
// try to initialize pool
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenA.publicKey,
tokenTarget.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenB
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenTarget.publicKey,
tokenB.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenA
}
async function runTestWithNativeMint(params: {
supported: boolean;
createTokenBadge: boolean;
isToken2022NativeMint: boolean;
anchorPatch?: boolean;
}) {
// We need to call this to use NATIVE_MINT_2022
await initializeNativeMint2022Idempotent(provider);
// create tokens
const nativeMint = params.isToken2022NativeMint
? NATIVE_MINT_2022
: NATIVE_MINT;
let tokenA = Keypair.generate();
while (PoolUtil.compareMints(tokenA.publicKey, nativeMint) >= 0)
tokenA = Keypair.generate();
let tokenB = Keypair.generate();
while (PoolUtil.compareMints(nativeMint, tokenB.publicKey) >= 0)
tokenB = Keypair.generate();
assert.ok(
PoolUtil.orderMints(tokenA.publicKey, nativeMint)[1].toString() ===
nativeMint.toString(),
);
assert.ok(
PoolUtil.orderMints(nativeMint, tokenB.publicKey)[0].toString() ===
nativeMint.toString(),
);
await createMintV2(provider, { isToken2022: false }, undefined, tokenA);
await createMintV2(provider, { isToken2022: false }, undefined, tokenB);
// create config and feetier
const configKeypair = Keypair.generate();
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority: provider.wallet.publicKey,
feeAuthority: provider.wallet.publicKey,
rewardEmissionsSuperAuthority: provider.wallet.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
const tickSpacing = 64;
await toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, {
defaultFeeRate: 3000,
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
tickSpacing,
whirlpoolsConfig: configKeypair.publicKey,
feeTierPda: PDAUtil.getFeeTier(
ctx.program.programId,
configKeypair.publicKey,
tickSpacing,
),
}),
).buildAndExecute();
// create token badge if wanted
if (params.createTokenBadge) {
const pda = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: provider.wallet.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtensionPda: pda,
}),
).buildAndExecute();
const configExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
configKeypair.publicKey,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKeypair.publicKey,
nativeMint,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: configKeypair.publicKey,
whirlpoolsConfigExtension: configExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: provider.wallet.publicKey,
tokenBadgePda,
tokenMint: nativeMint,
}),
).buildAndExecute();
}
// try to initialize pool
await checkSupported(
params.supported,
configKeypair.publicKey,
tokenA.publicKey,
nativeMint,
tickSpacing,
params.anchorPatch,
); // as TokenB
await checkSupported(
params.supported,
configKeypair.publicKey,
nativeMint,
tokenB.publicKey,
tickSpacing,
params.anchorPatch,
); // as TokenA
}
it("Token: mint without FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
},
});
});
it("Token: mint with FreezeAuthority", async () => {
// not good, but allowed for compatibility to initialize_pool
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: false,
hasFreezeAuthority: true,
},
});
});
it("Token: native mint (WSOL)", async () => {
await runTestWithNativeMint({
supported: true,
createTokenBadge: false,
isToken2022NativeMint: false,
});
});
it("Token-2022: with TransferFeeConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
},
});
});
it("Token-2022: with InterestBearingConfig", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasInterestBearingExtension: true,
},
});
});
it("Token-2022: with MetadataPointer & TokenMetadata", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTokenMetadataExtension: true,
hasMetadataPointerExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
});
});
it("Token-2022: with ConfidentialTransferMint & TransferFeeConfig (& ConfidentialTransferFeeConfig)", async () => {
await runTest({
supported: true,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
// test util will automatically initialize ConfidentialTransferFeeConfig
},
});
});
it("Token-2022: with TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: with TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: with TokenBadge with TransferHook", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: with TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: with TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: true,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] with TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with FreezeAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with PermanentDelegate", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasPermanentDelegate: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with TransferHook", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with MintCloseAuthority", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasMintCloseAuthorityExtension: true,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Initialized)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Initialized,
},
});
});
it("Token-2022: [FAIL] without TokenBadge with DefaultAccountState(Frozen)", async () => {
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait: {
isToken2022: true,
hasFreezeAuthority: true, // needed to set initial state to Frozen
hasDefaultAccountStateExtension: true,
defaultAccountInitialState: AccountState.Frozen,
},
});
});
it("Token-2022: [FAIL] with/without TokenBadge, native mint (WSOL-2022)", async () => {
await runTestWithNativeMint({
supported: false,
createTokenBadge: false,
isToken2022NativeMint: true,
});
await runTestWithNativeMint({
supported: false,
createTokenBadge: true,
isToken2022NativeMint: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Group", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Group
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with GroupPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize GroupPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
//[11 Mar, 2024] NOT IMPLEMENTED / I believe this extension is not stable yet
it.skip("Token-2022: [FAIL] with/without TokenBadge with Member", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize Member
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with MemberPointer", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasGroupMemberPointerExtension: true,
};
// TODO: remove anchorPatch: v0.29 doesn't recognize MemberPointer
await runTest({
supported: false,
createTokenBadge: true,
tokenTrait,
anchorPatch: true,
});
await runTest({
supported: false,
createTokenBadge: false,
tokenTrait,
anchorPatch: true,
});
});
it("Token-2022: [FAIL] with/without TokenBadge with NonTransferable", async () => {
const tokenTrait: TokenTrait = {
isToken2022: true,
hasNonTransferableExtension: true,
};
await runTest({ supported: false, createTokenBadge: true, tokenTrait });
await runTest({ supported: false, createTokenBadge: false, tokenTrait });
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/decrease_liquidity_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import { BN } from "bn.js";
import Decimal from "decimal.js";
import type { PositionData, TickArrayData, WhirlpoolData } from "../../../src";
import {
METADATA_PROGRAM_ADDRESS,
WhirlpoolContext,
WhirlpoolIx,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { decreaseLiquidityQuoteByLiquidityWithParams } from "../../../src/quotes/public/decrease-liquidity-quote";
import {
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
approveToken as approveTokenForPosition,
assertTick,
sleep,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { initTickArray, openPosition } from "../../utils/init-utils";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createMintV2,
createAndMintToTokenAccountV2,
approveTokenV2,
} from "../../utils/v2/token-2022";
import {
createTokenAccount as createTokenAccountForPosition,
createAndMintToTokenAccount as createAndMintToTokenAccountForPosition,
} from "../../utils/token";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
describe("decrease_liquidity_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully decrease liquidity from position in one tick array", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo, tokenAccountA, tokenAccountB, positions } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// To check if rewardLastUpdatedTimestamp is updated
await sleep(3000);
const removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(1_000_000),
sqrtPrice: poolBefore.sqrtPrice,
slippageTolerance: Percentage.fromFraction(1, 100),
tickCurrentIndex: poolBefore.tickCurrentIndex,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolBefore,
IGNORE_CACHE,
),
});
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const remainingLiquidity = liquidityAmount.sub(
removalQuote.liquidityAmount,
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gt(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.ok(poolAfter.liquidity.eq(remainingLiquidity));
const position = await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
assert.ok(position?.liquidity.eq(remainingLiquidity));
const tickArray = (await fetcher.getTickArray(
positions[0].tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArray.ticks[56],
true,
remainingLiquidity,
remainingLiquidity,
);
assertTick(
tickArray.ticks[70],
true,
remainingLiquidity,
remainingLiquidity.neg(),
);
});
it("successfully decrease liquidity from position in two tick arrays", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = -1280,
tickUpper = 1280;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{ tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const position = positions[0];
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(1_000_000),
sqrtPrice: poolBefore.sqrtPrice,
slippageTolerance: Percentage.fromFraction(1, 100),
tickCurrentIndex: poolBefore.tickCurrentIndex,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolBefore,
IGNORE_CACHE,
),
});
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const remainingLiquidity = liquidityAmount.sub(
removalQuote.liquidityAmount,
);
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
poolAfter.rewardLastUpdatedTimestamp.gte(
poolBefore.rewardLastUpdatedTimestamp,
),
);
assert.ok(poolAfter.liquidity.eq(remainingLiquidity));
const positionAfter = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionAfter.liquidity.eq(remainingLiquidity));
const tickArrayLower = (await fetcher.getTickArray(
position.tickArrayLower,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayLower.ticks[78],
true,
remainingLiquidity,
remainingLiquidity,
);
const tickArrayUpper = (await fetcher.getTickArray(
position.tickArrayUpper,
IGNORE_CACHE,
)) as TickArrayData;
assertTick(
tickArrayUpper.ticks[10],
true,
remainingLiquidity,
remainingLiquidity.neg(),
);
});
it("successfully decrease liquidity with approved delegate", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{ tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
const removeAmount = new anchor.BN(1_000_000);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: removeAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute();
});
it("successfully decrease liquidity with owner even if there is approved delegate", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
positions[0].tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
const removeAmount = new anchor.BN(1_000_000);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: removeAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
});
it("successfully decrease liquidity with transferred position token", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const removeAmount = new anchor.BN(1_000_000);
const newOwner = anchor.web3.Keypair.generate();
const newOwnerPositionTokenAccount =
await createTokenAccountForPosition(
provider,
position.mintKeypair.publicKey,
newOwner.publicKey,
);
await transferToken(
provider,
position.tokenAccount,
newOwnerPositionTokenAccount,
1,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: removeAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: newOwner.publicKey,
position: position.publicKey,
positionTokenAccount: newOwnerPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
)
.addSigner(newOwner)
.buildAndExecute();
});
it("fails when liquidity amount is zero", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{ tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: new anchor.BN(0),
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x177c/, // LiquidityZero
);
});
it("fails when position has insufficient liquidity for the withdraw amount", async () => {
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: -1280,
tickUpperIndex: 1280,
liquidityAmount: ZERO_BN,
},
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: new anchor.BN(1_000),
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x177f/, // LiquidityUnderflow
);
});
it("fails when token min a subceeded", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(0.005)),
positions: [
{ tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(1_000_000),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
});
it("fails when token min b subceeded", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(5)),
positions: [
{ tickLowerIndex: -1280, tickUpperIndex: 1280, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(1_000_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
});
it("fails when position account does not have exactly 1 token", async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
// Create a position token account that contains 0 tokens
const newPositionTokenAccount = await createTokenAccountForPosition(
provider,
positions[0].mintKeypair.publicKey,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: newPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
// Send position token to other position token account
await transferToken(
provider,
position.tokenAccount,
newPositionTokenAccount,
1,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position token account mint does not match position mint", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const fakeMint = await createMintV2(provider, { isToken2022: false });
const invalidPositionTokenAccount =
await createAndMintToTokenAccountForPosition(provider, fakeMint, 1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: invalidPositionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // A raw constraint was violated
);
});
it("fails when position does not match whirlpool", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7d1/, // A has_one constraint was violated
);
});
it("fails when token vaults do not match whirlpool vaults", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenMintA, tokenMintB } = poolInitInfo;
const position = positions[0];
const fakeVaultA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
1_000,
);
const fakeVaultB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
1_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: fakeVaultA,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when owner token account mint does not match whirlpool token mint", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const invalidMintA = await createMintV2(
provider,
tokenTraits.tokenTraitA,
);
const invalidTokenAccountA = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
invalidMintA,
1_000_000,
);
const invalidMintB = await createMintV2(
provider,
tokenTraits.tokenTraitB,
);
const invalidTokenAccountB = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
invalidMintB,
1_000_000,
);
const position = positions[0];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: invalidTokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidTokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
it("fails when position authority is not approved delegate for position token account", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1783/, // MissingOrInvalidDelegate
);
});
it("fails when position authority is not authorized for exactly 1 token", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
position.tokenAccount,
delegate.publicKey,
0,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
)
.addSigner(delegate)
.buildAndExecute(),
/0x1784/, // InvalidPositionTokenAmount
);
});
it("fails when position authority was not a signer", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const delegate = anchor.web3.Keypair.generate();
await approveTokenForPosition(
provider,
position.tokenAccount,
delegate.publicKey,
1,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitA,
tokenAccountA,
delegate.publicKey,
1_000_000,
);
await approveTokenV2(
provider,
tokenTraits.tokenTraitB,
tokenAccountB,
delegate.publicKey,
1_000_000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(167_000),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: delegate.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when tick arrays do not match the position", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 11264);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, whirlpoolPda.publicKey, 22528);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x1779/, // TicKNotFound
);
});
it("fails when the tick arrays are for a different whirlpool", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const position = positions[0];
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing: TickSpacing.Standard,
});
const poolInitInfo2 = anotherFixture.getInfos().poolInitInfo;
const {
params: { tickArrayPda: tickArrayLowerPda },
} = await initTickArray(
ctx,
poolInitInfo2.whirlpoolPda.publicKey,
-11264,
);
const {
params: { tickArrayPda: tickArrayUpperPda },
} = await initTickArray(ctx, poolInitInfo2.whirlpoolPda.publicKey, 0);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
}),
).buildAndExecute(),
/0x7d1/, // A has one constraint was violated
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
assert.ok(poolInitInfo.tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
}),
).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const liquidityAmount = new anchor.BN(6_500_000);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(2.2)),
positions: [
{ tickLowerIndex: 7168, tickUpperIndex: 8960, liquidityAmount },
],
});
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const tickArray = positions[0].tickArrayLower;
const {
params: {
positionPda,
positionTokenAccount: positionTokenAccountAddress,
},
} = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
7168,
8960,
);
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.decreaseLiquidityV2(
liquidityAmount,
new BN(0), // minA
new BN(0), // minB
{ slices: [] },
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: tickArray,
tickArrayUpper: tickArray,
memoProgram: invalidMemoProgram,
},
},
),
],
}).buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/set_reward_emissions_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import type { WhirlpoolData } from "../../../src";
import { toTx, WhirlpoolContext, WhirlpoolIx } from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { TickSpacing, ZERO_BN } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import {
initTestPoolV2,
initializeRewardV2,
} from "../../utils/v2/init-utils-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import {
createAndMintToTokenAccountV2,
mintToDestinationV2,
} from "../../utils/v2/token-2022";
describe("set_reward_emissions_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const emissionsPerSecondX64 = new anchor.BN(10_000)
.shln(64)
.div(new anchor.BN(60 * 60 * 24));
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitAB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitAB: { isToken2022: false },
tokenTraitR: { isToken2022: true },
},
{
tokenTraitAB: { isToken2022: true },
tokenTraitR: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA/B: ${
tokenTraits.tokenTraitAB.isToken2022 ? "Token2022" : "Token"
}, tokenTraitReward: ${tokenTraits.tokenTraitR.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully set_reward_emissions", async () => {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardVaultKeypair, rewardMint },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await mintToDestinationV2(
provider,
tokenTraits.tokenTraitR,
rewardMint,
rewardVaultKeypair.publicKey,
10000,
);
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
rewardVaultKey: rewardVaultKeypair.publicKey,
emissionsPerSecondX64,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
let whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(
whirlpool.rewardInfos[0].emissionsPerSecondX64.eq(
emissionsPerSecondX64,
),
);
// Successfuly set emissions back to zero
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
rewardVaultKey: rewardVaultKeypair.publicKey,
emissionsPerSecondX64: ZERO_BN,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
whirlpool = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(whirlpool.rewardInfos[0].emissionsPerSecondX64.eq(ZERO_BN));
});
it("fails when token vault does not contain at least 1 day of emission runway", async () => {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardVaultKeypair },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
rewardVaultKey: rewardVaultKeypair.publicKey,
emissionsPerSecondX64,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0x178b/, // RewardVaultAmountInsufficient
);
});
it("fails if provided reward vault does not match whirlpool reward vault", async () => {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
const {
params: { rewardMint },
} = await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
const fakeVault = await createAndMintToTokenAccountV2(
provider,
tokenTraits.tokenTraitR,
rewardMint,
10000,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
rewardVaultKey: fakeVault,
rewardIndex,
emissionsPerSecondX64,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // An address constraint was violated
);
});
it("cannot set emission for an uninitialized reward", async () => {
const { poolInitInfo, configInitInfo, configKeypairs } =
await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
rewardVaultKey: anchor.web3.PublicKey.default,
rewardIndex: rewardIndex,
emissionsPerSecondX64,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("cannot set emission without the authority's signature", async () => {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitAB,
tokenTraits.tokenTraitAB,
TickSpacing.Standard,
);
const rewardIndex = 0;
await initializeRewardV2(
ctx,
tokenTraits.tokenTraitR,
poolInitInfo.whirlpoolsConfig,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
rewardAuthority: configInitInfo.rewardEmissionsSuperAuthority,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
rewardIndex,
rewardVaultKey: provider.wallet.publicKey, // TODO fix
emissionsPerSecondX64,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/collect_protocol_fees_v2.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type { WhirlpoolData } from "../../../src";
import {
METADATA_PROGRAM_ADDRESS,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { createMintV2, createTokenAccountV2 } from "../../utils/v2/token-2022";
describe("collect_protocol_fees_v2", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
describe("v1 parity", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"}`, () => {
it("successfully collects fees", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: {
feeAuthorityKeypair,
collectProtocolFeesAuthorityKeypair,
},
configInitInfo: {
whirlpoolsConfigKeypair: whirlpoolsConfigKeypair,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
await toTx(
ctx,
WhirlpoolIx.setProtocolFeeRateIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
protocolFeeRate: 2500,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolBefore?.protocolFeeOwedA.eq(ZERO_BN));
assert.ok(poolBefore?.protocolFeeOwedB.eq(ZERO_BN));
const tickArrayPda = positions[0].tickArrayLower;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda,
tickArray1: tickArrayPda,
tickArray2: tickArrayPda,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda,
tickArray1: tickArrayPda,
tickArray2: tickArrayPda,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
const poolAfter = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolAfter?.protocolFeeOwedA.eq(new BN(150)));
assert.ok(poolAfter?.protocolFeeOwedB.eq(new BN(150)));
const destA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const destB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: destA,
tokenOwnerAccountB: destB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const balanceDestA = await getTokenBalance(provider, destA);
const balanceDestB = await getTokenBalance(provider, destB);
assert.equal(balanceDestA, "150");
assert.equal(balanceDestB, "150");
assert.ok(poolBefore?.protocolFeeOwedA.eq(ZERO_BN));
assert.ok(poolBefore?.protocolFeeOwedB.eq(ZERO_BN));
});
it("fails to collect fees without the authority's signature", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
).buildAndExecute(),
/.*signature verification fail.*/i,
);
});
it("fails when collect_protocol_fees_authority is invalid", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { rewardEmissionsSuperAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when whirlpool does not match config", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const anotherFixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool:
anotherFixture.getInfos().poolInitInfo.whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("fails when vaults do not match whirlpool vaults", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: {
whirlpoolsConfigKeypair: whirlpoolsConfigKeypair,
},
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const fakeVaultA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
const fakeVaultB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: fakeVaultA,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: fakeVaultB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when destination mints do not match whirlpool mints", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
...tokenTraits,
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKepair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const invalidDestA = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitB,
tokenMintB,
provider.wallet.publicKey,
);
const invalidDestB = await createTokenAccountV2(
provider,
tokenTraits.tokenTraitA,
tokenMintA,
provider.wallet.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKepair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: invalidDestA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKepair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: invalidDestB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7d3/, // ConstraintRaw
);
});
});
});
});
describe("v2 specific accounts", () => {
it("fails when passed token_mint_a does not match whirlpool's token_mint_a", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
//tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA: otherTokenPublicKey, // invalid
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_mint_b does not match whirlpool's token_mint_b", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
//tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const otherTokenPublicKey = await createMintV2(provider, {
isToken2022: true,
});
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB: otherTokenPublicKey, // invalid
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token program (token-2022 is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is not token-2022 program (token is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: TEST_TOKEN_PROGRAM_ID, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_a is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramA.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA: METADATA_PROGRAM_ADDRESS, // invalid
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed token_program_b is not token program (token-2022 is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_2022_PROGRAM_ID, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is not token-2022 program (token is passed)", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: TEST_TOKEN_PROGRAM_ID, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("fails when passed token_program_b is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
assert.ok(tokenProgramB.equals(TEST_TOKEN_2022_PROGRAM_ID));
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB: METADATA_PROGRAM_ADDRESS, // invalid
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
it("fails when passed memo_program is token_metadata", async () => {
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex: 29440,
tickUpperIndex: 33536,
liquidityAmount: new anchor.BN(10_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair },
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const invalidMemoProgram = METADATA_PROGRAM_ADDRESS;
await assert.rejects(
toTx(ctx, {
cleanupInstructions: [],
signers: [],
instructions: [
ctx.program.instruction.collectProtocolFeesV2(
{ slices: [] },
{
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenDestinationA: tokenAccountA,
tokenDestinationB: tokenAccountB,
memoProgram: invalidMemoProgram,
},
},
),
],
})
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/transfer-fee.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { MintWithTokenProgram, PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityV2Params,
IncreaseLiquidityV2Params,
InitPoolV2Params,
PositionData,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
MEMO_PROGRAM_ADDRESS,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
TickUtil,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type {
FundedPositionV2Params,
TokenTrait,
} from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import {
calculateTransferFeeExcludedAmount,
calculateTransferFeeIncludedAmount,
createTokenAccountV2,
} from "../../../utils/v2/token-2022";
import { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type {
InitAquariumV2Params,
TestAquarium,
} from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import type { TransferFee, TransferFeeConfig } from "@solana/spl-token";
import {
MAX_FEE_BASIS_POINTS,
getAccount,
getEpochFee,
getMint,
getTransferFeeAmount,
getTransferFeeConfig,
} from "@solana/spl-token";
import { createSetTransferFeeInstruction } from "../../../utils/v2/transfer-fee";
import type { TokenExtensionContext } from "../../../../src/utils/public/token-extension-util";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/TransferFee", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const dummyTokenMintWithProgram: MintWithTokenProgram = {
address: PublicKey.default,
decimals: 0,
freezeAuthority: null,
isInitialized: true,
mintAuthority: null,
supply: 1_000_000_000n,
tlvData: Buffer.from([]),
tokenProgram: TEST_TOKEN_PROGRAM_ID,
};
const withNoExtension: TokenExtensionContext = {
currentEpoch: 100,
tokenMintWithProgramA: dummyTokenMintWithProgram,
tokenMintWithProgramB: dummyTokenMintWithProgram,
rewardTokenMintsWithProgram: [
dummyTokenMintWithProgram,
dummyTokenMintWithProgram,
dummyTokenMintWithProgram,
],
};
async function getTransferFee(mint: PublicKey): Promise<TransferFee> {
const mintData = await getMint(
provider.connection,
mint,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfig = getTransferFeeConfig(mintData);
assert.ok(transferFeeConfig !== null);
const epochInfo = await provider.connection.getEpochInfo();
const transferFee = getEpochFee(transferFeeConfig, BigInt(epochInfo.epoch));
return transferFee;
}
const WAIT_EPOCH_TIMEOUT_MS = 30 * 1000;
async function getCurrentEpoch(): Promise<number> {
const epochInfo = await provider.connection.getEpochInfo("confirmed");
return epochInfo.epoch;
}
async function waitEpoch(waitForEpoch: number) {
const startWait = Date.now();
while (Date.now() - startWait < WAIT_EPOCH_TIMEOUT_MS) {
const epoch = await getCurrentEpoch();
if (epoch >= waitForEpoch) return;
sleep(1000);
}
throw Error(
"waitEpoch Timeout, Please set slots_per_epoch smaller in Anchor.toml",
);
}
async function fetchTransferFeeConfig(
mint: PublicKey,
): Promise<TransferFeeConfig> {
const mintData = await getMint(
provider.connection,
mint,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const config = getTransferFeeConfig(mintData);
assert.ok(config !== null);
return config!;
}
async function fetchTransferFeeWithheldAmount(
account: PublicKey,
): Promise<BN> {
const accountData = await getAccount(
provider.connection,
account,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const amount = getTransferFeeAmount(accountData);
assert.ok(amount !== null);
return new BN(amount.withheldAmount.toString());
}
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: with transfer fee", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be non zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
//console.info("A", positionBeforeCollect.feeOwedA.toString(), feeBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", positionBeforeCollect.feeOwedB.toString(), feeBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
// all owed amount should be collected
const positionAfterCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionAfterCollect.feeOwedA.isZero());
assert.ok(positionAfterCollect.feeOwedB.isZero());
});
it("collect_fees_v2: feeOwed is zero", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// collect owed fees
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionBeforeCollect.feeOwedA.isZero());
assert.ok(positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA).sub(new BN(postVaultBalanceA)).isZero(),
);
assert.ok(
new BN(preVaultBalanceB).sub(new BN(postVaultBalanceB)).isZero(),
);
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(postFeeBalanceA).sub(new BN(preFeeBalanceA)).isZero());
assert.ok(new BN(postFeeBalanceB).sub(new BN(preFeeBalanceB)).isZero());
});
it("collect_fees_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
positionBeforeCollect.feeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(
positionBeforeCollect.feeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(
positionBeforeCollect.feeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("collect_fees_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// feeOwed includes transfer fee
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
positionBeforeCollect.feeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
positionBeforeCollect.feeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(
positionBeforeCollect.feeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(
positionBeforeCollect.feeOwedB,
),
);
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(positionBeforeCollect.feeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(positionBeforeCollect.feeOwedB),
);
// owner received 0 tokens
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).isZero());
assert.ok(new BN(feeBalanceB).isZero());
// all tokens should be withheld as transfer fee
const transferFeeWithheldA =
await fetchTransferFeeWithheldAmount(feeAccountA);
const transferFeeWithheldB =
await fetchTransferFeeWithheldAmount(feeAccountB);
assert.ok(transferFeeWithheldA.eq(positionBeforeCollect.feeOwedA));
assert.ok(transferFeeWithheldB.eq(positionBeforeCollect.feeOwedB));
});
it("collect_protocol_fees_v2: with transfer fee", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be non zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault sent owed only (transfer fee is paid from owed)
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received feeOwed minus transfer fee (transferFeeExcludedAmount)
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(feeBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(feeBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all owed amount should be collected
const poolAfterCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolAfterCollect.protocolFeeOwedA.isZero());
assert.ok(poolAfterCollect.protocolFeeOwedB.isZero());
});
it("collect_protocol_fees_v2: protocolFeeOwed is zero", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// collect
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const transferFeeA = await getTransferFee(tokenMintA);
const transferFeeB = await getTransferFee(tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
transferFeeA,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
transferFeeB,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(preVaultBalanceA).eq(new BN(postVaultBalanceA)));
assert.ok(new BN(preVaultBalanceB).eq(new BN(postVaultBalanceB)));
// protocol received 0 tokens
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(preFeeBalanceA).eq(new BN(postFeeBalanceA)));
assert.ok(new BN(preFeeBalanceB).eq(new BN(postFeeBalanceB)));
});
it("collect_protocol_fees_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be zero
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(
poolBeforeCollect.protocolFeeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(
poolBeforeCollect.protocolFeeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
const preFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const preFeeBalanceB = await getTokenBalance(provider, feeAccountB);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received all owed amount
const postFeeBalanceA = await getTokenBalance(provider, feeAccountA);
const postFeeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(
new BN(postFeeBalanceA)
.sub(new BN(preFeeBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(postFeeBalanceB)
.sub(new BN(preFeeBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
});
it("collect_protocol_fees_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenMintA,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
tokenMintB,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenMintA);
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenMintB);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
// protocolFeeOwed includes transfer fee
const poolBeforeCollect = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
assert.ok(!poolBeforeCollect.protocolFeeOwedA.isZero());
assert.ok(!poolBeforeCollect.protocolFeeOwedB.isZero());
// transfer fee should be 100%
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
poolBeforeCollect.protocolFeeOwedA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
poolBeforeCollect.protocolFeeOwedB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(
poolBeforeCollect.protocolFeeOwedA,
),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(
poolBeforeCollect.protocolFeeOwedB,
),
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
// vault balance should not change
const postVaultBalanceA = await getTokenBalance(
provider,
tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(poolBeforeCollect.protocolFeeOwedA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(poolBeforeCollect.protocolFeeOwedB),
);
// protocol received 0 tokens
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).isZero());
assert.ok(new BN(feeBalanceB).isZero());
// all tokens should be withheld as transfer fee
const transferFeeWithheldA =
await fetchTransferFeeWithheldAmount(feeAccountA);
const transferFeeWithheldB =
await fetchTransferFeeWithheldAmount(feeAccountB);
assert.ok(transferFeeWithheldA.eq(poolBeforeCollect.protocolFeeOwedA));
assert.ok(transferFeeWithheldB.eq(poolBeforeCollect.protocolFeeOwedB));
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 5000,
}, // 50%
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
// Lock the collectRewards quote to the last time we called updateFeesAndRewards
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
assert.ok(!expectation.transferFee.deductedFromRewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: with transfer fee", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: withNoExtension, // no TransferFee consideration because it is taken into account later
});
for (let i = 0; i < NUM_REWARDS; i++) {
const transferFee = await getTransferFee(rewards[i].rewardMint);
assert.equal(transferFee.transferFeeBasisPoints, [500, 1000, 5000][i]);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
expectation.rewardOwed[i]!,
);
assert.ok(expectedTransferFeeExcludedAmount.fee.gtn(0));
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(expectation.rewardOwed[i]!),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(
new BN(rewardBalance).eq(expectedTransferFeeExcludedAmount.amount),
);
//console.info("R", expectation[i]?.toString(), rewardBalance.toString(), expectedTransferFeeExcludedAmount.amount.toString(), expectedTransferFeeExcludedAmount.fee.toString());
}
const positionPostCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const expectationPostCollect = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPostCollect.getData(),
tickLower: positionPostCollect.getLowerTickData(),
tickUpper: positionPostCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: withNoExtension,
});
assert.ok(expectationPostCollect.rewardOwed.every((n) => n!.isZero()));
});
it("collect_reward_v2: rewardOwed is zero", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// collect
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
}
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const transferFee = await getTransferFee(rewards[i].rewardMint);
assert.equal(transferFee.transferFeeBasisPoints, [500, 1000, 5000][i]);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(expectedTransferFeeExcludedAmount.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmount.fee.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
const preRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(new BN(preVaultBalance).eq(new BN(postVaultBalance)));
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(postRewardBalance).eq(new BN(preRewardBalance)));
}
});
it("collect_reward_v2: transfer fee rate is 0%", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: whirlpoolData.rewardInfos.map((rewardInfo) =>
createSetTransferFeeInstruction(
rewardInfo.mint,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
),
}).buildAndExecute();
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const updatedFeeConfig = await fetchTransferFeeConfig(
rewards[i].rewardMint,
);
assert.equal(
updatedFeeConfig.newerTransferFee.transferFeeBasisPoints,
0,
);
await waitEpoch(Number(updatedFeeConfig.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfig.newerTransferFee.epoch,
);
const transferFee = await getTransferFee(rewards[i].rewardMint);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(
expectedTransferFeeExcludedAmount.amount.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
assert.ok(expectedTransferFeeExcludedAmount.fee.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(positionPreCollect.getData().rewardInfos[i].amountOwed),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(
new BN(postRewardBalance).eq(
expectedTransferFeeExcludedAmount.amount,
),
);
}
});
it("collect_reward_v2: transfer fee rate is 100%", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: whirlpoolData.rewardInfos.map((rewardInfo) =>
createSetTransferFeeInstruction(
rewardInfo.mint,
MAX_FEE_BASIS_POINTS, // 100 %
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
),
}).buildAndExecute();
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
for (let i = 0; i < NUM_REWARDS; i++) {
const updatedFeeConfig = await fetchTransferFeeConfig(
rewards[i].rewardMint,
);
assert.equal(
updatedFeeConfig.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
await waitEpoch(Number(updatedFeeConfig.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfig.newerTransferFee.epoch,
);
const transferFee = await getTransferFee(rewards[i].rewardMint);
// expectation include transfer fee
const expectedTransferFeeExcludedAmount =
calculateTransferFeeExcludedAmount(
transferFee,
positionPreCollect.getData().rewardInfos[i].amountOwed,
);
assert.ok(
expectedTransferFeeExcludedAmount.fee.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
assert.ok(expectedTransferFeeExcludedAmount.amount.isZero());
const preVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
// vault sent owed only (no transfer fee, transfer fee is paid from owed)
const postVaultBalance = await getTokenBalance(
provider,
rewards[i].rewardVaultKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalance)
.sub(new BN(postVaultBalance))
.eq(positionPreCollect.getData().rewardInfos[i].amountOwed),
);
// owner received expectation minus transfer fee (transferFeeExcludedAmount)
const postRewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(postRewardBalance).isZero());
const withheldAmount = await fetchTransferFeeWithheldAmount(
rewardAccounts[i],
);
assert.ok(
withheldAmount.eq(
positionPreCollect.getData().rewardInfos[i].amountOwed,
),
);
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount: ZERO_BN,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount: ZERO_BN,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: transfer fee rate is 0%", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.isZero());
assert.ok(
expectedTransferFeeIncludedAmountA.amount.eq(
requiredAmountDelta.tokenA,
),
);
assert.ok(
expectedTransferFeeIncludedAmountB.amount.eq(
requiredAmountDelta.tokenB,
),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees (0)
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(requiredAmountDelta.tokenA),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(requiredAmountDelta.tokenB),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: [FAIL] transfer fee rate is 100% without cap", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
// overflow at client-side
assert.throws(() => {
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
});
assert.throws(() => {
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
});
// overflow at contract-side
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: U64_MAX,
tokenMaxB: U64_MAX,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
});
it("increase_liquidity_v2: transfer fee rate is 100% with cap", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(updatedFeeConfigA.newerTransferFee.maximumFee, 99n);
assert.equal(updatedFeeConfigB.newerTransferFee.maximumFee, 99n);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
updatedFeeConfigA.newerTransferFee,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
updatedFeeConfigB.newerTransferFee,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.eq(new BN(99)));
assert.ok(expectedTransferFeeIncludedAmountB.fee.eq(new BN(99)));
assert.ok(
expectedTransferFeeIncludedAmountA.amount
.sub(expectedTransferFeeIncludedAmountA.fee)
.eq(requiredAmountDelta.tokenA),
);
assert.ok(
expectedTransferFeeIncludedAmountB.amount
.sub(expectedTransferFeeIncludedAmountB.fee)
.eq(requiredAmountDelta.tokenB),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
const withheldAmountA = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const withheldAmountB = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(withheldAmountA).eq(new BN(99)));
assert.ok(new BN(withheldAmountB).eq(new BN(99)));
});
it("increase_liquidity_v2: out or range (above, tokenB amount is zero)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[1];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
aboveLowerIndex,
aboveUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(aboveLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(aboveUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.isZero()); // out of range, all asset is in tokenA
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.amount.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.isZero());
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(preOwnerAccountBalanceB.sub(postOwnerAccountBalanceB).isZero());
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(postVaultBalanceB.sub(preVaultBalanceB).isZero());
});
it("increase_liquidity_v2: out or range (below, tokenA amount is zero)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[2];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
belowLowerIndex,
belowUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(belowLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(belowUpperIndex),
true,
);
assert.ok(requiredAmountDelta.tokenA.isZero()); // out of range, all asset is in tokenB
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeIncludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(preOwnerAccountBalanceA.sub(postOwnerAccountBalanceA).isZero());
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(postVaultBalanceA.sub(preVaultBalanceA).isZero());
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
it("increase_liquidity_v2: [FAIL] TokenMaxExceeded due to transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const normalParams: IncreaseLiquidityV2Params = {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMaxA: requiredAmountDelta.tokenA,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMaxB: requiredAmountDelta.tokenB,
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set maxA to expected - 1
tokenMaxA: requiredAmountDelta.tokenA
.add(expectedTransferFeeIncludedAmountA.fee)
.subn(1),
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set maxB to expected - 1
tokenMaxB: requiredAmountDelta.tokenB
.add(expectedTransferFeeIncludedAmountB.fee)
.subn(1),
}),
).buildAndExecute(),
/0x1781/, // TokenMaxExceeded
);
// success with normal params
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, normalParams),
).buildAndExecute();
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (transferFeeExcludedAmount)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
//console.info("A", destBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", destBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all liquidity have been decreased
const positionDataAfterWithdraw = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionDataAfterWithdraw.liquidity.isZero());
});
it("decrease_liquidity_v2: transfer fee rate is 0%", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
0,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
0,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
0,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
assert.ok(
expectedTransferFeeExcludedAmountA.amount.eq(expectedAmount.tokenA),
);
assert.ok(
expectedTransferFeeExcludedAmountB.amount.eq(expectedAmount.tokenB),
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (0)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("decrease_liquidity_v2: transfer fee rate is 100% without cap", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(
expectedTransferFeeExcludedAmountA.fee.eq(expectedAmount.tokenA),
);
assert.ok(
expectedTransferFeeExcludedAmountB.fee.eq(expectedAmount.tokenB),
);
assert.ok(expectedTransferFeeExcludedAmountA.amount.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.amount.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received 0 tokens
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
// all amount is collected as transfer fee
assert.ok(new BN(destBalanceA).isZero());
assert.ok(new BN(destBalanceB).isZero());
const withheldAmountA =
await fetchTransferFeeWithheldAmount(destAccountA);
const withheldAmountB =
await fetchTransferFeeWithheldAmount(destAccountB);
assert.ok(withheldAmountA.eq(expectedAmount.tokenA));
assert.ok(withheldAmountB.eq(expectedAmount.tokenB));
});
it("decrease_liquidity_v2: transfer fee rate is 100% with cap", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
MAX_FEE_BASIS_POINTS,
99n, // cap
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
const updatedFeeConfigB = await fetchTransferFeeConfig(
poolInitInfo.tokenMintB,
);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
MAX_FEE_BASIS_POINTS,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigA.newerTransferFee.epoch,
);
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >= updatedFeeConfigB.newerTransferFee.epoch,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(
updatedFeeConfigA.newerTransferFee,
expectedAmount.tokenA,
);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(
updatedFeeConfigB.newerTransferFee,
expectedAmount.tokenB,
);
assert.ok(expectedTransferFeeExcludedAmountA.fee.eqn(99));
assert.ok(expectedTransferFeeExcludedAmountB.fee.eqn(99));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received expectedAmount minus capped transfer fee
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
// all amount is collected as transfer fee
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
const withheldAmountA =
await fetchTransferFeeWithheldAmount(destAccountA);
const withheldAmountB =
await fetchTransferFeeWithheldAmount(destAccountB);
assert.ok(withheldAmountA.eqn(99));
assert.ok(withheldAmountB.eqn(99));
});
it("decrease_liquidity_v2: out or range (above, tokenB amount is zero", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[1]; // [1] for above
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.isZero());
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.isZero());
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB).sub(new BN(postVaultBalanceB)).isZero(),
);
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(new BN(destBalanceB).isZero());
});
it("decrease_liquidity_v2: out or range (above, tokenA amount is zero", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[2]; // [2] for below
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
assert.ok(expectedAmount.tokenA.isZero());
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.isZero());
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA).sub(new BN(postVaultBalanceA)).isZero(),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).isZero());
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
});
it("decrease_liquidity_v2: [FAIL] TokenMinSubceeded due to transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const normalParams: DecreaseLiquidityV2Params = {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
};
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMinA: expectedAmount.tokenA,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// TransferFee is not taken into account
tokenMinB: expectedAmount.tokenB,
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set minA to expected + 1
tokenMinA: expectedAmount.tokenA
.sub(expectedTransferFeeExcludedAmountA.fee)
.addn(1),
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...normalParams,
// set minB to expected + 1
tokenMinB: expectedAmount.tokenB
.sub(expectedTransferFeeExcludedAmountB.fee)
.addn(1),
}),
).buildAndExecute(),
/0x1782/, // TokenMinSubceeded
);
// success with normal params
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, normalParams),
).buildAndExecute();
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let transferFeeA: TransferFee | null;
let transferFeeB: TransferFee | null;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
const variations: { tokenA: TokenTrait; tokenB: TokenTrait }[] = [
// both A & B has transfer fee
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
},
// only A has transfer fee
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
tokenB: { isToken2022: true, hasTransferFeeExtension: false },
},
// only B has transfer fee
{
tokenA: { isToken2022: true, hasTransferFeeExtension: false },
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
},
// both A & B has transfer fee extension, but bps is zero
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
];
variations.forEach(({ tokenA, tokenB }) => {
const labelA = `TokenA: transfer fee bps = ${
tokenA.hasTransferFeeExtension
? tokenA.transferFeeInitialBps?.toString()
: "none"
}`;
const labelB = `TokenB: transfer fee bps = ${
tokenB.hasTransferFeeExtension
? tokenB.transferFeeInitialBps?.toString()
: "none"
}`;
describe(`${labelA}, ${labelB}`, () => {
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
tokenA,
tokenB,
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
transferFeeA = tokenA.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintA)
: null;
transferFeeB = tokenB.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintB)
: null;
if (transferFeeA)
assert.equal(
transferFeeA.transferFeeBasisPoints,
tokenA.transferFeeInitialBps!,
);
if (transferFeeB)
assert.equal(
transferFeeB.transferFeeBasisPoints,
tokenB.transferFeeInitialBps!,
);
});
it("A --> B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(transferFeeA, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(
transferFeeB,
quoteAToB.estimatedAmountOut,
)
: { amount: quoteAToB.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = inputAmount.neg(); // out
const expectedOwnerAccountBDelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedVaultAccountADelta =
transferFeeExcludedInputAmount.amount; // in
const expectedVaultAccountBDelta = quoteAToB.estimatedAmountOut.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(transferFeeB, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(
transferFeeA,
quoteBToA.estimatedAmountOut,
)
: { amount: quoteBToA.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedOwnerAccountBDelta = inputAmount.neg(); // out
const expectedVaultAccountADelta = quoteBToA.estimatedAmountOut.neg(); // out
const expectedVaultAccountBDelta =
transferFeeExcludedInputAmount.amount; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A --> B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const outputAmount = new BN(2000000);
const transferFeeIncludedOutputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(transferFeeB, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(
transferFeeA,
quoteAToB.estimatedAmountIn,
)
: { amount: quoteAToB.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountBDelta = outputAmount; // in
const expectedVaultAccountADelta = quoteAToB.estimatedAmountIn; // in
const expectedVaultAccountBDelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const outputAmount = new BN(100000);
const transferFeeIncludedOutputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(transferFeeA, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(
transferFeeB,
quoteBToA.estimatedAmountIn,
)
: { amount: quoteBToA.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = outputAmount; // in
const expectedOwnerAccountBDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedVaultAccountADelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
const expectedVaultAccountBDelta = quoteBToA.estimatedAmountIn; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
});
});
const variationsWith100PercentFee: {
tokenA: TokenTrait;
tokenB: TokenTrait;
}[] = [
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
},
{
tokenA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
tokenB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
},
];
variationsWith100PercentFee.forEach(({ tokenA, tokenB }) => {
const labelA = `TokenA: transfer fee bps = ${tokenA.transferFeeInitialBps ? "100%" + (tokenA.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const labelB = `TokenB: transfer fee bps = ${tokenB.transferFeeInitialBps ? "100%" + (tokenB.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
describe(`${labelA}, ${labelB}`, () => {
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
poolInitInfo.tokenMintA,
tokenA.transferFeeInitialBps!,
tokenA.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
poolInitInfo.tokenMintB,
tokenB.transferFeeInitialBps!,
tokenB.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
// wait for epoch to enable updated fee rate
const updatedFeeConfigA = await fetchTransferFeeConfig(
poolInitInfo.tokenMintA,
);
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
transferFeeA = tokenA.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintA)
: null;
transferFeeB = tokenB.hasTransferFeeExtension
? await getTransferFee(poolInitInfo.tokenMintB)
: null;
assert.equal(
transferFeeA!.transferFeeBasisPoints,
tokenA.transferFeeInitialBps!,
);
assert.equal(
transferFeeA!.maximumFee,
tokenA.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFeeB!.transferFeeBasisPoints,
tokenB.transferFeeInitialBps!,
);
assert.equal(
transferFeeB!.maximumFee,
tokenB.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
});
it("A --> B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(100000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: true,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount (All amount is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(transferFeeA, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(
transferFeeB,
quoteAToB.estimatedAmountOut,
)
: { amount: quoteAToB.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = inputAmount.neg(); // out
const expectedOwnerAccountBDelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedVaultAccountADelta =
transferFeeExcludedInputAmount.amount; // in
const expectedVaultAccountBDelta = quoteAToB.estimatedAmountOut.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactIn", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const inputAmount = new BN(100000);
// edge-case
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: true,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1793/, // ZeroTradableAmount (All amount is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeB
? calculateTransferFeeExcludedAmount(transferFeeB, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeExcludedOutputAmount = transferFeeA
? calculateTransferFeeExcludedAmount(
transferFeeA,
quoteBToA.estimatedAmountOut,
)
: { amount: quoteBToA.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeExcludedOutputAmount.amount; // in
const expectedOwnerAccountBDelta = inputAmount.neg(); // out
const expectedVaultAccountADelta = quoteBToA.estimatedAmountOut.neg(); // out
const expectedVaultAccountBDelta =
transferFeeExcludedInputAmount.amount; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold:
transferFeeExcludedOutputAmount.amount.addn(1), // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1794/, // AmountOutBelowMinimum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A --> B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const outputAmount = new BN(2000000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine output size including transfer fee because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(transferFeeB, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteAToB = swapQuoteWithParams(
{
// A --> B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(
transferFeeA,
quoteAToB.estimatedAmountIn,
)
: { amount: quoteAToB.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountBDelta = outputAmount; // in
const expectedVaultAccountADelta = quoteAToB.estimatedAmountIn; // in
const expectedVaultAccountBDelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
assert.ok(expectedVaultAccountADelta.eq(quoteAToB.estimatedAmountIn));
assert.ok(
expectedVaultAccountBDelta.eq(quoteAToB.estimatedAmountOut.neg()),
);
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
it("A <-- B, ExactOut", async () => {
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = false;
const outputAmount = new BN(100000);
// edge-case
if (
transferFeeA!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeA!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine output size including transfer fee because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
if (
transferFeeB!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeB!.maximumFee === BigInt(U64_MAX.toString())
) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArrays = await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: outputAmount,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
amountSpecifiedIsInput: false,
aToB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[0].address,
tickArray2: tickArrays[0].address,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeA
? calculateTransferFeeIncludedAmount(transferFeeA, outputAmount)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeA && transferFeeA.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quoteBToA = swapQuoteWithParams(
{
// A <-- B, ExactOut
amountSpecifiedIsInput: false,
aToB,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeIncludedInputAmount = transferFeeB
? calculateTransferFeeIncludedAmount(
transferFeeB,
quoteBToA.estimatedAmountIn,
)
: { amount: quoteBToA.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeB && transferFeeB.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountADelta = outputAmount; // in
const expectedOwnerAccountBDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedVaultAccountADelta =
transferFeeIncludedOutputAmount.amount.neg(); // out
const expectedVaultAccountBDelta = quoteBToA.estimatedAmountIn; // in
assert.ok(
expectedVaultAccountADelta.eq(quoteBToA.estimatedAmountOut.neg()),
);
assert.ok(expectedVaultAccountBDelta.eq(quoteBToA.estimatedAmountIn));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold:
transferFeeIncludedInputAmount.amount.subn(1), // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute(),
/0x1795/, // AmountInAboveMaximum
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(
postVaultBalanceA
.sub(preVaultBalanceA)
.eq(expectedVaultAccountADelta),
);
assert.ok(
postVaultBalanceB
.sub(preVaultBalanceB)
.eq(expectedVaultAccountBDelta),
);
assert.ok(
postOwnerAccountBalanceA
.sub(preOwnerAccountBalanceA)
.eq(expectedOwnerAccountADelta),
);
assert.ok(
postOwnerAccountBalanceB
.sub(preOwnerAccountBalanceB)
.eq(expectedOwnerAccountBDelta),
);
});
});
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let aquarium: TestAquarium;
let whirlpoolOneKey: PublicKey;
let whirlpoolTwoKey: PublicKey;
let whirlpoolDataOne: WhirlpoolData;
let whirlpoolDataTwo: WhirlpoolData;
const variations: TokenTrait[][] = [
// all token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// input token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{ isToken2022: true, hasTransferFeeExtension: false },
{ isToken2022: true, hasTransferFeeExtension: false },
],
// input and mid token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{ isToken2022: true, hasTransferFeeExtension: false },
],
// output token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// output and mid token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// mid token has transfer fee
[
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
},
{ isToken2022: true, hasTransferFeeExtension: false },
],
// input and output token has transfer fee
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 300,
},
{ isToken2022: true, hasTransferFeeExtension: false },
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
},
],
// all token has transfer fee, but bps are zero
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
];
variations.forEach(([token0, token1, token2]) => {
const label0 = `Token0: transfer fee bps = ${
token0.hasTransferFeeExtension
? token0.transferFeeInitialBps?.toString()
: "none"
}`;
const label1 = `Token1: transfer fee bps = ${
token1.hasTransferFeeExtension
? token1.transferFeeInitialBps?.toString()
: "none"
}`;
const label2 = `Token2: transfer fee bps = ${
token2.hasTransferFeeExtension
? token2.transferFeeInitialBps?.toString()
: "none"
}`;
describe(`${label0}, ${label1}, ${label2}`, () => {
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: token0 },
{ tokenTrait: token1 },
{ tokenTrait: token2 },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { pools } = aquarium;
whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
});
it("T0 --> T1 --> T2, ExactIn", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(1000);
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(midToken);
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactIn", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(100000);
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintA.equals(midToken);
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 --> T1 --> T2, ExactOut", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(500000);
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataOne.tokenMintB.equals(midToken);
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactOut", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(1000);
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const aToBTwo = whirlpoolDataOne.tokenMintB.equals(outputToken);
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const aToBOne = whirlpoolDataTwo.tokenMintB.equals(midToken);
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
const pools = aquarium.pools;
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
});
});
const variationsWith100PercentFee: TokenTrait[][] = [
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
},
],
[
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
{
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: MAX_FEE_BASIS_POINTS,
transferFeeInitialMax: 99n,
},
],
];
variationsWith100PercentFee.forEach(([token0, token1, token2]) => {
const label0 = `Token0: transfer fee bps = ${token0.transferFeeInitialBps ? "100%" + (token0.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const label1 = `Token1: transfer fee bps = ${token1.transferFeeInitialBps ? "100%" + (token1.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
const label2 = `Token2: transfer fee bps = ${token2.transferFeeInitialBps ? "100%" + (token2.transferFeeInitialMax ? " with cap" : " without cap") : "0%"}`;
describe(`${label0}, ${label1}, ${label2}`, () => {
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
{
tokenTrait: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 0,
},
},
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { pools } = aquarium;
whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
pools[0].tokenMintA,
token0.transferFeeInitialBps!,
token0.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
pools[0].tokenMintB,
token1.transferFeeInitialBps!,
token1.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
createSetTransferFeeInstruction(
pools[1].tokenMintB,
token2.transferFeeInitialBps!,
token2.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
// wait for epoch to enable updated fee rate
const updatedFeeConfig0 = await fetchTransferFeeConfig(
pools[0].tokenMintA,
);
await waitEpoch(Number(updatedFeeConfig0.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfig0.newerTransferFee.epoch,
);
const transferFee0 = await getTransferFee(pools[0].tokenMintA);
const transferFee1 = await getTransferFee(pools[0].tokenMintB);
const transferFee2 = await getTransferFee(pools[1].tokenMintB);
assert.equal(
transferFee0!.transferFeeBasisPoints,
token0.transferFeeInitialBps!,
);
assert.equal(
transferFee0!.maximumFee,
token0.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFee1!.transferFeeBasisPoints,
token1.transferFeeInitialBps!,
);
assert.equal(
transferFee1!.maximumFee,
token1.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
assert.equal(
transferFee2!.transferFeeBasisPoints,
token2.transferFeeInitialBps!,
);
assert.equal(
transferFee2!.maximumFee,
token2.transferFeeInitialMax ?? BigInt(U64_MAX.toString()),
);
});
it("T0 --> T1 --> T2, ExactIn", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(1000);
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || midWithoutCap) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: true,
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
aToBOne,
aToBTwo,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolOneKey,
whirlpoolTwo: whirlpoolTwoKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultOneIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenVaultTwoIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultTwoOutput: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenOwnerAccountInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysOne[0].address,
tickArrayOne1: tickArraysOne[0].address,
tickArrayOne2: tickArraysOne[0].address,
tickArrayTwo0: tickArraysTwo[0].address,
tickArrayTwo1: tickArraysTwo[0].address,
tickArrayTwo2: tickArraysTwo[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
}),
).buildAndExecute(),
inputWithoutCap
? /0x1793/ // ZeroTradableAmount (All amount is collected as transfer fee...)
: /0x1793/, // ZeroTradableAmount (all intermediate token is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactIn", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const inputAmount = new BN(100000);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(inputToken);
const aToBOne = whirlpoolDataOne.tokenMintA.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || midWithoutCap) {
// we cannot determine input size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: true,
amount: inputAmount,
otherAmountThreshold: new BN(0),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
aToBOne: aToBTwo,
aToBTwo: aToBOne,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolTwoKey,
whirlpoolTwo: whirlpoolOneKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultOneIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenVaultTwoIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultTwoOutput: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenOwnerAccountInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysTwo[0].address,
tickArrayOne1: tickArraysTwo[0].address,
tickArrayOne2: tickArraysTwo[0].address,
tickArrayTwo0: tickArraysOne[0].address,
tickArrayTwo1: tickArraysOne[0].address,
tickArrayTwo2: tickArraysOne[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
}),
).buildAndExecute(),
inputWithoutCap
? /0x1793/ // ZeroTradableAmount (All amount is collected as transfer fee...)
: /0x1793/, // ZeroTradableAmount (all intermediate token is collected as transfer fee...)
);
return;
}
const transferFeeExcludedInputAmount = transferFeeInput
? calculateTransferFeeExcludedAmount(transferFeeInput, inputAmount)
: { amount: inputAmount, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// vault -> owner
const transferFeeExcludedMidOutputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, quote.estimatedAmountOut)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidOutputAmount.fee.gtn(0));
// owner -> vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(transferFeeMid, transferFeeExcludedMidOutputAmount.amount)
: { amount: transferFeeExcludedMidOutputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeExcludedMidInputAmount = transferFeeMid
? calculateTransferFeeExcludedAmount(
transferFeeMid,
quote.estimatedAmountOut,
)
: { amount: quote.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedMidInputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactIn
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: transferFeeExcludedMidInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeExcludedOutputAmount = transferFeeOutput
? calculateTransferFeeExcludedAmount(
transferFeeOutput,
quote2.estimatedAmountOut,
)
: { amount: quote2.estimatedAmountOut, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta = inputAmount.neg(); // out
const expectedOwnerAccountOutputDelta =
transferFeeExcludedOutputAmount.amount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
transferFeeExcludedInputAmount.amount,
quote.estimatedAmountOut.neg(),
]
: [
quote.estimatedAmountOut.neg(),
transferFeeExcludedInputAmount.amount,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
transferFeeExcludedMidInputAmount.amount,
quote2.estimatedAmountOut.neg(),
]
: [
quote2.estimatedAmountOut.neg(),
transferFeeExcludedMidInputAmount.amount,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: inputAmount, // transfer fee included
otherAmountThreshold: transferFeeExcludedOutputAmount.amount, // transfer fee excluded
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.addn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1794/, // AmountOutBelowMinimum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("in", transferFeeExcludedInputAmount.amount.toString(), transferFeeExcludedInputAmount.fee.toString());
//console.info("midout", transferFeeExcludedMidOutputAmount.amount.toString(), transferFeeExcludedMidOutputAmount.fee.toString());
//console.info("midin", transferFeeExcludedMidInputAmount.amount.toString(), transferFeeExcludedMidInputAmount.fee.toString());
//console.info("out", transferFeeExcludedOutputAmount.amount.toString(), transferFeeExcludedOutputAmount.fee.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
});
it("T0 --> T1 --> T2, ExactOut", async () => {
const [inputToken, midToken, outputToken] = aquarium.mintKeys;
const [inputTokenTrait, midTokenTrait, outputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(500000);
const aToBTwo = whirlpoolDataTwo.tokenMintB.equals(outputToken);
const aToBOne = whirlpoolDataOne.tokenMintB.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
const outputWithoutCap =
transferFeeOutput!.transferFeeBasisPoints ===
MAX_FEE_BASIS_POINTS &&
transferFeeOutput!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || outputWithoutCap || midWithoutCap) {
// we cannot determine input/output size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: false,
amount: outputAmount,
otherAmountThreshold: new BN(U64_MAX.toString()),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
aToBOne,
aToBTwo,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolOneKey,
whirlpoolTwo: whirlpoolTwoKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultOneIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenVaultTwoIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultTwoOutput: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenOwnerAccountInput: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysOne[0].address,
tickArrayOne1: tickArraysOne[0].address,
tickArrayOne2: tickArraysOne[0].address,
tickArrayTwo0: tickArraysTwo[0].address,
tickArrayTwo1: tickArraysTwo[0].address,
tickArrayTwo2: tickArraysTwo[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T1 --> T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T0 --> T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBOne} ${aToBTwo}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
it("T0 <-- T1 <-- T2, ExactOut", async () => {
const [outputToken, midToken, inputToken] = aquarium.mintKeys;
const [outputTokenTrait, midTokenTrait, inputTokenTrait] = [
token0,
token1,
token2,
];
const transferFeeInput = inputTokenTrait.hasTransferFeeExtension
? await getTransferFee(inputToken)
: null;
const transferFeeMid = midTokenTrait.hasTransferFeeExtension
? await getTransferFee(midToken)
: null;
const transferFeeOutput = outputTokenTrait.hasTransferFeeExtension
? await getTransferFee(outputToken)
: null;
const outputAmount = new BN(1000);
const aToBTwo = whirlpoolDataOne.tokenMintB.equals(outputToken);
const aToBOne = whirlpoolDataTwo.tokenMintB.equals(midToken);
const pools = aquarium.pools;
// edge-case
const inputWithoutCap =
transferFeeInput!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeInput!.maximumFee === BigInt(U64_MAX.toString());
const midWithoutCap =
transferFeeMid!.transferFeeBasisPoints === MAX_FEE_BASIS_POINTS &&
transferFeeMid!.maximumFee === BigInt(U64_MAX.toString());
const outputWithoutCap =
transferFeeOutput!.transferFeeBasisPoints ===
MAX_FEE_BASIS_POINTS &&
transferFeeOutput!.maximumFee === BigInt(U64_MAX.toString());
if (inputWithoutCap || outputWithoutCap || midWithoutCap) {
// we cannot determine input/output size because all amount will be collected as transfer fee
const tickArraysOne = await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
);
const tickArraysTwo = await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
amountSpecifiedIsInput: false,
amount: outputAmount,
otherAmountThreshold: new BN(U64_MAX.toString()),
sqrtPriceLimitOne:
SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
sqrtPriceLimitTwo:
SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
aToBOne: aToBTwo,
aToBTwo: aToBOne,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: whirlpoolTwoKey,
whirlpoolTwo: whirlpoolOneKey,
tokenMintInput: inputToken,
tokenMintIntermediate: midToken,
tokenMintOutput: outputToken,
tokenProgramInput: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramIntermediate: TEST_TOKEN_2022_PROGRAM_ID,
tokenProgramOutput: TEST_TOKEN_2022_PROGRAM_ID,
tokenVaultOneInput: aToBTwo
? whirlpoolDataTwo.tokenVaultA
: whirlpoolDataTwo.tokenVaultB,
tokenVaultOneIntermediate: aToBTwo
? whirlpoolDataTwo.tokenVaultB
: whirlpoolDataTwo.tokenVaultA,
tokenVaultTwoIntermediate: aToBOne
? whirlpoolDataOne.tokenVaultA
: whirlpoolDataOne.tokenVaultB,
tokenVaultTwoOutput: aToBOne
? whirlpoolDataOne.tokenVaultB
: whirlpoolDataOne.tokenVaultA,
tokenOwnerAccountInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenOwnerAccountOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tickArrayOne0: tickArraysTwo[0].address,
tickArrayOne1: tickArraysTwo[0].address,
tickArrayOne2: tickArraysTwo[0].address,
tickArrayTwo0: tickArraysOne[0].address,
tickArrayTwo1: tickArraysOne[0].address,
tickArrayTwo2: tickArraysOne[0].address,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolTwoKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
whirlpoolOneKey,
).publicKey,
}),
).buildAndExecute(),
/0x17a4/, // TransferFeeCalculationError
);
return;
}
const transferFeeIncludedOutputAmount = transferFeeOutput
? calculateTransferFeeIncludedAmount(
transferFeeOutput,
outputAmount,
)
: { amount: outputAmount, fee: ZERO_BN };
if (transferFeeOutput && transferFeeOutput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedOutputAmount.fee.gtn(0));
const quote2 = swapQuoteWithParams(
{
// T0 <-- T1, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBTwo,
tokenAmount: transferFeeIncludedOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
/*
// owner -> vault
const transferFeeIncludedMidInputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, quote2.estimatedAmountIn)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidInputAmount.fee.gtn(0));
// vault -> owner
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(transferFeeMid, transferFeeIncludedMidInputAmount.amount)
: { amount: transferFeeIncludedMidInputAmount.amount, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
*/
// vault to vault
const transferFeeIncludedMidOutputAmount = transferFeeMid
? calculateTransferFeeIncludedAmount(
transferFeeMid,
quote2.estimatedAmountIn,
)
: { amount: quote2.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeMid && transferFeeMid.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedMidOutputAmount.fee.gtn(0));
const quote = swapQuoteWithParams(
{
// T1 <-- T2, ExactOut
amountSpecifiedIsInput: false,
aToB: aToBOne,
tokenAmount: transferFeeIncludedMidOutputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(false),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100),
);
const transferFeeIncludedInputAmount = transferFeeInput
? calculateTransferFeeIncludedAmount(
transferFeeInput,
quote.estimatedAmountIn,
)
: { amount: quote.estimatedAmountIn, fee: ZERO_BN };
if (transferFeeInput && transferFeeInput.transferFeeBasisPoints > 0)
assert.ok(transferFeeIncludedInputAmount.fee.gtn(0));
const expectedOwnerAccountInputDelta =
transferFeeIncludedInputAmount.amount.neg(); // out
const expectedOwnerAccountOutputDelta = outputAmount; // in
const [expectedVaultAccountTwoADelta, expectedVaultAccountTwoBDelta] =
aToBTwo
? [
quote2.estimatedAmountIn,
transferFeeIncludedOutputAmount.amount.neg(),
]
: [
transferFeeIncludedOutputAmount.amount.neg(),
quote2.estimatedAmountIn,
];
const [expectedVaultAccountOneADelta, expectedVaultAccountOneBDelta] =
aToBOne
? [
quote.estimatedAmountIn,
transferFeeIncludedMidOutputAmount.amount.neg(),
]
: [
transferFeeIncludedMidOutputAmount.amount.neg(),
quote.estimatedAmountIn,
];
assert.ok(
expectedVaultAccountTwoADelta.eq(
aToBTwo
? quote2.estimatedAmountIn
: quote2.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountTwoBDelta.eq(
aToBTwo
? quote2.estimatedAmountOut.neg()
: quote2.estimatedAmountIn,
),
);
assert.ok(
expectedVaultAccountOneADelta.eq(
aToBOne
? quote.estimatedAmountIn
: quote.estimatedAmountOut.neg(),
),
);
assert.ok(
expectedVaultAccountOneBDelta.eq(
aToBOne
? quote.estimatedAmountOut.neg()
: quote.estimatedAmountIn,
),
);
const tokenAccKeys = getTokenAccsForPoolsV2(
pools,
aquarium.tokenAccounts,
);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
const baseIxParams: TwoHopSwapV2Params = {
...twoHopQuote,
amount: outputAmount, // transfer fee excluded
otherAmountThreshold: transferFeeIncludedInputAmount.amount, // transfer fee included
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[1].whirlpoolPda.publicKey,
whirlpoolTwo: pools[0].whirlpoolPda.publicKey,
tokenMintInput: aToBTwo ? pools[1].tokenMintA : pools[1].tokenMintB,
tokenMintIntermediate: aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenMintOutput: aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenProgramInput: aToBTwo
? pools[1].tokenProgramA
: pools[1].tokenProgramB,
tokenProgramIntermediate: aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenProgramOutput: aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenOwnerAccountInput: aToBTwo ? tokenAccKeys[2] : tokenAccKeys[3],
tokenOwnerAccountOutput: aToBOne
? tokenAccKeys[1]
: tokenAccKeys[0],
tokenVaultOneInput: aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
};
const preVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const preVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const preOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
otherAmountThreshold: baseIxParams.otherAmountThreshold.subn(1),
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(), // add CU
/0x1795/, // AmountInAboveMaximum
);
await toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams))
.prependInstruction(useMaxCU())
.buildAndExecute(); // add CU
const postVaultBalanceOneA = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceOneB = new BN(
await getTokenBalance(
provider,
pools[1].tokenVaultBKeypair.publicKey,
),
);
const postVaultBalanceTwoA = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceTwoB = new BN(
await getTokenBalance(
provider,
pools[0].tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceInput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountInput,
),
);
const postOwnerAccountBalanceOutput = new BN(
await getTokenBalance(
provider,
baseIxParams.tokenOwnerAccountOutput,
),
);
assert.ok(
postVaultBalanceOneA
.sub(preVaultBalanceOneA)
.eq(expectedVaultAccountOneADelta),
);
assert.ok(
postVaultBalanceOneB
.sub(preVaultBalanceOneB)
.eq(expectedVaultAccountOneBDelta),
);
assert.ok(
postVaultBalanceTwoA
.sub(preVaultBalanceTwoA)
.eq(expectedVaultAccountTwoADelta),
);
assert.ok(
postVaultBalanceTwoB
.sub(preVaultBalanceTwoB)
.eq(expectedVaultAccountTwoBDelta),
);
assert.ok(
postOwnerAccountBalanceInput
.sub(preOwnerAccountBalanceInput)
.eq(expectedOwnerAccountInputDelta),
);
assert.ok(
postOwnerAccountBalanceOutput
.sub(preOwnerAccountBalanceOutput)
.eq(expectedOwnerAccountOutputDelta),
);
//console.info(`aToB: ${aToBTwo} ${aToBOne}`);
//console.info("out", transferFeeIncludedOutputAmount.amount.toString(), transferFeeIncludedOutputAmount.fee.toString());
//console.info("midin", transferFeeIncludedMidInputAmount.amount.toString(), transferFeeIncludedMidInputAmount.fee.toString());
//console.info("midout", transferFeeIncludedMidOutputAmount.amount.toString(), transferFeeIncludedMidOutputAmount.fee.toString());
//console.info("in", transferFeeIncludedInputAmount.amount.toString(), transferFeeIncludedInputAmount.fee.toString());
//console.info("q2", quote2.estimatedAmountIn.toString(), quote2.estimatedAmountOut.toString());
//console.info("q1", quote.estimatedAmountIn.toString(), quote.estimatedAmountOut.toString());
});
});
});
});
describe("Special cases", () => {
// We know that all transfers are executed 2 functions depending on the direction, so 2 test cases.
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
const mintAmount = new BN(2_000_000_000);
const tickSpacing = 1;
const rangeLowerTickIndex = -64;
const rangeUpperTickIndex = +64;
const currentTickIndex = 0;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex,
rangeLowerTickIndex,
rangeUpperTickIndex,
{
// half deposit (50:50)
tokenA: mintAmount.divn(2),
tokenB: mintAmount.divn(2),
},
);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 500,
transferFeeInitialMax: 100_000n,
},
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
transferFeeInitialBps: 1000,
transferFeeInitialMax: 200_000n,
},
tickSpacing,
// pool has much liquidity in both direction
positions: [
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
});
describe("use current fee rate even if next fee rate exists", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints,
500,
);
assert.equal(
initialFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
initialFeeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.lt(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
// PREPEND setTransferFee ix
tx.prependInstruction({
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
2000,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
});
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
// but newer fee bps have been updated
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
2000,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
});
it("vault to owner", async () => {
// in A to B, vault to owner is output
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1000,
);
assert.equal(
initialFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
initialFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.lt(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
// PREPEND setTransferFee ix
tx.prependInstruction({
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
1500,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
});
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
// but newer fee bps have been updated
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1500,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
});
});
describe("use updated fee rate once epoch comes", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints,
500,
);
assert.equal(
initialFeeConfigA.olderTransferFee.transferFeeBasisPoints,
500,
);
const newBpsList = [2000, 3000];
let oldBps = 500;
for (let i = 0; i < newBpsList.length; i++) {
const newBps = newBpsList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
newBps,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.transferFeeBasisPoints,
newBps,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.transferFeeBasisPoints,
oldBps,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
updatedFeeConfigA,
BigInt(await getCurrentEpoch()),
);
assert.ok(transferFeeA.transferFeeBasisPoints === newBps);
// non zero, but not limited by maximum
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.lt(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
oldBps = newBps;
}
});
it("vault to owner", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints,
1000,
);
assert.equal(
initialFeeConfigB.olderTransferFee.transferFeeBasisPoints,
1000,
);
const newBpsList = [2000, 3000];
let oldBps = 1000;
for (let i = 0; i < newBpsList.length; i++) {
const newBps = newBpsList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
newBps,
BigInt(U64_MAX.toString()),
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.transferFeeBasisPoints,
newBps,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.transferFeeBasisPoints,
oldBps,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigB.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
updatedFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, but not limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.lt(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current bps
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
oldBps = newBps;
}
});
});
describe("use maximum limit", () => {
it("owner to vault", async () => {
// in A to B, owner to vault is input
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
// fee config is initialized with older = newer state
const initialFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(initialFeeConfigA.newerTransferFee.maximumFee, 100_000n);
assert.equal(initialFeeConfigA.olderTransferFee.maximumFee, 100_000n);
const newMaximumFeeList = [10_000n, 1_000n];
let oldMaximumFee = 100_000n;
for (let i = 0; i < newMaximumFeeList.length; i++) {
const newMaximumFee = newMaximumFeeList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenA,
initialFeeConfigA.newerTransferFee.transferFeeBasisPoints, // no change
newMaximumFee,
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigA = await fetchTransferFeeConfig(tokenA);
assert.equal(
updatedFeeConfigA.newerTransferFee.maximumFee,
newMaximumFee,
);
assert.equal(
updatedFeeConfigA.olderTransferFee.maximumFee,
oldMaximumFee,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigA.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigA.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeA = getEpochFee(
updatedFeeConfigA,
BigInt(await getCurrentEpoch()),
);
assert.ok(transferFeeA.maximumFee === newMaximumFee);
// non zero, and limited by maximum
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
assert.ok(transferFeeExcludedInputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedInputAmount.fee.eq(
new BN(transferFeeA.maximumFee.toString()),
),
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
await tx.buildAndExecute();
const postWithheldAmount = await fetchTransferFeeWithheldAmount(
poolInitInfo.tokenVaultAKeypair.publicKey,
);
// fee is based on the current maximum
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedInputAmount.fee));
oldMaximumFee = newMaximumFee;
}
});
it("vault to owner", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
// fee config is initialized with older = newer state
const initialFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(initialFeeConfigB.newerTransferFee.maximumFee, 200_000n);
assert.equal(initialFeeConfigB.olderTransferFee.maximumFee, 200_000n);
const newMaximumFeeList = [10_000n, 1_000n];
let oldMaximumFee = 200_000n;
for (let i = 0; i < newMaximumFeeList.length; i++) {
const newMaximumFee = newMaximumFeeList[i];
// update fee config
await toTx(ctx, {
cleanupInstructions: [],
signers: [], // provider.wallet is authority & payer
instructions: [
createSetTransferFeeInstruction(
tokenB,
initialFeeConfigB.newerTransferFee.transferFeeBasisPoints, // no change
newMaximumFee,
provider.wallet.publicKey,
),
],
}).buildAndExecute();
const updatedFeeConfigB = await fetchTransferFeeConfig(tokenB);
assert.equal(
updatedFeeConfigB.newerTransferFee.maximumFee,
newMaximumFee,
);
assert.equal(
updatedFeeConfigB.olderTransferFee.maximumFee,
oldMaximumFee,
);
// wait for epoch to enable updated fee rate
await waitEpoch(Number(updatedFeeConfigB.newerTransferFee.epoch));
assert.ok(
(await getCurrentEpoch()) >=
updatedFeeConfigB.newerTransferFee.epoch,
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedInputAmount =
calculateTransferFeeExcludedAmount(transferFeeA, inputAmount);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const transferFeeB = getEpochFee(
updatedFeeConfigB,
BigInt(await getCurrentEpoch()),
);
const transferFeeExcludedOutputAmount =
calculateTransferFeeExcludedAmount(
transferFeeB,
quote.estimatedAmountOut,
);
// non zero, and limited by maximum
assert.ok(transferFeeExcludedOutputAmount.fee.gtn(0));
assert.ok(
transferFeeExcludedOutputAmount.fee.eq(
new BN(transferFeeB.maximumFee.toString()),
),
);
const tx = toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
);
const preWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
await tx.buildAndExecute();
const postWithheldAmount =
await fetchTransferFeeWithheldAmount(tokenAccountB);
// fee is based on the current maximum
const withheldDelta = postWithheldAmount.sub(preWithheldAmount);
assert.ok(withheldDelta.eq(transferFeeExcludedOutputAmount.fee));
oldMaximumFee = newMaximumFee;
}
});
});
it("logging applied TransferFee config info", async () => {
const { poolInitInfo, tokenAccountA, tokenAccountB } = fixture.getInfos();
const tokenA = poolInitInfo.tokenMintA;
const tokenB = poolInitInfo.tokenMintB;
const feeConfigA = await fetchTransferFeeConfig(tokenA);
const feeConfigB = await fetchTransferFeeConfig(tokenB);
const transferFeeA = getEpochFee(
feeConfigA,
BigInt(await getCurrentEpoch()),
);
const transferFeeB = getEpochFee(
feeConfigB,
BigInt(await getCurrentEpoch()),
);
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
let whirlpoolData = (await fetcher.getPool(
whirlpoolPubkey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const inputAmount = new BN(1_000_000);
const transferFeeExcludedInputAmount = calculateTransferFeeExcludedAmount(
transferFeeA,
inputAmount,
);
const quote = swapQuoteWithParams(
{
// A --> B, ExactIn
amountSpecifiedIsInput: true,
aToB,
tokenAmount: transferFeeExcludedInputAmount.amount,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: withNoExtension, // TransferFee is taken into account later
},
Percentage.fromFraction(0, 100), // 0% slippage
);
const sig = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
amount: inputAmount,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true), // not interested in this case
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(ctx.program.programId, whirlpoolPubkey)
.publicKey,
}),
).buildAndExecute();
const parsedTx = await provider.connection.getParsedTransaction(sig, {
maxSupportedTransactionVersion: 0,
});
assert.ok(parsedTx?.meta?.innerInstructions);
assert.ok(parsedTx!.meta!.innerInstructions.length === 1); // twoHopSwap only (top-level ix)
const memoLogs = parsedTx!.meta!.innerInstructions[0].instructions.filter(
(ix) => ix.programId.equals(MEMO_PROGRAM_ADDRESS),
);
assert.ok(memoLogs.length === 2);
assert.ok(
(memoLogs[0] as { parsed: string }).parsed ===
`TFe: ${transferFeeA.transferFeeBasisPoints}, ${transferFeeA.maximumFee}`,
);
assert.ok(
(memoLogs[1] as { parsed: string }).parsed ===
`TFe: ${transferFeeB.transferFeeBasisPoints}, ${transferFeeB.maximumFee}`,
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/non-confidential-transfer.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import { createTokenAccountV2 } from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import { hasConfidentialTransferMintExtension } from "../../../utils/v2/confidential-transfer";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/ConfidentialTransfer (NON confidential transfer only)", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: non confidential transfer", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintA),
);
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintB),
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
});
it("collect_protocol_fees_v2: non confidential transfer", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintA),
);
assert.ok(
await hasConfidentialTransferMintExtension(provider, tokenMintB),
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
// Lock the collectRewards quote to the last time we called updateFeesAndRewards
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: non confidential transfer", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(
hasConfidentialTransferMintExtension(provider, rewards[i].rewardMint),
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: non confidential transfer", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tokenTraitB: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(1_000_000),
sqrtPrice: poolBefore.sqrtPrice,
slippageTolerance: Percentage.fromFraction(1, 100),
tickCurrentIndex: poolBefore.tickCurrentIndex,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolBefore,
IGNORE_CACHE,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: non confidential transfer", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true, hasConfidentialTransferExtension: true },
{ isToken2022: true, hasConfidentialTransferExtension: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
});
it("swap_v2: non confidential transfer, a to b", async () => {
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(postBalanceA.lt(preBalanceA));
assert.ok(postBalanceB.gt(preBalanceB));
});
it("swap_v2: non confidential transfer, b to a", async () => {
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
);
assert.ok(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
);
const preBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const postBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
assert.ok(postBalanceA.gt(preBalanceA));
assert.ok(postBalanceB.lt(preBalanceB));
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenAccountIn: PublicKey;
let tokenAccountOut: PublicKey;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
{
tokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
},
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
tokenAccountIn = baseIxParams.tokenOwnerAccountInput;
tokenAccountOut = baseIxParams.tokenOwnerAccountOutput;
});
it("two_hop_swap_v2: non confidential transfer", async () => {
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/memo-transfer.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
NUM_REWARDS,
PDAUtil,
swapQuoteWithParams,
SwapUtils,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
} from "../../../utils/v2/init-utils-v2";
import {
createTokenAccountV2,
disableRequiredMemoTransfers,
enableRequiredMemoTransfers,
isRequiredMemoTransfersEnabled,
} from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("TokenExtension/MemoTransfer", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const MEMO_TRANSFER_COLLECT_FEES = "Orca CollectFees";
const MEMO_TRANSFER_COLLECT_PROTOCOL_FEES = "Orca CollectProtocolFees";
const MEMO_TRANSFER_COLLECT_REWARD = "Orca CollectReward";
const MEMO_TRANSFER_DECREASE_LIQUIDITY = "Orca Withdraw";
const MEMO_TRANSFER_SWAP = "Orca Trade";
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
});
it("collect_fees_v2: without memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_fees_v2: with memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 2);
});
it("collect_fees_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
await disableRequiredMemoTransfers(provider, feeAccountA);
await disableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
}),
).buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_protocol_fees_v2: without memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 0);
});
it("collect_protocol_fees_v2: with memo", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 2);
});
it("collect_protocol_fees_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await enableRequiredMemoTransfers(provider, feeAccountA);
await enableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, feeAccountB));
await disableRequiredMemoTransfers(provider, feeAccountA);
await disableRequiredMemoTransfers(provider, feeAccountB);
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountA)));
assert.ok(!(await isRequiredMemoTransfersEnabled(provider, feeAccountB)));
const sig = await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_PROTOCOL_FEES,
);
assert.equal(memoCount, 0);
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: true },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
// Lock the collectRewards quote to the last time we called updateFeesAndRewards
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
});
it("collect_reward_v2: without memo", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i])),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 0);
}
});
it("collect_reward_v2: with memo", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await enableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i]),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 1);
}
});
it("collect_reward_v2: without memo (has extension, but disabled)", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await enableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i]),
);
await disableRequiredMemoTransfers(provider, rewardAccounts[i]);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, rewardAccounts[i])),
);
const sig = await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
}),
).buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_COLLECT_REWARD,
);
assert.equal(memoCount, 0);
}
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(1_000_000),
sqrtPrice: poolBefore.sqrtPrice,
slippageTolerance: Percentage.fromFraction(1, 100),
tickCurrentIndex: poolBefore.tickCurrentIndex,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolBefore,
IGNORE_CACHE,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: without memo", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 0);
});
it("decrease_liquidity_v2: with memo", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await enableRequiredMemoTransfers(provider, destAccountA);
await enableRequiredMemoTransfers(provider, destAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountB));
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 2);
});
it("decrease_liquidity_v2: without memo (has extension, but disabled)", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await enableRequiredMemoTransfers(provider, destAccountA);
await enableRequiredMemoTransfers(provider, destAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, destAccountB));
await disableRequiredMemoTransfers(provider, destAccountA);
await disableRequiredMemoTransfers(provider, destAccountB);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, destAccountA)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, destAccountB)),
);
const sig = await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
).buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const memoCount = await countMemoLog(
provider,
sig,
MEMO_TRANSFER_DECREASE_LIQUIDITY,
);
assert.equal(memoCount, 0);
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true },
{ isToken2022: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
});
it("swap_v2: without memo", async () => {
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 0);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 0);
});
it("swap_v2: with memo", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountA);
await enableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountB));
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 1);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 1);
});
it("swap_v2: without memo (has extension, but disabled", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountA);
await enableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountA));
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountB));
await disableRequiredMemoTransfers(provider, tokenAccountA);
await disableRequiredMemoTransfers(provider, tokenAccountB);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountA)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountB)),
);
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
const sigBToA = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceB1.lt(balanceB0));
assert.ok(balanceA1.gt(balanceA0));
const memoCountBToA = await countMemoLog(
provider,
sigBToA,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountBToA, 0);
const sigAToB = await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA2 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB2 = new BN(await getTokenBalance(provider, tokenAccountB));
assert.ok(balanceA2.lt(balanceA1));
assert.ok(balanceB2.gt(balanceB1));
const memoCountAToB = await countMemoLog(
provider,
sigAToB,
MEMO_TRANSFER_SWAP,
);
assert.equal(memoCountAToB, 0);
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenAccountIn: PublicKey;
let tokenAccountOut: PublicKey;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
tokenAccountIn = baseIxParams.tokenOwnerAccountInput;
tokenAccountOut = baseIxParams.tokenOwnerAccountOutput;
});
it("two_hop_swap_v2: without memo", async () => {
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 0);
});
it("two_hop_swap_v2: with memo", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountIn);
await enableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn));
assert.ok(
await isRequiredMemoTransfersEnabled(provider, tokenAccountOut),
);
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 1); // mid token uses vault to vault transfer, so no memo
});
it("two_hop_swap_v2: without memo (has extension, but disabled", async () => {
await enableRequiredMemoTransfers(provider, tokenAccountIn);
await enableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn));
assert.ok(
await isRequiredMemoTransfersEnabled(provider, tokenAccountOut),
);
await disableRequiredMemoTransfers(provider, tokenAccountIn);
await disableRequiredMemoTransfers(provider, tokenAccountOut);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountIn)),
);
assert.ok(
!(await isRequiredMemoTransfersEnabled(provider, tokenAccountOut)),
);
const preBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const preBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
const sig = await toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, baseIxParams),
).buildAndExecute();
const postBalanceIn = new BN(
await getTokenBalance(provider, tokenAccountIn),
);
const postBalanceOut = new BN(
await getTokenBalance(provider, tokenAccountOut),
);
assert.ok(postBalanceIn.lt(preBalanceIn));
assert.ok(postBalanceOut.gt(preBalanceOut));
const memoCount = await countMemoLog(provider, sig, MEMO_TRANSFER_SWAP);
assert.equal(memoCount, 0);
});
});
});
async function countMemoLog(
provider: anchor.AnchorProvider,
signature: string,
logMessage: string,
): Promise<number> {
const logLen = logMessage.length;
const logFormat = `Program log: Memo (len ${logLen}): "${logMessage}"`;
const tx = await provider.connection.getParsedTransaction(signature, {
maxSupportedTransactionVersion: 0,
});
const memos = tx?.meta?.logMessages?.filter((msg) => msg === logFormat);
return memos!.length;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/non-confidential-transfer+transfer-fee.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import * as assert from "assert";
import type { PositionData, WhirlpoolData } from "../../../../src";
import {
PoolUtil,
PriceMath,
TickUtil,
toTokenAmount,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import {
calculateTransferFeeExcludedAmount,
calculateTransferFeeIncludedAmount,
createTokenAccountV2,
} from "../../../utils/v2/token-2022";
import type { PublicKey } from "@solana/web3.js";
import {
hasConfidentialTransferFeeConfigExtension,
hasConfidentialTransferMintExtension,
} from "../../../utils/v2/confidential-transfer";
import type { TransferFee } from "@solana/spl-token";
import { getEpochFee, getMint, getTransferFeeConfig } from "@solana/spl-token";
describe("TokenExtension/ConfidentialTransfer (NON confidential transfer only) + TransferFee", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
// ConfidentialTransfer + TransferFee is combination test
// We'll test owner to vault transfer by increase liquidity, vault to owner transfer by decrease liquidity
async function getTransferFee(mint: PublicKey): Promise<TransferFee> {
const mintData = await getMint(
provider.connection,
mint,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfig = getTransferFeeConfig(mintData);
assert.ok(transferFeeConfig !== null);
const epochInfo = await provider.connection.getEpochInfo();
const transferFee = getEpochFee(transferFeeConfig, BigInt(epochInfo.epoch));
return transferFee;
}
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
let fixture: WhirlpoolTestFixtureV2;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount: ZERO_BN,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount: ZERO_BN,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
});
it("increase_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
// transfer fee
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// confidential transfer
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
// confidential transfer fee config
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
const tokenAmount = toTokenAmount(1_000_000 * 0.8, 1_000_000 * 0.8);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const requiredAmountDelta = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
PriceMath.tickIndexToSqrtPriceX64(currTick),
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// transfer fee should be non zero
assert.ok(requiredAmountDelta.tokenA.gtn(0));
assert.ok(requiredAmountDelta.tokenB.gtn(0));
const expectedTransferFeeIncludedAmountA =
calculateTransferFeeIncludedAmount(
transferFeeA,
requiredAmountDelta.tokenA,
);
const expectedTransferFeeIncludedAmountB =
calculateTransferFeeIncludedAmount(
transferFeeB,
requiredAmountDelta.tokenB,
);
assert.ok(expectedTransferFeeIncludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeIncludedAmountB.fee.gtn(0));
const preVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const preVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const preOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const preOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: expectedTransferFeeIncludedAmountA.amount,
tokenMaxB: expectedTransferFeeIncludedAmountB.amount,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
),
);
const postVaultBalanceB = new BN(
await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
),
);
const postOwnerAccountBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const postOwnerAccountBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
// owner sent requiredAmountDelta plus transfer fees
assert.ok(
preOwnerAccountBalanceA
.sub(postOwnerAccountBalanceA)
.eq(expectedTransferFeeIncludedAmountA.amount),
);
assert.ok(
preOwnerAccountBalanceB
.sub(postOwnerAccountBalanceB)
.eq(expectedTransferFeeIncludedAmountB.amount),
);
// vault received requiredAmountDelta
assert.ok(
postVaultBalanceA.sub(preVaultBalanceA).eq(requiredAmountDelta.tokenA),
);
assert.ok(
postVaultBalanceB.sub(preVaultBalanceB).eq(requiredAmountDelta.tokenB),
);
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
const aboveLowerIndex = TickUtil.getNextInitializableTickIndex(
currTick + 1,
TickSpacing.Standard,
);
const aboveUpperIndex = tickUpperIndex;
const belowLowerIndex = tickLowerIndex;
const belowUpperIndex = TickUtil.getPrevInitializableTickIndex(
currTick - 1,
TickSpacing.Standard,
);
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 500,
}, // 5%
tokenTraitB: {
isToken2022: true,
hasTransferFeeExtension: true,
hasConfidentialTransferExtension: true,
transferFeeInitialBps: 1000,
}, // 10%
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount },
{
tickLowerIndex: aboveLowerIndex,
tickUpperIndex: aboveUpperIndex,
liquidityAmount,
},
{
tickLowerIndex: belowLowerIndex,
tickUpperIndex: belowUpperIndex,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
});
it("decrease_liquidity_v2: with transfer fee", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
// transfer fee
const transferFeeA = await getTransferFee(poolInitInfo.tokenMintA);
const transferFeeB = await getTransferFee(poolInitInfo.tokenMintB);
assert.equal(transferFeeA.transferFeeBasisPoints, 500); // 5%
assert.equal(transferFeeB.transferFeeBasisPoints, 1000); // 10%
// confidential transfer
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferMintExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
// confidential transfer fee config
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintA,
),
true,
);
assert.equal(
await hasConfidentialTransferFeeConfigExtension(
provider,
poolInitInfo.tokenMintB,
),
true,
);
const position = positions[0];
const positionData = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
const whirlpoolData = (await fetcher.getPool(
positionData.whirlpool,
IGNORE_CACHE,
)) as WhirlpoolData;
const expectedAmount = PoolUtil.getTokenAmountsFromLiquidity(
positionData.liquidity,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(positionData.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(positionData.tickUpperIndex),
false,
);
// transfer fee should be non zero
assert.ok(expectedAmount.tokenA.gtn(0));
assert.ok(expectedAmount.tokenB.gtn(0));
const expectedTransferFeeExcludedAmountA =
calculateTransferFeeExcludedAmount(transferFeeA, expectedAmount.tokenA);
const expectedTransferFeeExcludedAmountB =
calculateTransferFeeExcludedAmount(transferFeeB, expectedAmount.tokenB);
assert.ok(expectedTransferFeeExcludedAmountA.fee.gtn(0));
assert.ok(expectedTransferFeeExcludedAmountB.fee.gtn(0));
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: positionData.liquidity,
tokenMinA: expectedAmount.tokenA.sub(
expectedTransferFeeExcludedAmountA.fee,
),
tokenMinB: expectedAmount.tokenB.sub(
expectedTransferFeeExcludedAmountB.fee,
),
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: position.publicKey,
positionTokenAccount: position.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: position.tickArrayLower,
tickArrayUpper: position.tickArrayUpper,
}),
).buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(
new BN(preVaultBalanceA)
.sub(new BN(postVaultBalanceA))
.eq(expectedAmount.tokenA),
);
assert.ok(
new BN(preVaultBalanceB)
.sub(new BN(postVaultBalanceB))
.eq(expectedAmount.tokenB),
);
// owner received withdrawable amount minus transfer fee (transferFeeExcludedAmount)
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
//console.info("A", destBalanceA.toString(), expectedTransferFeeExcludedAmountA.amount.toString(), expectedTransferFeeExcludedAmountA.fee.toString());
//console.info("B", destBalanceB.toString(), expectedTransferFeeExcludedAmountB.amount.toString(), expectedTransferFeeExcludedAmountB.fee.toString());
assert.ok(
new BN(destBalanceA).eq(expectedTransferFeeExcludedAmountA.amount),
);
assert.ok(
new BN(destBalanceB).eq(expectedTransferFeeExcludedAmountB.amount),
);
// all liquidity have been decreased
const positionDataAfterWithdraw = (await fetcher.getPosition(
position.publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(positionDataAfterWithdraw.liquidity.isZero());
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/interest-bearing.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import type { WhirlpoolData } from "../../../../src";
import {
PDAUtil,
swapQuoteWithParams,
SwapUtils,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
getTokenBalance,
sleep,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
} from "../../../utils/v2/init-utils-v2";
import type { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
import {
amountToUiAmount,
updateRateInterestBearingMint,
} from "@solana/spl-token";
describe("TokenExtension/InterestBearing", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const payer = (ctx.wallet as NodeWallet).payer;
async function rawAmountToUIAmount(
mint: PublicKey,
rawAmount: BN,
): Promise<string> {
const result = await amountToUiAmount(
ctx.connection,
payer,
mint,
rawAmount.toNumber(),
TEST_TOKEN_2022_PROGRAM_ID,
);
if (typeof result === "string") {
return result;
}
throw new Error("Failed to convert raw amount to UI amount");
}
// Since InterestBearing is no different from normal mint as far as handling raw amounts (u64 amounts),
// swap_v2 is executed to check the owner to vault and vault to owner logic.
// |----------|-----*S*T*|****------| (*: liquidity, S: start, T: end)
it("swap_v2 (covers both owner to vault and vault to owner transfer)", async () => {
const { whirlpoolPda, poolInitInfo, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokensV2(
ctx,
{
isToken2022: true,
hasInterestBearingExtension: true,
interestBearingRate: 0,
}, // 0%
{
isToken2022: true,
hasInterestBearingExtension: true,
interestBearingRate: 0,
}, // 0%
TickSpacing.Standard,
);
const initialRawBalanceA = new BN(
await getTokenBalance(provider, tokenAccountA),
);
const initialRawBalanceB = new BN(
await getTokenBalance(provider, tokenAccountB),
);
const initialUIBalanceA = await rawAmountToUIAmount(
poolInitInfo.tokenMintA,
initialRawBalanceA,
);
const initialUIBalanceB = await rawAmountToUIAmount(
poolInitInfo.tokenMintB,
initialRawBalanceB,
);
// rate is 0%, so these values should be equal
assert.ok(
initialRawBalanceA.eq(new BN(Number.parseInt(initialUIBalanceA))),
);
assert.ok(
initialRawBalanceB.eq(new BN(Number.parseInt(initialUIBalanceB))),
);
// set rate > 0%
const sigA = await updateRateInterestBearingMint(
ctx.connection,
payer,
poolInitInfo.tokenMintA,
payer,
30_000, // 300%
);
const sigB = await updateRateInterestBearingMint(
ctx.connection,
payer,
poolInitInfo.tokenMintB,
payer,
10_000, // 100%
);
await Promise.all([
ctx.connection.confirmTransaction(sigA),
ctx.connection.confirmTransaction(sigB),
]);
await sleep(10 * 1000);
const newUIBalanceA = await rawAmountToUIAmount(
poolInitInfo.tokenMintA,
initialRawBalanceA,
);
const newUIBalanceB = await rawAmountToUIAmount(
poolInitInfo.tokenMintB,
initialRawBalanceB,
);
// rate is >0%, so these values should NOT be equal
assert.ok(initialRawBalanceA.lt(new BN(Number.parseInt(newUIBalanceA))));
assert.ok(initialRawBalanceB.lt(new BN(Number.parseInt(newUIBalanceB))));
// now we can assure that InterestBearing works as expected on both tokens
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
await fundPositionsV2(ctx, poolInitInfo, tokenAccountA, tokenAccountB, [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
]);
const oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
// tick: 32190 -> 32269
const quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(200000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(0, 100),
);
assert.ok(quoteBToA.estimatedAmountIn.gtn(0));
assert.ok(quoteBToA.estimatedAmountOut.gtn(0));
const balanceA0 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB0 = new BN(await getTokenBalance(provider, tokenAccountB));
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
}),
).buildAndExecute();
const balanceA1 = new BN(await getTokenBalance(provider, tokenAccountA));
const balanceB1 = new BN(await getTokenBalance(provider, tokenAccountB));
const diffA = balanceA1.sub(balanceA0);
const diffB = balanceB1.sub(balanceB0);
assert.ok(diffA.eq(quoteBToA.estimatedAmountOut));
assert.ok(diffB.eq(quoteBToA.estimatedAmountIn.neg()));
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-extensions/transfer-hook.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import type {
DecreaseLiquidityQuote,
InitPoolV2Params,
PositionData,
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolData,
} from "../../../../src";
import {
buildWhirlpoolClient,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
MEMO_PROGRAM_ADDRESS,
NUM_REWARDS,
PDAUtil,
PoolUtil,
PriceMath,
swapQuoteWithParams,
SwapUtils,
toTokenAmount,
toTx,
twoHopSwapQuoteFromSwapQuotes,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { getTokenBalance, sleep, TickSpacing, ZERO_BN } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
import type { FundedPositionV2Params } from "../../../utils/v2/init-utils-v2";
import {
fundPositionsV2,
initTestPoolWithTokensV2,
useMaxCU,
} from "../../../utils/v2/init-utils-v2";
import { createTokenAccountV2 } from "../../../utils/v2/token-2022";
import type { AccountMeta } from "@solana/web3.js";
import { PublicKey } from "@solana/web3.js";
import { initTickArrayRange } from "../../../utils/init-utils";
import type { InitAquariumV2Params } from "../../../utils/v2/aquarium-v2";
import {
buildTestAquariumsV2,
getDefaultAquariumV2,
getTokenAccsForPoolsV2,
} from "../../../utils/v2/aquarium-v2";
import {
getExtraAccountMetasForTestTransferHookProgram,
getTestTransferHookCounter,
updateTransferHookProgram,
} from "../../../utils/v2/test-transfer-hook-program";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
} from "../../../../src/utils/remaining-accounts-util";
describe("TokenExtension/TransferHook", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
describe("collect_fees_v2, collect_protocol_fees_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let feeAccountA: PublicKey;
let feeAccountB: PublicKey;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// TransferHook
const tokenTransferHookAccountsAForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
tokenMintA,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
const tokenTransferHookAccountsBForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintB,
tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
);
const tokenTransferHookAccountsAForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintA,
tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
);
const tokenTransferHookAccountsBForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
tokenMintB,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: tickArrayPda.publicKey,
tickArrayUpper: tickArrayPda.publicKey,
}),
).buildAndExecute();
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
))!;
assert.ok(!whirlpoolData.protocolFeeOwedA.isZero());
assert.ok(!whirlpoolData.protocolFeeOwedB.isZero());
const positionBeforeCollect = (await fetcher.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
)) as PositionData;
assert.ok(!positionBeforeCollect.feeOwedA.isZero());
assert.ok(!positionBeforeCollect.feeOwedB.isZero());
feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintA,
provider.wallet.publicKey,
);
feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
tokenMintB,
provider.wallet.publicKey,
);
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintA,
tokenVaultAKeypair.publicKey,
feeAccountA,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
tokenMintB,
tokenVaultBKeypair.publicKey,
feeAccountB,
whirlpoolPda.publicKey,
);
});
it("collect_fees_v2: with transfer hook", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("collect_fees_v2: without transfer hook (has extension, but set null)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await updateTransferHookProgram(provider, tokenMintA, PublicKey.default);
await updateTransferHookProgram(provider, tokenMintB, PublicKey.default);
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: undefined, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA);
assert.equal(postCounterB, preCounterB);
});
it("collect_fees_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_fees_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(counter)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// counter account is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(account_order_verifier)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// account_order_verifier account is missing
const insufficientTransferHookAccountsA = [
// counter_account
...tokenTransferHookAccountsA!.slice(0, 1),
// skip account_order_verifier
// extra account metas, hook program
...tokenTransferHookAccountsA!.slice(2),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(ExtraAccountMetas)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// ExtraAccountMetas is missing
const insufficientTransferHookAccountsA = [
// counter_account, account_order_verifier
...tokenTransferHookAccountsA!.slice(0, 2),
// skip extra account metas
// hook program
...tokenTransferHookAccountsA!.slice(3),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("collect_fees_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(HookProgram)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
// HookProgram is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(0, 3);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("collect_fees_v2: [Fail] with TransferHookReward", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// invalid accounts type
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccountsA,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a0/, // RemainingAccountsInvalidSlice
);
});
it("collect_fees_v2: [Fail] with insufficient remaining accounts", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
.build();
const missingRemainingAccounts = remainingAccounts!.slice(
0,
remainingAccounts!.length - 1,
); // drop last 1 accounts
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: missingRemainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a1/, // RemainingAccountsInsufficient
);
});
it("collect_fees_v2: [Fail] with duplicated remaining accounts (TransferHookA)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("collect_fees_v2: [Fail] with duplicated remaining accounts (TransferHookB)", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
positions,
} = fixture.getInfos();
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookA,
tokenTransferHookAccountsA,
)
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookB,
tokenTransferHookAccountsB,
)
.build();
const ix = ctx.program.instruction.collectFeesV2(remainingAccountsInfo, {
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
});
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("collect_protocol_fees_v2: with transfer hook", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute();
const feeBalanceA = await getTokenBalance(provider, feeAccountA);
const feeBalanceB = await getTokenBalance(provider, feeAccountB);
assert.ok(new BN(feeBalanceA).gtn(0));
assert.ok(new BN(feeBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("collect_protocol_fees_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("collect_protocol_fees_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
configKeypairs: { collectProtocolFeesAuthorityKeypair },
configInitInfo: { whirlpoolsConfigKeypair: whirlpoolsConfigKeypair },
} = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectProtocolFeesV2Ix(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpool: whirlpoolPda.publicKey,
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.addSigner(collectProtocolFeesAuthorityKeypair)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("collect_reward_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let rewardAccounts: PublicKey[];
let tokenTransferHookAccounts: (AccountMeta[] | undefined)[];
beforeEach(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
// accrue rewards
await sleep(3000);
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position: positions[0].publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
// Generate collect reward expectation
const whirlpoolData = (await fetcher.getPool(
whirlpoolPda.publicKey,
)) as WhirlpoolData;
const positionPreCollect = await client.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
// Lock the collectRewards quote to the last time we called updateFeesAndRewards
const expectation = collectRewardsQuote({
whirlpool: whirlpoolData,
position: positionPreCollect.getData(),
tickLower: positionPreCollect.getLowerTickData(),
tickUpper: positionPreCollect.getUpperTickData(),
timeStampInSeconds: whirlpoolData.rewardLastUpdatedTimestamp,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!expectation.rewardOwed[i]!.isZero());
}
rewardAccounts = await Promise.all(
rewards.map((reward) => {
return createTokenAccountV2(
provider,
{ isToken2022: true },
reward.rewardMint,
provider.wallet.publicKey,
);
}),
);
tokenTransferHookAccounts = await Promise.all(
rewards.map((reward, i) => {
return getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
reward.rewardMint,
reward.rewardVaultKeypair.publicKey,
rewardAccounts[i],
whirlpoolPda.publicKey,
);
}),
);
});
it("collect_reward_v2: with transfer hook", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const preCounter = await getTestTransferHookCounter(
provider,
rewards[i].rewardMint,
);
await toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
rewardTransferHookAccounts: tokenTransferHookAccounts[i], // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const rewardBalance = await getTokenBalance(
provider,
rewardAccounts[i],
);
assert.ok(new BN(rewardBalance).gtn(0));
const postCounter = await getTestTransferHookCounter(
provider,
rewards[i].rewardMint,
);
assert.equal(postCounter, preCounter + 1);
}
});
it("collect_reward_v2: [Fail] with transfer hook, but no extra accounts provided for rewardToken", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
await getTestTransferHookCounter(provider, rewards[i].rewardMint);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardIndex: i,
rewardTransferHookAccounts: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
}
});
it("collect_reward_v2: [Fail] with duplicated remaining accounts (TransferHookReward)", async () => {
const {
poolInitInfo: { whirlpoolPda },
positions,
rewards,
} = fixture.getInfos();
for (let i = 0; i < NUM_REWARDS; i++) {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccounts[i],
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookReward,
tokenTransferHookAccounts[i],
)
.build();
const ix = ctx.program.instruction.collectRewardV2(
i,
remainingAccountsInfo,
{
accounts: {
whirlpool: whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
rewardMint: rewards[i].rewardMint,
rewardTokenProgram: rewards[i].tokenProgram,
rewardOwnerAccount: rewardAccounts[i],
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
}
});
});
describe("increase_liquidity_v2", () => {
const tickLowerIndex = 7168;
const tickUpperIndex = 8960;
const currTick = Math.round((tickLowerIndex + tickUpperIndex) / 2);
let fixture: WhirlpoolTestFixtureV2;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing: TickSpacing.Standard,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount: ZERO_BN },
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currTick),
});
const { poolInitInfo } = fixture.getInfos();
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintA,
fixture.getInfos().tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintB,
fixture.getInfos().tokenAccountB,
poolInitInfo.tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
});
it("increase_liquidity_v2: with transfer hook", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("increase_liquidity_v2: without transfer hook (has extension, but set null)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
const preVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const preVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
await updateTransferHookProgram(
provider,
poolInitInfo.tokenMintA,
PublicKey.default,
);
await updateTransferHookProgram(
provider,
poolInitInfo.tokenMintB,
PublicKey.default,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postVaultBalanceA = await getTokenBalance(
provider,
poolInitInfo.tokenVaultAKeypair.publicKey,
);
const postVaultBalanceB = await getTokenBalance(
provider,
poolInitInfo.tokenVaultBKeypair.publicKey,
);
assert.ok(new BN(postVaultBalanceA).gt(new BN(preVaultBalanceA)));
assert.ok(new BN(postVaultBalanceB).gt(new BN(preVaultBalanceB)));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA);
assert.equal(postCounterB, preCounterB);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(counter)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// counter account is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(1);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(account_order_verifier)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// account_order_verifier account is missing
const insufficientTransferHookAccountsA = [
// counter_account
...tokenTransferHookAccountsA!.slice(0, 1),
// skip account_order_verifier
// extra account metas, hook program
...tokenTransferHookAccountsA!.slice(2),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on tlv-account-resolution
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/libraries/tlv-account-resolution/src/error.rs#L6
/0xa261c2c0/, // IncorrectAccount (2724315840)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(ExtraAccountMetas)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// ExtraAccountMetas is missing
const insufficientTransferHookAccountsA = [
// counter_account, account_order_verifier
...tokenTransferHookAccountsA!.slice(0, 2),
// skip extra account metas
// hook program
...tokenTransferHookAccountsA!.slice(3),
];
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
it("increase_liquidity_v2: [Fail] with transfer hook, but extra accounts provided for A is insufficient(HookProgram)", async () => {
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const positionInitInfo = positions[0];
const tokenAmount = toTokenAmount(1_000_000, 1_000_000);
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currTick,
tickLowerIndex,
tickUpperIndex,
tokenAmount,
);
// HookProgram is missing
const insufficientTransferHookAccountsA =
tokenTransferHookAccountsA!.slice(0, 3);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount,
tokenMaxA: tokenAmount.tokenA,
tokenMaxB: tokenAmount.tokenB,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positionInitInfo.publicKey,
positionTokenAccount: positionInitInfo.tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positionInitInfo.tickArrayLower,
tickArrayUpper: positionInitInfo.tickArrayUpper,
tokenTransferHookAccountsA: insufficientTransferHookAccountsA,
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
// Errors on transfer-hook-interface
// https://github.com/solana-labs/solana-program-library/blob/dbf609206a60ed5698644f4840ddbd117d2c83d8/token/transfer-hook/interface/src/error.rs#L6
/0x7dc8348c/, // IncorrectAccount (2110272652)
);
});
});
describe("decrease_liquidity_v2", () => {
let fixture: WhirlpoolTestFixtureV2;
let removalQuote: DecreaseLiquidityQuote;
let destAccountA: PublicKey;
let destAccountB: PublicKey;
let tokenTransferHookAccountsA: AccountMeta[] | undefined;
let tokenTransferHookAccountsB: AccountMeta[] | undefined;
beforeEach(async () => {
const liquidityAmount = new anchor.BN(1_250_000);
const tickLower = 7168,
tickUpper = 8960;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing: TickSpacing.Standard,
initialSqrtPrice: MathUtil.toX64(new Decimal(1.48)),
positions: [
{
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
liquidityAmount,
},
],
});
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const poolBefore = (await fetcher.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
removalQuote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(1_000_000),
sqrtPrice: poolBefore.sqrtPrice,
slippageTolerance: Percentage.fromFraction(1, 100),
tickCurrentIndex: poolBefore.tickCurrentIndex,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolBefore,
IGNORE_CACHE,
),
});
assert.ok(!removalQuote.tokenEstA.isZero());
assert.ok(!removalQuote.tokenEstB.isZero());
destAccountA = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintA,
provider.wallet.publicKey,
);
destAccountB = await createTokenAccountV2(
provider,
{ isToken2022: true },
poolInitInfo.tokenMintB,
provider.wallet.publicKey,
);
// TransferHook
tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintA,
poolInitInfo.tokenVaultAKeypair.publicKey,
destAccountA,
poolInitInfo.whirlpoolPda.publicKey,
);
tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
destAccountB,
poolInitInfo.whirlpoolPda.publicKey,
);
});
it("decrease_liquidity_v2: with transfer hook", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const destBalanceA = await getTokenBalance(provider, destAccountA);
const destBalanceB = await getTokenBalance(provider, destAccountB);
assert.ok(new BN(destBalanceA).gtn(0));
assert.ok(new BN(destBalanceB).gtn(0));
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("decrease_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for A", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("decrease_liquidity_v2: [Fail] with transfer hook, but no extra accounts provided for B", async () => {
const { poolInitInfo, positions } = fixture.getInfos();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
...removalQuote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
positionAuthority: provider.wallet.publicKey,
position: positions[0].publicKey,
positionTokenAccount: positions[0].tokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: destAccountA,
tokenOwnerAccountB: destAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArrayLower: positions[0].tickArrayLower,
tickArrayUpper: positions[0].tickArrayUpper,
tokenTransferHookAccountsA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("swap_v2", () => {
let poolInitInfo: InitPoolV2Params;
let whirlpoolPda: PDA;
let tokenAccountA: PublicKey;
let tokenAccountB: PublicKey;
let oraclePubkey: PublicKey;
let quoteAToB: SwapQuote;
let quoteBToA: SwapQuote;
let tokenTransferHookAccountsAForAToB: AccountMeta[] | undefined;
let tokenTransferHookAccountsBForAToB: AccountMeta[] | undefined;
let tokenTransferHookAccountsAForBToA: AccountMeta[] | undefined;
let tokenTransferHookAccountsBForBToA: AccountMeta[] | undefined;
beforeEach(async () => {
const init = await initTestPoolWithTokensV2(
ctx,
{ isToken2022: true, hasTransferHookExtension: true },
{ isToken2022: true, hasTransferHookExtension: true },
TickSpacing.Standard,
);
poolInitInfo = init.poolInitInfo;
whirlpoolPda = init.whirlpoolPda;
tokenAccountA = init.tokenAccountA;
tokenAccountB = init.tokenAccountB;
const aToB = false;
await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
aToB,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
oraclePubkey = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
).publicKey;
const whirlpoolKey = poolInitInfo.whirlpoolPda.publicKey;
const whirlpoolData = (await fetcher.getPool(
whirlpoolKey,
IGNORE_CACHE,
)) as WhirlpoolData;
quoteAToB = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: true,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(true),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
true,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
quoteBToA = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: false,
tokenAmount: new BN(100000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(false),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
false,
ctx.program.programId,
whirlpoolKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(100, 100), // 100% slippage
);
// TransferHook
tokenTransferHookAccountsAForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintA,
tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
tokenTransferHookAccountsBForAToB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsAForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// vault to owner
poolInitInfo.tokenMintA,
poolInitInfo.tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
);
tokenTransferHookAccountsBForBToA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// owner to vault
poolInitInfo.tokenMintB,
tokenAccountB,
poolInitInfo.tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
);
});
it("swap_v2: with transfer hook, a to b", async () => {
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("swap_v2: with transfer hook, b to a", async () => {
const preCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const preCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
const postCounterA = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintA,
);
const postCounterB = await getTestTransferHookCounter(
provider,
poolInitInfo.tokenMintB,
);
assert.equal(postCounterA, preCounterA + 1);
assert.equal(postCounterB, preCounterB + 1);
});
it("swap_v2: [Fail] with transfer hook, a to b, but no extra accounts provided for A", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB: tokenTransferHookAccountsBForAToB, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, a to b, but no extra accounts provided for B", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteAToB,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForAToB, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, b to a, but no extra accounts provided for A", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: undefined, // TransferHook (not provided)
tokenTransferHookAccountsB: tokenTransferHookAccountsBForBToA, // TransferHook
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("swap_v2: [Fail] with transfer hook, b to a, but no extra accounts provided for B", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quoteBToA,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: oraclePubkey,
tokenTransferHookAccountsA: tokenTransferHookAccountsAForBToA, // TransferHook
tokenTransferHookAccountsB: undefined, // TransferHook (not provided)
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
});
describe("two_hop_swap", () => {
let aqConfig: InitAquariumV2Params;
let baseIxParams: TwoHopSwapV2Params;
let tokenMintIn: PublicKey;
let tokenMintOut: PublicKey;
let tokenMintMid: PublicKey;
let tokenTransferHookAccountsInput: AccountMeta[] | undefined;
let tokenTransferHookAccountsMid: AccountMeta[] | undefined;
let tokenTransferHookAccountsOutput: AccountMeta[] | undefined;
beforeEach(async () => {
aqConfig = getDefaultAquariumV2();
// Add a third token and account and a second pool
aqConfig.initMintParams = [
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
{ tokenTrait: { isToken2022: true, hasTransferHookExtension: true } },
];
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams.push({
mintIndices: [1, 2],
tickSpacing: TickSpacing.Standard,
});
// Add tick arrays and positions
const aToB = false;
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 22528,
arrayCount: 3,
aToB,
});
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: 29440,
tickUpperIndex: 33536,
},
];
aqConfig.initPositionParams.push({ poolIndex: 0, fundParams });
aqConfig.initPositionParams.push({ poolIndex: 1, fundParams });
const aquarium = (await buildTestAquariumsV2(ctx, [aqConfig]))[0];
const { tokenAccounts, mintKeys, pools } = aquarium;
const whirlpoolOneKey = pools[0].whirlpoolPda.publicKey;
const whirlpoolTwoKey = pools[1].whirlpoolPda.publicKey;
const whirlpoolDataOne = (await fetcher.getPool(
whirlpoolOneKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const whirlpoolDataTwo = (await fetcher.getPool(
whirlpoolTwoKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const [inputToken, intermediaryToken, _outputToken] = mintKeys;
const aToBOne = whirlpoolDataOne.tokenMintA.equals(inputToken);
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBOne,
tokenAmount: new BN(1000),
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBOne),
whirlpoolData: whirlpoolDataOne,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataOne.tickCurrentIndex,
whirlpoolDataOne.tickSpacing,
aToBOne,
ctx.program.programId,
whirlpoolOneKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataOne,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const aToBTwo = whirlpoolDataTwo.tokenMintA.equals(intermediaryToken);
const quote2 = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB: aToBTwo,
tokenAmount: quote.estimatedAmountOut,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToBTwo),
whirlpoolData: whirlpoolDataTwo,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolDataTwo.tickCurrentIndex,
whirlpoolDataTwo.tickSpacing,
aToBTwo,
ctx.program.programId,
whirlpoolTwoKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolDataTwo,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
const tokenAccKeys = getTokenAccsForPoolsV2(pools, tokenAccounts);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote, quote2);
baseIxParams = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pools[0].whirlpoolPda.publicKey,
whirlpoolTwo: pools[1].whirlpoolPda.publicKey,
tokenMintInput: twoHopQuote.aToBOne
? pools[0].tokenMintA
: pools[0].tokenMintB,
tokenMintIntermediate: twoHopQuote.aToBOne
? pools[0].tokenMintB
: pools[0].tokenMintA,
tokenMintOutput: twoHopQuote.aToBTwo
? pools[1].tokenMintB
: pools[1].tokenMintA,
tokenProgramInput: twoHopQuote.aToBOne
? pools[0].tokenProgramA
: pools[0].tokenProgramB,
tokenProgramIntermediate: twoHopQuote.aToBOne
? pools[0].tokenProgramB
: pools[0].tokenProgramA,
tokenProgramOutput: twoHopQuote.aToBTwo
? pools[1].tokenProgramB
: pools[1].tokenProgramA,
tokenOwnerAccountInput: twoHopQuote.aToBOne
? tokenAccKeys[0]
: tokenAccKeys[1],
tokenOwnerAccountOutput: twoHopQuote.aToBTwo
? tokenAccKeys[3]
: tokenAccKeys[2],
tokenVaultOneInput: twoHopQuote.aToBOne
? pools[0].tokenVaultAKeypair.publicKey
: pools[0].tokenVaultBKeypair.publicKey,
tokenVaultOneIntermediate: twoHopQuote.aToBOne
? pools[0].tokenVaultBKeypair.publicKey
: pools[0].tokenVaultAKeypair.publicKey,
tokenVaultTwoIntermediate: twoHopQuote.aToBTwo
? pools[1].tokenVaultAKeypair.publicKey
: pools[1].tokenVaultBKeypair.publicKey,
tokenVaultTwoOutput: twoHopQuote.aToBTwo
? pools[1].tokenVaultBKeypair.publicKey
: pools[1].tokenVaultAKeypair.publicKey,
oracleOne: PDAUtil.getOracle(
ctx.program.programId,
pools[0].whirlpoolPda.publicKey,
).publicKey,
oracleTwo: PDAUtil.getOracle(
ctx.program.programId,
pools[1].whirlpoolPda.publicKey,
).publicKey,
};
// TransferHook
tokenMintIn = baseIxParams.tokenMintInput;
tokenMintOut = baseIxParams.tokenMintOutput;
tokenMintMid = baseIxParams.tokenMintIntermediate;
tokenTransferHookAccountsInput =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// input: owner to vault
baseIxParams.tokenMintInput,
baseIxParams.tokenOwnerAccountInput,
baseIxParams.tokenVaultOneInput,
baseIxParams.tokenAuthority,
);
tokenTransferHookAccountsMid =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// intermediate: vault to vault (vault to owner logic is used)
baseIxParams.tokenMintIntermediate,
baseIxParams.tokenVaultOneIntermediate,
baseIxParams.tokenVaultTwoIntermediate,
baseIxParams.whirlpoolOne,
);
tokenTransferHookAccountsOutput =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// output: vault to owner
baseIxParams.tokenMintOutput,
baseIxParams.tokenVaultTwoOutput,
baseIxParams.tokenOwnerAccountOutput,
baseIxParams.whirlpoolTwo,
);
});
it("two_hop_swap_v2: with transfer hook", async () => {
const preCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const preCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const preCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
const tx = toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput,
}),
);
// add Compute units (because it calls 3 external hooks)
tx.prependInstruction(useMaxCU());
await tx.buildAndExecute();
const postCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const postCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const postCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
assert.equal(postCounterIn, preCounterIn + 1);
assert.equal(postCounterOut, preCounterOut + 1);
assert.equal(
postCounterMid,
preCounterMid + 1 /* must be 1 (vault to vault) */,
);
});
it("two_hop_swap_v2: without transfer hook (has extension, but set null)", async () => {
const preCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const preCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const preCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
await updateTransferHookProgram(provider, tokenMintIn, PublicKey.default);
await updateTransferHookProgram(
provider,
tokenMintOut,
PublicKey.default,
);
await updateTransferHookProgram(
provider,
tokenMintMid,
PublicKey.default,
);
const tx = toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput: undefined,
tokenTransferHookAccountsIntermediate: undefined,
tokenTransferHookAccountsOutput: undefined,
}),
);
// add Compute units (because it calls 3 external hooks)
tx.prependInstruction(useMaxCU());
await tx.buildAndExecute();
const postCounterIn = await getTestTransferHookCounter(
provider,
tokenMintIn,
);
const postCounterOut = await getTestTransferHookCounter(
provider,
tokenMintOut,
);
const postCounterMid = await getTestTransferHookCounter(
provider,
tokenMintMid,
);
assert.equal(postCounterIn, preCounterIn);
assert.equal(postCounterOut, preCounterOut);
assert.equal(postCounterMid, preCounterMid);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenInput", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput: undefined,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenIntermediate", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: undefined,
tokenTransferHookAccountsOutput,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with transfer hook, but no extra accounts provided for tokenOutput", async () => {
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.twoHopSwapV2Ix(ctx.program, {
...baseIxParams,
// TransferHook
tokenTransferHookAccountsInput,
tokenTransferHookAccountsIntermediate: tokenTransferHookAccountsMid,
tokenTransferHookAccountsOutput: undefined,
}),
// add Compute units (because it calls 4 external hooks)
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a2/, // NoExtraAccountsForTransferHook
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookInput)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookIntermediate)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
it("two_hop_swap_v2: [Fail] with duplicated remaining accounts (TransferHookOutput)", async () => {
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.TransferHookInput,
tokenTransferHookAccountsInput,
)
.addSlice(
RemainingAccountsType.TransferHookIntermediate,
tokenTransferHookAccountsMid,
)
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
// duplicated
.addSlice(
RemainingAccountsType.TransferHookOutput,
tokenTransferHookAccountsOutput,
)
.build();
const ix = ctx.program.instruction.twoHopSwapV2(
baseIxParams.amount,
baseIxParams.otherAmountThreshold,
baseIxParams.amountSpecifiedIsInput,
baseIxParams.aToBOne,
baseIxParams.aToBTwo,
baseIxParams.sqrtPriceLimitOne,
baseIxParams.sqrtPriceLimitTwo,
remainingAccountsInfo,
{
accounts: {
...baseIxParams,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
await assert.rejects(
toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [],
})
.prependInstruction(useMaxCU())
.buildAndExecute(),
/0x17a5/, // RemainingAccountsDuplicatedAccountsType
);
});
});
describe("Special Errors", () => {
describe("TransferHook program rejects transfer", () => {
const TOO_LARGE_THRESHOLD_U64 = new BN(1_000_000_000_000);
// We know that all transfers are executed 2 functions depending on the direction, so 2 test cases.
it("[FAIL] owner to vault, amount too large", async () => {
// tokenA has transfer hook (so increase liquidity with large tokenB amount will not fail)
const mintAmount = TOO_LARGE_THRESHOLD_U64.muln(2);
const tickSpacing = 1;
const rangeLowerTickIndex = -1;
const rangeUpperTickIndex = +1;
const currentTickIndex = +2;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex, // price is above range ([-1, +1] p)
rangeLowerTickIndex,
rangeUpperTickIndex,
{
tokenA: mintAmount,
tokenB: mintAmount,
},
);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
// tokenA has transfer hook
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: false },
tickSpacing,
positions: [
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const inputTokenAmount = TOO_LARGE_THRESHOLD_U64.addn(1); // exceed threshold by 1
const whirlpoolData = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB,
tokenAmount: inputTokenAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
assert.ok(quote.estimatedAmountIn.gt(TOO_LARGE_THRESHOLD_U64));
// TransferHook
const tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// a to b, owner to vault (input token is tokenA)
poolInitInfo.tokenMintA,
tokenAccountA,
poolInitInfo.tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
);
const tokenTransferHookAccountsB = undefined;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
).publicKey,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
(err) => {
// error code is 0x1770 from transfer hook program and it is ambiguous, so use message string
return JSON.stringify(err).includes("AmountTooBig");
},
);
});
it("[FAIL] vault to owner, amount too large", async () => {
// all tokenB is deposited into [-1, +1] (one side)
const mintAmount = TOO_LARGE_THRESHOLD_U64.muln(2);
const tickSpacing = 1;
const rangeLowerTickIndex = -1;
const rangeUpperTickIndex = +1;
const currentTickIndex = +2;
const liquidityAmount = PoolUtil.estimateLiquidityFromTokenAmounts(
currentTickIndex, // price is above range ([-1, +1] p)
rangeLowerTickIndex,
rangeUpperTickIndex,
{
tokenA: TOO_LARGE_THRESHOLD_U64.muln(3).divn(4), // 3/4 of threshold
tokenB: TOO_LARGE_THRESHOLD_U64.muln(3).divn(4), // 3/4 of threshold
},
);
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
// tokenB has transfer hook
tokenTraitA: { isToken2022: true, hasTransferHookExtension: false },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing,
positions: [
// to avoid large amount increase liquidity, 2 3/4 deposit will be made.
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
{
tickLowerIndex: rangeLowerTickIndex,
tickUpperIndex: rangeUpperTickIndex,
liquidityAmount: liquidityAmount,
},
],
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currentTickIndex),
mintAmount,
});
const { poolInitInfo, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const inputTokenAmount = TOO_LARGE_THRESHOLD_U64.muln(130).divn(100); // 130% of threshold
const whirlpoolData = (await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
)) as WhirlpoolData;
const aToB = true;
const quote = swapQuoteWithParams(
{
amountSpecifiedIsInput: true,
aToB,
tokenAmount: inputTokenAmount,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
whirlpoolData,
tickArrays: await SwapUtils.getTickArrays(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
fetcher,
IGNORE_CACHE,
),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
),
},
Percentage.fromFraction(1, 100),
);
assert.ok(quote.estimatedAmountOut.gt(TOO_LARGE_THRESHOLD_U64));
// TransferHook
const tokenTransferHookAccountsA = undefined;
const tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
provider,
// a to b, vault to owner (output token is tokenB)
poolInitInfo.tokenMintB,
poolInitInfo.tokenVaultBKeypair.publicKey,
tokenAccountB,
poolInitInfo.whirlpoolPda.publicKey,
);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
...quote,
whirlpool: poolInitInfo.whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
oracle: PDAUtil.getOracle(
ctx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
).publicKey,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute(),
(err) => {
// error code is 0x1770 from transfer hook program and it is ambiguous, so use message string
return JSON.stringify(err).includes("AmountTooBig");
},
);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/initialize_config_extension.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import { PDAUtil, toTx, WhirlpoolContext, WhirlpoolIx } from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitConfigExtensionParams } from "../../../../src/instructions";
describe("initialize_config_extension", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
async function createOtherWallet(): Promise<Keypair> {
const keypair = Keypair.generate();
const signature = await provider.connection.requestAirdrop(
keypair.publicKey,
100 * LAMPORTS_PER_SOL,
);
await provider.connection.confirmTransaction(signature, "confirmed");
return keypair;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(
config: PublicKey,
overwrite: Partial<InitConfigExtensionParams>,
signers: Keypair[] = [feeAuthorityKeypair],
) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
const tx = toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
it("successfully initialize config extension and verify initialized account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
const configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(
configExtension!.configExtensionAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
assert.ok(
configExtension!.tokenBadgeAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
});
it("successfully initialize when funder is different than account paying for transaction fee", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const otherWallet = await createOtherWallet();
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{
funder: otherWallet.publicKey,
},
[feeAuthorityKeypair, otherWallet],
);
const postBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const diffBalance = preBalance - postBalance;
const minRent = await ctx.connection.getMinimumBalanceForRentExemption(0);
assert.ok(diffBalance < minRent); // ctx.wallet didn't pay any rent
const configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(
configExtension!.configExtensionAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
assert.ok(
configExtension!.tokenBadgeAuthority.equals(
feeAuthorityKeypair.publicKey,
),
);
});
it("WhirlpoolsConfigExtension account has reserved space", async () => {
const whirlpoolsConfigExtensionAccountSizeIncludingReserve =
8 + 32 + 32 + 32 + 512;
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
const account = await ctx.connection.getAccountInfo(
configExtensionPubkey,
"confirmed",
);
assert.equal(
account!.data.length,
whirlpoolsConfigExtensionAccountSizeIncludingReserve,
);
});
it("should be failed: already initialized", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const configExtensionPubkey = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
);
// initialized
const configExtension = await fetcher.getConfigExtension(
configExtensionPubkey,
);
assert.ok(
configExtension!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
// re-initialize
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
),
(err) => {
return JSON.stringify(err).includes("already in use");
},
);
});
describe("invalid input account", () => {
it("should be failed: invalid config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
// config not initialized
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{},
),
/0xbc4/, // AccountNotInitialized
);
});
it("should be failed: invalid config_extension address", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidPda = PDAUtil.getFeeTier(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
64,
);
await assert.rejects(
initializeWhirlpoolsConfigExtension(whirlpoolsConfigKeypair.publicKey, {
whirlpoolsConfigExtensionPda: invalidPda,
}),
/0x7d6/, // ConstraintSeeds
);
});
it("should be failed: funder is not signer", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const whirlpoolsConfigExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
);
const ix: TransactionInstruction =
program.instruction.initializeConfigExtension({
accounts: {
config: whirlpoolsConfigKeypair.publicKey,
configExtension: whirlpoolsConfigExtensionPda.publicKey,
funder: otherWallet.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 5);
assert.ok(ix.keys[2].pubkey.equals(otherWallet.publicKey));
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [feeAuthorityKeypair], // no otherWallet
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid fee_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidAuthorityKeypair = Keypair.generate();
await assert.rejects(
initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
{
feeAuthority: invalidAuthorityKeypair.publicKey,
},
[invalidAuthorityKeypair],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: invalid system program", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const invalidSystemProgram = TOKEN_PROGRAM_ID;
const whirlpoolsConfigExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
);
const ix: TransactionInstruction =
program.instruction.initializeConfigExtension({
accounts: {
config: whirlpoolsConfigKeypair.publicKey,
configExtension: whirlpoolsConfigExtensionPda.publicKey,
funder: ctx.wallet.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
systemProgram: invalidSystemProgram,
},
});
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [feeAuthorityKeypair],
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/set_config_extension_authority.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
describe("set_config_extension_authority", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedConfigExtensionAuthorityKeypair = Keypair.generate();
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function setConfigExtensionAuthority(
config: PublicKey,
configExtensionAuthority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: configExtensionAuthority.publicKey,
newConfigExtensionAuthority: newAuthority,
}),
)
.addSigner(configExtensionAuthority)
.buildAndExecute();
}
it("successfully set config extension authority and verify updated account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.configExtensionAuthority.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialConfigExtensionAuthorityKeypair.publicKey.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedConfigExtensionAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.configExtensionAuthority.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
// set back to initialConfigExtension with updateConfigExtensionAuthority
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
updatedConfigExtensionAuthorityKeypair,
initialConfigExtensionAuthorityKeypair.publicKey,
);
const backExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
backExtensionData!.configExtensionAuthority.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
// config_extension not initialized
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
const anotherWhirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension: anotherWhirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(initialConfigExtensionAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const fakeAuthority = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setConfigExtensionAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority: fakeAuthority.publicKey,
newConfigExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
}),
)
.addSigner(fakeAuthority)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await setConfigExtensionAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedConfigExtensionAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.configExtensionAuthority.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.setConfigExtensionAuthority({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
updatedConfigExtensionAuthorityKeypair.publicKey,
newConfigExtensionAuthority: Keypair.generate().publicKey,
},
});
assert.equal(ix.keys.length, 4);
assert.ok(
ix.keys[2].pubkey.equals(
updatedConfigExtensionAuthorityKeypair.publicKey,
),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedConfigExtensionAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/initialize_token_badge.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitializeTokenBadgeParams } from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
import type { TokenTrait } from "../../../utils/v2/init-utils-v2";
describe("initialize_token_badge", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
async function createOtherWallet(): Promise<Keypair> {
const keypair = Keypair.generate();
const signature = await provider.connection.requestAirdrop(
keypair.publicKey,
100 * LAMPORTS_PER_SOL,
);
await provider.connection.confirmTransaction(signature, "confirmed");
return keypair;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function updateTokenBadgeAuthority(
config: PublicKey,
authority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: authority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(authority)
.buildAndExecute();
}
describe("successfully initialize token badge and verify initialized account contents", () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
];
tokenTraits.forEach((tokenTrait) => {
it(`Mint TokenProgram: ${tokenTrait.isToken2022 ? "Token-2022" : "Token"}`, async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, tokenTrait);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
});
});
it("successfully initialize when funder is different than account paying for transaction fee", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
const preBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const otherWallet = await createOtherWallet();
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
funder: otherWallet.publicKey,
},
[initialTokenBadgeAuthorityKeypair, otherWallet],
);
const postBalance = await ctx.connection.getBalance(ctx.wallet.publicKey);
const diffBalance = preBalance - postBalance;
const minRent = await ctx.connection.getMinimumBalanceForRentExemption(0);
assert.ok(diffBalance < minRent); // ctx.wallet didn't pay any rent
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
it("TokenBadge account has reserved space", async () => {
const tokenBadgeAccountSizeIncludingReserve = 8 + 32 + 32 + 128;
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const account = await ctx.connection.getAccountInfo(
tokenBadgePda.publicKey,
"confirmed",
);
assert.equal(account!.data.length, tokenBadgeAccountSizeIncludingReserve);
});
it("should be failed: already initialized", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
// initialized
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeData !== null);
// re-initialize
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {}),
(err) => {
return JSON.stringify(err).includes("already in use");
},
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
// with fake PDA
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
tokenBadgePda: PDAUtil.getTokenBadge(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
mint,
),
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
// config_extension not initialized
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const fakeAuthority = Keypair.generate();
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: ctx.wallet.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 7);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: config_extension_authority is passed as token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const fakeAuthority = initialConfigExtensionAuthorityKeypair;
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: invalid token_mint", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
// mint is not uninitialized
const uninitializedMint = Keypair.generate().publicKey;
await assert.rejects(
initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
uninitializedMint,
{},
),
/0xbc4/, // AccountNotInitialized
);
// different mint
const mintA = await createMintV2(provider, { isToken2022: true });
const mintB = await createMintV2(provider, { isToken2022: true });
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mintA, {
tokenMint: mintB,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: invalid token_badge", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
// different mint
const mintA = await createMintV2(provider, { isToken2022: true });
const mintB = await createMintV2(provider, { isToken2022: true });
const pdaForMintB = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mintB,
);
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mintA, {
tokenBadgePda: pdaForMintB,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: funder is not signer", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: otherWallet.publicKey,
systemProgram: SystemProgram.programId,
},
});
assert.equal(ix.keys.length, 7);
assert.ok(ix.keys[5].pubkey.equals(otherWallet.publicKey));
// unset signer flag
ix.keys[5].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [initialTokenBadgeAuthorityKeypair], // no otherWallet
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid system program", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const invalidSystemProgram = TOKEN_PROGRAM_ID;
const ix: TransactionInstruction =
program.instruction.initializeTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
funder: ctx.wallet.publicKey,
systemProgram: invalidSystemProgram,
},
});
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [initialTokenBadgeAuthorityKeypair],
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc0/, // InvalidProgramId
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/set_token_badge_authority.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type { InitializeTokenBadgeParams } from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
describe("set_token_badge_authority", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function setTokenBadgeAuthority(
config: PublicKey,
configExtensionAuthority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: configExtensionAuthority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(configExtensionAuthority)
.buildAndExecute();
}
it("successfully set token badge authority and verify updated account contents", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialTokenBadgeAuthorityKeypair.publicKey.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
// initialize TokenBadge with updated authority
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
},
[updatedTokenBadgeAuthorityKeypair],
);
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
// config_extension not initialized
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
const anotherWhirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey;
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension: anotherWhirlpoolsConfigExtension,
configExtensionAuthority:
initialConfigExtensionAuthorityKeypair.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(initialTokenBadgeAuthorityKeypair)
.buildAndExecute(),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const fakeAuthority = Keypair.generate();
await assert.rejects(
toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority: fakeAuthority.publicKey,
newTokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
}),
)
.addSigner(fakeAuthority)
.buildAndExecute(),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority != config_extension_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
const extensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extensionData!.tokenBadgeAuthority.equals(
initialTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!initialTokenBadgeAuthorityKeypair.publicKey.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const updatedExtensionData = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
updatedExtensionData!.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
assert.ok(
!updatedTokenBadgeAuthorityKeypair.publicKey.equals(
initialConfigExtensionAuthorityKeypair.publicKey,
),
);
await assert.rejects(
setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
updatedTokenBadgeAuthorityKeypair,
Keypair.generate().publicKey,
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await setTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialTokenBadgeAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction =
program.instruction.setTokenBadgeAuthority({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
configExtensionAuthority:
updatedTokenBadgeAuthorityKeypair.publicKey,
newTokenBadgeAuthority: Keypair.generate().publicKey,
},
});
assert.equal(ix.keys.length, 4);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/v2/token-badge/delete_token_badge.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import * as assert from "assert";
import {
IGNORE_CACHE,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../../src";
import { defaultConfirmOptions } from "../../../utils/const";
import type {
DeleteTokenBadgeParams,
InitializeTokenBadgeParams,
} from "../../../../src/instructions";
import { createMintV2 } from "../../../utils/v2/token-2022";
import type { TokenTrait } from "../../../utils/v2/init-utils-v2";
describe("delete_token_badge", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const collectProtocolFeesAuthorityKeypair = Keypair.generate();
const feeAuthorityKeypair = Keypair.generate();
const rewardEmissionsSuperAuthorityKeypair = Keypair.generate();
const initialConfigExtensionAuthorityKeypair = feeAuthorityKeypair;
const initialTokenBadgeAuthorityKeypair = feeAuthorityKeypair;
const updatedTokenBadgeAuthorityKeypair = Keypair.generate();
async function createOtherWallet(): Promise<Keypair> {
const keypair = Keypair.generate();
const signature = await provider.connection.requestAirdrop(
keypair.publicKey,
100 * LAMPORTS_PER_SOL,
);
await provider.connection.confirmTransaction(signature, "confirmed");
return keypair;
}
async function initializeWhirlpoolsConfig(configKeypair: Keypair) {
return toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, {
collectProtocolFeesAuthority:
collectProtocolFeesAuthorityKeypair.publicKey,
feeAuthority: feeAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: provider.wallet.publicKey,
whirlpoolsConfigKeypair: configKeypair,
}),
)
.addSigner(configKeypair)
.buildAndExecute();
}
async function initializeWhirlpoolsConfigExtension(config: PublicKey) {
const pda = PDAUtil.getConfigExtension(ctx.program.programId, config);
return toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(ctx.program, {
feeAuthority: feeAuthorityKeypair.publicKey,
funder: provider.wallet.publicKey,
whirlpoolsConfig: config,
whirlpoolsConfigExtensionPda: pda,
}),
)
.addSigner(feeAuthorityKeypair)
.buildAndExecute();
}
async function initializeTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<InitializeTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
funder: provider.wallet.publicKey,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda,
tokenMint: mint,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
async function updateTokenBadgeAuthority(
config: PublicKey,
authority: Keypair,
newAuthority: PublicKey,
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
return toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
configExtensionAuthority: authority.publicKey,
newTokenBadgeAuthority: newAuthority,
}),
)
.addSigner(authority)
.buildAndExecute();
}
async function deleteTokenBadge(
config: PublicKey,
mint: PublicKey,
overwrite: Partial<DeleteTokenBadgeParams>,
signers: Keypair[] = [initialTokenBadgeAuthorityKeypair],
) {
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
config,
).publicKey;
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
config,
mint,
);
const tx = toTx(
ctx,
WhirlpoolIx.deleteTokenBadgeIx(ctx.program, {
whirlpoolsConfig: config,
whirlpoolsConfigExtension,
tokenBadgeAuthority: initialTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: tokenBadgePda.publicKey,
receiver: provider.wallet.publicKey,
...overwrite,
}),
);
signers.forEach((signer) => tx.addSigner(signer));
return tx.buildAndExecute();
}
describe("successfully delete token badge", () => {
const tokenTraits: TokenTrait[] = [
{ isToken2022: true },
{ isToken2022: false },
];
tokenTraits.forEach((tokenTrait) => {
it(`Mint TokenProgram: ${tokenTrait.isToken2022 ? "Token-2022" : "Token"}`, async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, tokenTrait);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
const preBalance = await provider.connection.getBalance(
provider.wallet.publicKey,
);
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
const postBalance = await provider.connection.getBalance(
provider.wallet.publicKey,
);
// wallet paid network fee, but receive rent. so balance should be increased.
assert.ok(postBalance > preBalance);
});
});
});
it("successfully delete when receiver is different than account paying for transaction fee", async () => {
const otherWallet = await createOtherWallet();
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
const preBalance = await provider.connection.getBalance(
otherWallet.publicKey,
);
const rent = await provider.connection.getBalance(tokenBadgePda.publicKey);
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
receiver: otherWallet.publicKey,
});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
const postBalance = await provider.connection.getBalance(
otherWallet.publicKey,
);
assert.equal(postBalance, preBalance + rent);
});
it("should be failed: already deleted", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
const tokenBadgeData = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData!.tokenMint.equals(mint));
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved === null);
// delete again
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {}),
/0xbc4/, // AccountNotInitialized
);
});
describe("invalid input account", () => {
it("should be failed: invalid whirlpools_config", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// config not initialized
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// config initialized, but not match to whirlpools_config_extension
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfig: anotherWhirlpoolsConfigKeypair.publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid whirlpools_config_extension", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const anotherWhirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(anotherWhirlpoolsConfigKeypair);
// config_extension not initialized
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// initialized, but fake config_extension
await initializeWhirlpoolsConfigExtension(
anotherWhirlpoolsConfigKeypair.publicKey,
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
whirlpoolsConfigExtension: PDAUtil.getConfigExtension(
ctx.program.programId,
anotherWhirlpoolsConfigKeypair.publicKey,
).publicKey,
}),
/0x7d1/, // ConstraintHasOne
);
});
it("should be failed: invalid token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const fakeAuthority = Keypair.generate();
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: config_extension_authority is passed as token_badge_authority", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const fakeAuthority = initialConfigExtensionAuthorityKeypair;
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
mint,
{
tokenBadgeAuthority: fakeAuthority.publicKey,
},
[fakeAuthority],
),
/0x7dc/, // ConstraintAddress
);
});
it("should be failed: token_badge_authority is not signer", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const whirlpoolsConfigExtension = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
).publicKey;
// update authority from provider.wallet
await updateTokenBadgeAuthority(
whirlpoolsConfigKeypair.publicKey,
initialConfigExtensionAuthorityKeypair,
updatedTokenBadgeAuthorityKeypair.publicKey,
);
const extension = await fetcher.getConfigExtension(
whirlpoolsConfigExtension,
IGNORE_CACHE,
);
assert.ok(
extension?.tokenBadgeAuthority.equals(
updatedTokenBadgeAuthorityKeypair.publicKey,
),
);
const ix: TransactionInstruction = program.instruction.deleteTokenBadge({
accounts: {
whirlpoolsConfig: whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension,
tokenBadgeAuthority: updatedTokenBadgeAuthorityKeypair.publicKey,
tokenMint: mint,
tokenBadge: PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
).publicKey,
receiver: ctx.wallet.publicKey,
},
});
assert.equal(ix.keys.length, 6);
assert.ok(
ix.keys[2].pubkey.equals(updatedTokenBadgeAuthorityKeypair.publicKey),
);
// unset signer flag
ix.keys[2].isSigner = false;
const tx = toTx(ctx, {
instructions: [ix],
cleanupInstructions: [],
signers: [], // no updatedTokenBadgeAuthorityKeypair
});
await assert.rejects(
tx.buildAndExecute(),
/0xbc2/, // AccountNotSigner
);
});
it("should be failed: invalid token_mint", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// mint is not uninitialized
const uninitializedMint = Keypair.generate().publicKey;
await assert.rejects(
deleteTokenBadge(
whirlpoolsConfigKeypair.publicKey,
uninitializedMint,
{},
),
/0xbc4/, // AccountNotInitialized
);
// different mint
const anotherMint = await createMintV2(provider, { isToken2022: true });
await assert.rejects(
initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenMint: anotherMint,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
it("should be failed: invalid token_badge", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
// different mint (PDA not initialized)
const anotherMint = await createMintV2(provider, { isToken2022: true });
const pdaForAnotherMint = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
anotherMint,
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenBadge: pdaForAnotherMint.publicKey,
}),
/0xbc4/, // AccountNotInitialized
);
// different mint (PDA initialized)
await initializeTokenBadge(
whirlpoolsConfigKeypair.publicKey,
anotherMint,
{},
);
await assert.rejects(
deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {
tokenBadge: pdaForAnotherMint.publicKey,
}),
/0x7d6/, // ConstraintSeeds (token_badge (PDA) is not valid)
);
});
});
describe("lifecycle", () => {
it("initialize / delete / (re)initialize / (re)delete", async () => {
const whirlpoolsConfigKeypair = Keypair.generate();
await initializeWhirlpoolsConfig(whirlpoolsConfigKeypair);
await initializeWhirlpoolsConfigExtension(
whirlpoolsConfigKeypair.publicKey,
);
const mint = await createMintV2(provider, { isToken2022: true });
const tokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfigKeypair.publicKey,
mint,
);
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeData1 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData1!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData1!.tokenMint.equals(mint));
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved1 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved1 === null);
// re-initialize
await initializeTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeData2 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(
tokenBadgeData2!.whirlpoolsConfig.equals(
whirlpoolsConfigKeypair.publicKey,
),
);
assert.ok(tokenBadgeData2!.tokenMint.equals(mint));
// re-delete
await deleteTokenBadge(whirlpoolsConfigKeypair.publicKey, mint, {});
const tokenBadgeDataRemoved2 = await fetcher.getTokenBadge(
tokenBadgePda.publicKey,
IGNORE_CACHE,
);
assert.ok(tokenBadgeDataRemoved2 === null);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/position_with_token_extensions_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil, Percentage, TransactionBuilder } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import {
buildWhirlpoolClient,
increaseLiquidityQuoteByLiquidityWithParams,
PDAUtil,
toTx,
WhirlpoolContext,
WhirlpoolIx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { sleep, TickSpacing, ZERO_BN } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { createTokenAccountV2 } from "../../utils/v2/token-2022";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { generateDefaultOpenPositionWithTokenExtensionsParams } from "../../utils/test-builders";
import { initTestPool } from "../../utils/init-utils";
import { Keypair } from "@solana/web3.js";
import type { PublicKey } from "@solana/web3.js";
describe("position with token extensions management tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const client = buildWhirlpoolClient(ctx);
const fetcher = ctx.fetcher;
async function getRent(address: PublicKey): Promise<number> {
const rent = (await ctx.connection.getAccountInfo(address))?.lamports;
assert.ok(rent !== undefined);
return rent;
}
async function checkClosed(address: PublicKey): Promise<void> {
assert.equal(await provider.connection.getAccountInfo(address), undefined);
}
const isToken2022Variations = [false, true];
isToken2022Variations.forEach((isToken2022) => {
it(`open, deposit, update fees and reward, withdraw, collect fees, collect reward, close (${isToken2022 ? "V2" : "V1"} instructions)`, async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
// pool init
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022 },
tokenTraitB: { isToken2022 },
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(1000),
}, // In range position
],
rewards: [
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(1_000_000),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
},
tokenAccountA: tokenOwnerAccountA,
tokenAccountB: tokenOwnerAccountB,
} = fixture.getInfos();
const pool = await client.getPool(whirlpoolPda.publicKey);
const tokenVaultA = tokenVaultAKeypair.publicKey;
const tokenVaultB = tokenVaultBKeypair.publicKey;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const tickArrayLower = tickArrayPda.publicKey;
const tickArrayUpper = tickArrayPda.publicKey;
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// open position
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint)
.buildAndExecute();
const position = params.positionPda.publicKey;
const positionTokenAccount = params.positionTokenAccount;
const baseParams = {
position,
positionTokenAccount,
positionAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenProgramA,
tokenProgramB,
tokenVaultA,
tokenVaultB,
whirlpool: whirlpoolPda.publicKey,
tickArrayLower,
tickArrayUpper,
};
// deposit
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: new anchor.BN(10_000_000),
slippageTolerance: Percentage.fromFraction(0, 1000),
tickLowerIndex,
tickUpperIndex,
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMaxA: depositQuote.tokenMaxA,
tokenMaxB: depositQuote.tokenMaxB,
...baseParams,
})
: // test V1
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMaxA: depositQuote.tokenMaxA,
tokenMaxB: depositQuote.tokenMaxB,
...baseParams,
}),
).buildAndExecute();
const positionStep1 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep1!.liquidity.eq(depositQuote.liquidityAmount));
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenMintA,
tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// accrue rewards
await sleep(2000);
const positionStep2 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep2!.feeOwedA.isZero());
assert.ok(positionStep2!.feeOwedB.isZero());
assert.ok(positionStep2!.rewardInfos[0].amountOwed.isZero());
// update fees and rewards
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
whirlpool: whirlpoolPda.publicKey,
position,
tickArrayLower,
tickArrayUpper,
}),
).buildAndExecute();
const positionStep3 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(!positionStep3!.feeOwedA.isZero());
assert.ok(!positionStep3!.feeOwedB.isZero());
assert.ok(!positionStep3!.rewardInfos[0].amountOwed.isZero());
// withdraw
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMinA: ZERO_BN,
tokenMinB: ZERO_BN,
...baseParams,
})
: // test V1
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
liquidityAmount: depositQuote.liquidityAmount,
tokenMinA: ZERO_BN,
tokenMinB: ZERO_BN,
...baseParams,
}),
).buildAndExecute();
const positionStep4 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep4!.liquidity.isZero());
// collect fees
const feeAccountA = await createTokenAccountV2(
provider,
{ isToken2022 },
tokenMintA,
provider.wallet.publicKey,
);
const feeAccountB = await createTokenAccountV2(
provider,
{ isToken2022 },
tokenMintB,
provider.wallet.publicKey,
);
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
...baseParams,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
})
: // test V1
WhirlpoolIx.collectFeesIx(ctx.program, {
...baseParams,
tokenOwnerAccountA: feeAccountA,
tokenOwnerAccountB: feeAccountB,
}),
).buildAndExecute();
const positionStep5 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep5!.feeOwedA.isZero());
assert.ok(positionStep5!.feeOwedB.isZero());
// collect reward
const rewardAccount = await createTokenAccountV2(
provider,
{ isToken2022: false },
pool.getData().rewardInfos[0].mint,
provider.wallet.publicKey,
);
await toTx(
ctx,
isToken2022
? // test V2
WhirlpoolIx.collectRewardV2Ix(ctx.program, {
...baseParams,
rewardIndex: 0,
rewardMint: pool.getData().rewardInfos[0].mint,
rewardOwnerAccount: rewardAccount,
rewardVault: pool.getData().rewardInfos[0].vault,
rewardTokenProgram: TOKEN_PROGRAM_ID,
})
: // test V1
WhirlpoolIx.collectRewardIx(ctx.program, {
...baseParams,
rewardIndex: 0,
rewardOwnerAccount: rewardAccount,
rewardVault: pool.getData().rewardInfos[0].vault,
}),
).buildAndExecute();
const positionStep6 = await fetcher.getPosition(position, IGNORE_CACHE);
assert.ok(positionStep6!.rewardInfos[0].amountOwed.isZero());
// close position
await toTx(
ctx,
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
).buildAndExecute();
checkClosed(params.positionPda.publicKey);
});
});
it("successfully opens and closes a position in one transaction", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
// open
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
await builder.buildAndExecute();
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
});
it("successfully opens and closes a position repeatedly with same Mint keypair (one transaction)", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
const numRepeat = 3;
for (let i = 0; i < numRepeat; i++) {
// open
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
}
await builder.buildAndExecute();
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
});
it("successfully opens and closes a position repeatedly with same Mint keypair (different transactions)", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const tickLowerIndex = 0;
const tickUpperIndex = 128;
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
true,
tickLowerIndex,
tickUpperIndex,
provider.wallet.publicKey,
);
const numRepeat = 3;
for (let i = 0; i < numRepeat; i++) {
const builder = new TransactionBuilder(ctx.connection, ctx.wallet);
const receiver = Keypair.generate();
// open
builder
.addInstruction(
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
)
.addSigner(mint);
// close
builder.addInstruction(
WhirlpoolIx.closePositionWithTokenExtensionsIx(ctx.program, {
positionAuthority: ctx.wallet.publicKey,
receiver: receiver.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMint,
positionTokenAccount: params.positionTokenAccount,
}),
);
await builder.buildAndExecute(undefined, { skipPreflight: true });
checkClosed(params.positionPda.publicKey);
checkClosed(params.positionMint);
checkClosed(params.positionTokenAccount);
// receiver received the rent (= transaction have been executed)
const received = await getRent(receiver.publicKey);
assert.ok(received > 0);
}
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/position_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import { toTx, WhirlpoolIx } from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { TickSpacing } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { initTestPool, openPosition } from "../../utils/init-utils";
import { generateDefaultOpenPositionParams } from "../../utils/test-builders";
describe("position management tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
it("successfully closes and opens a position in one transaction", async () => {
const { poolInitInfo } = await initTestPool(ctx, TickSpacing.Standard);
const { params } = await openPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
0,
128,
);
const receiverKeypair = anchor.web3.Keypair.generate();
const { params: newParams, mint } = await generateDefaultOpenPositionParams(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
0,
128,
ctx.wallet.publicKey,
ctx.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.closePositionIx(ctx.program, {
positionAuthority: provider.wallet.publicKey,
receiver: receiverKeypair.publicKey,
position: params.positionPda.publicKey,
positionMint: params.positionMintAddress,
positionTokenAccount: params.positionTokenAccount,
}),
)
.addInstruction(WhirlpoolIx.openPositionIx(ctx.program, newParams))
.addSigner(mint)
.buildAndExecute();
const closedResponse = await provider.connection.getTokenSupply(
params.positionMintAddress,
);
assert.equal(closedResponse.value.uiAmount, 0);
const openResponse = await provider.connection.getTokenSupply(
newParams.positionMintAddress,
);
assert.equal(openResponse.value.uiAmount, 1);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/bundled_position_management.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, TransactionBuilder, ZERO } from "@orca-so/common-sdk";
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import { Keypair, SystemProgram } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type {
PositionBundleData,
Whirlpool,
WhirlpoolClient,
} from "../../../src";
import {
NUM_REWARDS,
PDAUtil,
POSITION_BUNDLE_SIZE,
PoolUtil,
PriceMath,
WhirlpoolIx,
buildWhirlpoolClient,
collectFeesQuote,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { TickSpacing, ZERO_BN, createTokenAccount } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import {
initializePositionBundle,
openBundledPosition,
} from "../../utils/init-utils";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("bundled position management tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const vaultStartBalance = 1_000_000;
const liquidityAmount = new BN(10_000_000);
const sleep = (second: number) =>
new Promise((resolve) => setTimeout(resolve, second * 1000));
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
function checkBitmapIsOpened(
account: PositionBundleData,
bundleIndex: number,
): boolean {
if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE)
throw Error("bundleIndex is out of bounds");
const bitmapIndex = Math.floor(bundleIndex / 8);
const bitmapOffset = bundleIndex % 8;
return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) > 0;
}
function checkBitmapIsClosed(
account: PositionBundleData,
bundleIndex: number,
): boolean {
if (bundleIndex < 0 || bundleIndex >= POSITION_BUNDLE_SIZE)
throw Error("bundleIndex is out of bounds");
const bitmapIndex = Math.floor(bundleIndex / 8);
const bitmapOffset = bundleIndex % 8;
return (account.positionBitmap[bitmapIndex] & (1 << bitmapOffset)) === 0;
}
function checkBitmap(
account: PositionBundleData,
openedBundleIndexes: number[],
) {
for (let i = 0; i < POSITION_BUNDLE_SIZE; i++) {
if (openedBundleIndexes.includes(i)) {
assert.ok(checkBitmapIsOpened(account, i));
} else {
assert.ok(checkBitmapIsClosed(account, i));
}
}
}
async function accrueFees(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// all position should get some fees
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
}
async function stopRewardsEmission(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, configKeypairs } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsIx(ctx.program, {
whirlpool: pool.getAddress(),
rewardVaultKey: pool.getData().rewardInfos[i].vault,
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
rewardIndex: i,
emissionsPerSecondX64: ZERO,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
}
}
it(`successfully open POSITION_BUNDLE_SIZE(${POSITION_BUNDLE_SIZE}) bundled positions and then close them`, async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const positionBundlePubkey = positionBundleInfo.positionBundlePda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const batchSize = 12;
const openedBundleIndexes: number[] = [];
// open all
for (
let startBundleIndex = 0;
startBundleIndex < POSITION_BUNDLE_SIZE;
startBundleIndex += batchSize
) {
const minBundleIndex = startBundleIndex;
const maxBundleIndex =
Math.min(startBundleIndex + batchSize, POSITION_BUNDLE_SIZE) - 1;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
for (
let bundleIndex = minBundleIndex;
bundleIndex <= maxBundleIndex;
bundleIndex++
) {
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
builder.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundlePubkey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
);
openedBundleIndexes.push(bundleIndex);
}
await builder.buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
checkBitmap(positionBundleAccount!, openedBundleIndexes);
}
assert.equal(openedBundleIndexes.length, POSITION_BUNDLE_SIZE);
// close all
for (
let startBundleIndex = 0;
startBundleIndex < POSITION_BUNDLE_SIZE;
startBundleIndex += batchSize
) {
const minBundleIndex = startBundleIndex;
const maxBundleIndex =
Math.min(startBundleIndex + batchSize, POSITION_BUNDLE_SIZE) - 1;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
for (
let bundleIndex = minBundleIndex;
bundleIndex <= maxBundleIndex;
bundleIndex++
) {
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
builder.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPda.publicKey,
bundleIndex,
positionBundle: positionBundlePubkey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
);
openedBundleIndexes.shift();
}
await builder.buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
checkBitmap(positionBundleAccount!, openedBundleIndexes);
}
assert.equal(openedBundleIndexes.length, 0);
// delete position bundle
await toTx(
ctx,
WhirlpoolIx.deletePositionBundleIx(ctx.program, {
positionBundle: positionBundlePubkey,
positionBundleMint:
positionBundleInfo.positionBundleMintKeypair.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
owner: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const positionBundleAccount = await ctx.fetcher.getPositionBundle(
positionBundlePubkey,
IGNORE_CACHE,
);
assert.ok(positionBundleAccount === null);
});
it("successfully increase/decrease liquidity and harvest on bundled position", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const { poolInitInfo, rewards } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
// open bundled position
const bundleIndex = 0;
const positionInitInfo = await openBundledPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
);
const { bundledPositionPda } = positionInitInfo.params;
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
// increaseLiquidity
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const preIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preIncrease!.liquidity.isZero());
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
).buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
await sleep(2); // accrueRewards
await accrueFees(fixture);
await stopRewardsEmission(fixture);
// updateFeesAndRewards
const preUpdate = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preUpdate!.feeOwedA.isZero());
assert.ok(preUpdate!.feeOwedB.isZero());
assert.ok(preUpdate!.rewardInfos.every((r) => r.amountOwed.isZero()));
await toTx(
ctx,
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
position: bundledPositionPubkey,
tickArrayLower,
tickArrayUpper,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postUpdate = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postUpdate!.feeOwedA.gtn(0));
assert.ok(postUpdate!.feeOwedB.gtn(0));
assert.ok(postUpdate!.rewardInfos.every((r) => r.amountOwed.gtn(0)));
// collectFees
await toTx(
ctx,
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectFees = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectFees!.feeOwedA.isZero());
assert.ok(postCollectFees!.feeOwedB.isZero());
// collectReward
for (let i = 0; i < NUM_REWARDS; i++) {
const ata = await createTokenAccount(
provider,
rewards[i].rewardMint,
ctx.wallet.publicKey,
);
const preCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preCollectReward!.rewardInfos[i].amountOwed.gtn(0));
await toTx(
ctx,
WhirlpoolIx.collectRewardIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
rewardIndex: i,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardOwnerAccount: ata,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectReward!.rewardInfos[i].amountOwed.isZero());
}
// decreaseLiquidity
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const preDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preDecrease!.liquidity.eq(liquidityAmount));
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
).buildAndExecute();
const postDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postDecrease!.liquidity.isZero());
// close bundled position
await toTx(
ctx,
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
});
it("successfully repeatedly open bundled position & close bundled position", async () => {
const openCloseIterationNum = 5;
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const { poolInitInfo, rewards } = fixture.getInfos();
// increase feeGrowth
await accrueFees(fixture);
// increase rewardGrowth
await sleep(2);
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
for (let iter = 0; iter < openCloseIterationNum; iter++) {
// open bundled position
const positionInitInfo = await openBundledPosition(
ctx,
poolInitInfo.whirlpoolPda.publicKey,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
);
const { bundledPositionPda } = positionInitInfo.params;
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
positionInitInfo.params.tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
// initialized check (No data left over from previous opening)
const postOpen = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postOpen!.feeGrowthCheckpointA.isZero());
assert.ok(postOpen!.feeGrowthCheckpointB.isZero());
assert.ok(
postOpen!.rewardInfos.every((r) => r.growthInsideCheckpoint.isZero()),
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
// increaseLiquidity
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const preIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preIncrease!.liquidity.isZero());
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
).buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
// non-zero check
assert.ok(postIncrease!.feeGrowthCheckpointA.gtn(0));
assert.ok(postIncrease!.feeGrowthCheckpointB.gtn(0));
assert.ok(
postIncrease!.rewardInfos.every((r) => r.growthInsideCheckpoint.gtn(0)),
);
await sleep(2); // accrueRewards
await accrueFees(fixture);
// decreaseLiquidity
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const preDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preDecrease!.liquidity.eq(liquidityAmount));
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
).buildAndExecute();
const postDecrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postDecrease!.liquidity.isZero());
// collectFees
await toTx(
ctx,
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectFees = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectFees!.feeOwedA.isZero());
assert.ok(postCollectFees!.feeOwedB.isZero());
// collectReward
for (let i = 0; i < NUM_REWARDS; i++) {
const ata = await createTokenAccount(
provider,
rewards[i].rewardMint,
ctx.wallet.publicKey,
);
const preCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(preCollectReward!.rewardInfos[i].amountOwed.gtn(0));
await toTx(
ctx,
WhirlpoolIx.collectRewardIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
rewardIndex: i,
rewardVault: rewards[i].rewardVaultKeypair.publicKey,
rewardOwnerAccount: ata,
whirlpool: whirlpoolPubkey,
}),
).buildAndExecute();
const postCollectReward = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postCollectReward!.rewardInfos[i].amountOwed.isZero());
}
// close bundled position
await toTx(
ctx,
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
).buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
}
});
describe("Single Transaction", () => {
it("successfully openBundledPosition+increaseLiquidity / decreaseLiquidity+closeBundledPosition in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
// openBundledPosition + increaseLiquidity
const openIncreaseBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
openIncreaseBuilder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
);
await openIncreaseBuilder.buildAndExecute();
const postIncrease = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postIncrease!.liquidity.eq(liquidityAmount));
const withdrawAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
false,
);
const decreaseCloseBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
decreaseCloseBuilder
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: withdrawAmounts.tokenA,
tokenMinB: withdrawAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: ctx.wallet.publicKey,
}),
);
await decreaseCloseBuilder.buildAndExecute();
const postClose = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postClose === null);
});
it("successfully open bundled position & close bundled position in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const receiver = Keypair.generate();
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: receiver.publicKey,
}),
);
await builder.buildAndExecute();
const receiverBalance = await ctx.connection.getBalance(
receiver.publicKey,
"confirmed",
);
assert.ok(receiverBalance > 0);
});
it("successfully close & re-open bundled position with the same bundle index in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// open
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// reopen bundled position with same bundleIndex in single Tx
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex: tickLowerIndex + tickSpacing,
tickUpperIndex: tickUpperIndex + tickSpacing,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
);
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
// in Anchor v0.26.0, close & open in same Tx will success.
await builder.buildAndExecute();
const postReopen = await ctx.fetcher.getPosition(
bundledPositionPubkey,
IGNORE_CACHE,
);
assert.ok(postReopen!.liquidity.isZero());
assert.ok(postReopen!.tickLowerIndex === tickLowerIndex + tickSpacing);
assert.ok(postReopen!.tickUpperIndex === tickUpperIndex + tickSpacing);
});
it("successfully open bundled position & swap & close bundled position in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{ liquidityAmount, tickLowerIndex, tickUpperIndex }, // non bundled position (to create TickArrays)
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tokenOwnerAccountA = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
ctx.wallet.publicKey,
);
const tokenOwnerAccountB = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
ctx.wallet.publicKey,
);
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPubkey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPubkey,
);
const modifyLiquidityParams = {
liquidityAmount,
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tickArrayLower,
tickArrayUpper,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
};
const depositAmounts = PoolUtil.getTokenAmountsFromLiquidity(
liquidityAmount,
(await ctx.fetcher.getPool(whirlpoolPubkey, IGNORE_CACHE))!.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex),
true,
);
const swapInput = new BN(200_000);
const poolLiquidity = new BN(liquidityAmount.muln(2).toString());
const estimatedFee = new BN(swapInput.toString())
.muln(3)
.divn(1000) // feeRate 0.3%
.muln(97)
.divn(100) // minus protocolFee 3%
.shln(64)
.div(poolLiquidity) // to X64 growth
.mul(liquidityAmount)
.shrn(64)
.toNumber();
const receiver = Keypair.generate();
const receiverAtaA = await createTokenAccount(
provider,
poolInitInfo.tokenMintA,
receiver.publicKey,
);
const receiverAtaB = await createTokenAccount(
provider,
poolInitInfo.tokenMintB,
receiver.publicKey,
);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMaxA: depositAmounts.tokenA,
tokenMaxB: depositAmounts.tokenB,
}),
)
.addInstruction(
WhirlpoolIx.swapIx(ctx.program, {
amount: swapInput,
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.swapIx(ctx.program, {
amount: swapInput,
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPubkey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
)
.addInstruction(
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
...modifyLiquidityParams,
tokenMinA: new BN(0),
tokenMinB: new BN(0),
}),
)
.addInstruction(
WhirlpoolIx.collectFeesIx(ctx.program, {
position: bundledPositionPubkey,
positionAuthority: ctx.wallet.publicKey,
positionTokenAccount: positionBundleInfo.positionBundleTokenAccount,
tokenOwnerAccountA: receiverAtaA,
tokenOwnerAccountB: receiverAtaB,
tokenVaultA: poolInitInfo.tokenVaultAKeypair.publicKey,
tokenVaultB: poolInitInfo.tokenVaultBKeypair.publicKey,
whirlpool: whirlpoolPubkey,
}),
)
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: receiver.publicKey,
}),
);
await builder.buildAndExecute();
assert.ok(
(await ctx.fetcher.getTokenInfo(receiverAtaA, IGNORE_CACHE))!.amount ===
BigInt(estimatedFee.toString()),
);
assert.ok(
(await ctx.fetcher.getTokenInfo(receiverAtaB, IGNORE_CACHE))!.amount ===
BigInt(estimatedFee.toString()),
);
});
});
describe("Ensuring that the account is closed", () => {
it("The discriminator of the deleted position bundle is marked as closed", async () => {
const ctx = testCtx.whirlpoolCtx;
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const preClose = await ctx.connection.getAccountInfo(
positionBundleInfo.positionBundlePda.publicKey,
"confirmed",
);
assert.ok(preClose !== null);
const rentOfPositionBundle = preClose.lamports;
assert.ok(rentOfPositionBundle > 0);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// close
.addInstruction(
WhirlpoolIx.deletePositionBundleIx(ctx.program, {
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleMint:
positionBundleInfo.positionBundleMintKeypair.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
owner: ctx.wallet.publicKey,
receiver: ctx.wallet.publicKey,
}),
)
// fund rent
.addInstruction({
instructions: [
SystemProgram.transfer({
fromPubkey: ctx.wallet.publicKey,
toPubkey: positionBundleInfo.positionBundlePda.publicKey,
lamports: rentOfPositionBundle,
}),
],
cleanupInstructions: [],
signers: [],
});
await builder.buildAndExecute();
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
const postClose = await ctx.connection.getAccountInfo(
positionBundleInfo.positionBundlePda.publicKey,
"confirmed",
);
assert.ok(postClose !== null);
assert.ok(postClose.owner.equals(SystemProgram.programId));
assert.ok(postClose.data.length === 0);
});
it("The owner of closed account should be system program", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
// open
await toTx(
ctx,
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
).buildAndExecute();
const preClose = await ctx.connection.getAccountInfo(
bundledPositionPubkey,
"confirmed",
);
assert.ok(preClose !== null);
const rentOfBundledPosition = preClose.lamports;
assert.ok(rentOfBundledPosition > 0);
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// fund rent
.addInstruction({
instructions: [
SystemProgram.transfer({
fromPubkey: ctx.wallet.publicKey,
toPubkey: bundledPositionPubkey,
lamports: rentOfBundledPosition,
}),
],
cleanupInstructions: [],
signers: [],
});
await builder.buildAndExecute();
// Account closing reassigns to system program and reallocates
// https://github.com/coral-xyz/anchor/pull/2169
const postClose = await ctx.connection.getAccountInfo(
bundledPositionPubkey,
"confirmed",
);
assert.ok(postClose !== null);
assert.ok(postClose.owner.equals(SystemProgram.programId));
assert.ok(postClose.data.length === 0);
});
it("should be failed: close bundled position and then updateFeesAndRewards in single Tx", async () => {
// create test pool
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [],
rewards: [],
});
const { poolInitInfo } = fixture.getInfos();
// initialize position bundle
const positionBundleInfo = await initializePositionBundle(
ctx,
ctx.wallet.publicKey,
);
const bundleIndex = Math.floor(Math.random() * POSITION_BUNDLE_SIZE);
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleInfo.positionBundleMintKeypair.publicKey,
bundleIndex,
);
const bundledPositionPubkey = bundledPositionPda.publicKey;
const whirlpoolPubkey = poolInitInfo.whirlpoolPda.publicKey;
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
tickLowerIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
tickUpperIndex,
poolInitInfo.tickSpacing,
poolInitInfo.whirlpoolPda.publicKey,
ctx.program.programId,
).publicKey;
const builder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
builder
// open
.addInstruction(
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
tickLowerIndex,
tickUpperIndex,
whirlpool: whirlpoolPubkey,
funder: ctx.wallet.publicKey,
}),
)
// close
.addInstruction(
WhirlpoolIx.closeBundledPositionIx(ctx.program, {
bundledPosition: bundledPositionPubkey,
bundleIndex,
positionBundle: positionBundleInfo.positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount:
positionBundleInfo.positionBundleTokenAccount,
receiver: whirlpoolPubkey,
}),
)
// try to use closed bundled position
.addInstruction(
WhirlpoolIx.updateFeesAndRewardsIx(ctx.program, {
position: bundledPositionPubkey,
tickArrayLower,
tickArrayUpper,
whirlpool: whirlpoolPubkey,
}),
);
await assert.rejects(
builder.buildAndExecute(),
/0xbc4/, // AccountNotInitialized
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/sparse_swap.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { DecimalUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { AccountMeta } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import type {
SwapQuote,
TwoHopSwapV2Params,
WhirlpoolClient,
WhirlpoolData,
} from "../../../src";
import {
MEMO_PROGRAM_ADDRESS,
PDAUtil,
PriceMath,
SwapUtils,
TickUtil,
WhirlpoolIx,
buildWhirlpoolClient,
increaseLiquidityQuoteByInputToken,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { defaultConfirmOptions } from "../../utils/const";
import {
buildTestAquariums,
getDefaultAquarium,
initTestPoolWithTokens,
} from "../../utils/init-utils";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { buildTickArrayData } from "../../utils/testDataTypes";
import type { SwapV2Params } from "../../../src/instructions";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
} from "../../../src/utils/remaining-accounts-util";
interface SharedTestContext {
provider: anchor.AnchorProvider;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("sparse swap tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
whirlpoolCtx,
whirlpoolClient,
};
});
const tickSpacing64 = 64;
const tickSpacing8192 = 8192;
describe("TickArray order adjustment", () => {
it("reverse order(ta2, ta1, ta0 => ta0, ta1, ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// reverse
tickArray0: params.tickArray2,
tickArray1: params.tickArray1,
tickArray2: params.tickArray0,
}),
).buildAndExecute();
// 3000 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("reverse order(ta2, ta1, ta0 => ta0, ta1, ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-3000), // tickCurrentIndex = -3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [-2944, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
-2944,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-2944, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// reverse
tickArray0: params.tickArray2,
tickArray1: params.tickArray1,
tickArray2: params.tickArray0,
}),
).buildAndExecute();
// -3000 --> larger than 5632
assert.ok((await pool.refreshData()).tickCurrentIndex > 5632);
});
it("skip ta0(ta0, ta1, ta2 => ta1, ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(64), // tickCurrentIndex = 64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, -128], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
-128,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, -128, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 64);
// another swap push tickCurrentIndex to less than -128
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex <= -128);
assert.ok((await pool.refreshData()).tickCurrentIndex > -5632);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// less than -128 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("skip ta0, ta1(ta0, ta1, ta2 => ta2), a to b", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(64), // tickCurrentIndex = 64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, -5760], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
-5760,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, -5760, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 64);
// another swap push tickCurrentIndex to less than -5760
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex <= -5760);
assert.ok((await pool.refreshData()).tickCurrentIndex > -9984);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// less than -5760 --> less than -5760
assert.ok((await pool.refreshData()).tickCurrentIndex < -5760);
});
it("skip ta0(ta0, ta1, ta2 => ta1, ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-64), // tickCurrentIndex = -64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [128, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
128,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(128, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -64);
// another swap push tickCurrentIndex to greater than 128
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex >= 128);
assert.ok((await pool.refreshData()).tickCurrentIndex < 5632);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// greater than 128 --> greater than 5632
assert.ok((await pool.refreshData()).tickCurrentIndex > 5632);
});
it("skip ta0, ta1(ta0, ta1, ta2 => ta2), b to a", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-64), // tickCurrentIndex = -64
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-5632 ][0 ][5632 ]
await (await pool.initTickArrayForTicks([
-5632, 0, 5632,
]))!.buildAndExecute();
// deposit [5760, 9984], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
5760,
9984,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(5760, 9984, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(99_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex <= -64);
// another swap push tickCurrentIndex to greater than 5760
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool.refreshData()).tickCurrentIndex >= 5760);
assert.ok((await pool.refreshData()).tickCurrentIndex < 9984);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params),
).buildAndExecute();
// greater than 5760 --> greater than 5760
assert.ok((await pool.refreshData()).tickCurrentIndex > 5760);
});
it("a to b & b to a with same TickArray list", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing8192,
PriceMath.tickIndexToSqrtPriceX64(0),
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-720896 ][0 ]
await (await pool.initTickArrayForTicks([-720896, 0]))!.buildAndExecute();
// deposit FullRange, 100_000_000
const fullrange = TickUtil.getFullRangeTickIndex(tickSpacing8192);
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000), 0),
fullrange[0],
fullrange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(fullrange[0], fullrange[1], depositQuote)
).tx.buildAndExecute();
const ta0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
whirlpoolPda.publicKey,
-720896,
).publicKey;
const ta1 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
whirlpoolPda.publicKey,
0,
).publicKey;
// a to b
await pool.refreshData();
const aToBParams = SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(1_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...aToBParams,
// always use ta0, ta1, ta1
tickArray0: ta0,
tickArray1: ta1,
tickArray2: ta1,
}),
).buildAndExecute();
// b to a
await pool.refreshData();
const bToAParams = SwapUtils.getSwapParamsFromQuote(
await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintA,
new BN(1_000),
Percentage.fromFraction(10, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...bToAParams,
// always use ta0, ta1, ta1
tickArray0: ta0,
tickArray1: ta1,
tickArray2: ta1,
}),
).buildAndExecute();
});
describe("failures", () => {
async function buildTestEnvironment() {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
return { poolInitInfo, params };
}
it("fail: invalid tick array (owned by other program)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tokenVaultA, // owned by TokenProgram
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tokenVaultA, // owned by TokenProgram
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: params.tokenVaultA, // owned by TokenProgram
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [params.tokenVaultA],
}),
).buildAndExecute(),
/0xbbf/, // AccountOwnedByWrongProgram
);
});
it("fail: invalid tick array (owned by Whirlpool program, but not TickArray account)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: params.whirlpool, // owned by Whirlpool program, but Whirlpool account
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [
params.whirlpool, // owned by Whirlpool program, but Whirlpool account
],
}),
).buildAndExecute(),
/0xbba/, // AccountDiscriminatorMismatch
);
});
it("fail: invalid tick array (initialized TickArray account, but for other whirlpool)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const { whirlpoolPda: anotherWhirlpoolPda } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const anotherPool = await testCtx.whirlpoolClient.getPool(
anotherWhirlpoolPda.publicKey,
);
await (await anotherPool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
const anotherWhirlpoolTickArray0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
anotherWhirlpoolPda.publicKey,
0,
).publicKey;
const fetched = await testCtx.whirlpoolCtx.fetcher.getTickArray(
anotherWhirlpoolTickArray0,
IGNORE_CACHE,
);
assert.ok(fetched !== null);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: anotherWhirlpoolTickArray0, // for another Whirlpool
tickArray1: params.tickArray1,
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: anotherWhirlpoolTickArray0, // for another Whirlpool
tickArray2: params.tickArray2,
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
tickArray0: params.tickArray0,
tickArray1: params.tickArray1,
tickArray2: anotherWhirlpoolTickArray0, // for another Whirlpool
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// supplemental
supplementalTickArrays: [
anotherWhirlpoolTickArray0, // for another Whirlpool
],
}),
).buildAndExecute(),
/0x17a8/, // DifferentWhirlpoolTickArrayAccount
);
});
it("fail: no appropriate tick array (initialized TickArray, but start_tick_index mismatch)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const tickArrayNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
poolInitInfo.whirlpoolPda.publicKey,
-5632,
).publicKey;
const fetched = await testCtx.whirlpoolCtx.fetcher.getTickArray(
tickArrayNeg5632,
IGNORE_CACHE,
);
assert.ok(fetched !== null);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// expected first tick array should start from 0
tickArray0: tickArrayNeg5632,
tickArray1: tickArrayNeg5632,
tickArray2: tickArrayNeg5632,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// expected first tick array should start from 0
tickArray0: tickArrayNeg5632,
tickArray1: tickArrayNeg5632,
tickArray2: tickArrayNeg5632,
// supplemental
supplementalTickArrays: [
tickArrayNeg5632,
tickArrayNeg5632,
tickArrayNeg5632,
],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
it("fail: no appropriate tick array (uninitialized TickArray, and PDA mismatch)", async () => {
const { poolInitInfo, params } = await buildTestEnvironment();
const uninitializedRandomAddress = Keypair.generate().publicKey;
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
// expected first tick array should start from 0
tickArray0: uninitializedRandomAddress,
tickArray1: uninitializedRandomAddress,
tickArray2: uninitializedRandomAddress,
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, {
...params,
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// expected first tick array should start from 0
tickArray0: uninitializedRandomAddress,
tickArray1: uninitializedRandomAddress,
tickArray2: uninitializedRandomAddress,
// supplemental
supplementalTickArrays: [
uninitializedRandomAddress,
uninitializedRandomAddress,
uninitializedRandomAddress,
],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
});
});
});
describe("swap through uninitialized TickArrays(*: init, -: uninit, S: start, T: end)", () => {
// |--------| uninitialized
// |********| initialized
// S: swap start / T: swap end
async function buildTestEnvironment() {
// ts: 64
// liquidity provided from full range
const initResult = await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(2816),
new BN(1_000_000_000),
);
const { poolInitInfo, whirlpoolPda } = initResult;
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
const fullrange = TickUtil.getFullRangeTickIndex(tickSpacing8192);
await (await pool.initTickArrayForTicks([
fullrange[0],
fullrange[1],
]))!.buildAndExecute();
// deposit FullRange, 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintA,
DecimalUtil.fromBN(new BN(100_000_000), 0),
fullrange[0],
fullrange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(fullrange[0], fullrange[1], depositQuote)
).tx.buildAndExecute();
const data = await pool.refreshData();
assert.ok(data.tickCurrentIndex == 2816);
assert.ok(data.liquidity.gtn(0));
return initResult;
}
describe("swap, b to a: 2816 --> 2816 + (64 * 88) * 2", () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{ quote: SwapQuote; poolData: WhirlpoolData }> {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const startTickIndexes = [0, 5632, 11264];
const init = [init0, init1, init2];
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays = await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays[i].data === null);
tickArrays[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays[i].data!.whirlpool = pool.getAddress();
} else {
assert.ok(tickArrays[i].data !== null);
}
});
const quote = swapQuoteWithParams(
{
whirlpoolData: pool.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote.estimatedAmountIn.gtn(0));
assert.ok(quote.estimatedAmountOut.gtn(0));
const params = {
...SwapUtils.getSwapParamsFromQuote(
quote,
testCtx.whirlpoolCtx,
pool,
tokenAccountB,
tokenAccountA,
testCtx.provider.wallet.publicKey,
),
amountSpecifiedIsInput: true,
amount: quote.estimatedAmountIn,
otherAmountThreshold: quote.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool.refreshData()).tickCurrentIndex === targetTickIndex,
);
return { quote, poolData: pool.getData() };
}
let referenceResult: { quote: SwapQuote; poolData: WhirlpoolData };
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta0}${ta1}${ta2}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote.estimatedAmountIn.eq(
referenceResult.quote.estimatedAmountIn,
),
);
assert.ok(
result.quote.estimatedAmountOut.eq(
referenceResult.quote.estimatedAmountOut,
),
);
assert.ok(
result.poolData.tickCurrentIndex ===
referenceResult.poolData.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("swap, a to b: 2816 - (64 * 88) * 2 <-- 2816", () => {
const aToB = true;
const initialTickIndex = 2816;
const targetTickIndex = 2816 - tickSpacing64 * 88 * 2; // <-- 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{ quote: SwapQuote; poolData: WhirlpoolData }> {
const { poolInitInfo, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const startTickIndexes = [0, -5632, -11264];
const init = [init0, init1, init2];
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays = await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays[i].data === null);
tickArrays[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays[i].data!.whirlpool = pool.getAddress();
} else {
assert.ok(tickArrays[i].data !== null);
}
});
const quote = swapQuoteWithParams(
{
whirlpoolData: pool.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote.estimatedAmountIn.gtn(0));
assert.ok(quote.estimatedAmountOut.gtn(0));
const params = {
...SwapUtils.getSwapParamsFromQuote(
quote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
amountSpecifiedIsInput: true,
amount: quote.estimatedAmountIn,
otherAmountThreshold: quote.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
// v2 specific
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool.refreshData()).tickCurrentIndex ===
targetTickIndex - 1 /* shift */,
);
return { quote, poolData: pool.getData() };
}
let referenceResult: { quote: SwapQuote; poolData: WhirlpoolData };
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta2}${ta1}${ta0}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote.estimatedAmountIn.eq(
referenceResult.quote.estimatedAmountIn,
),
);
assert.ok(
result.quote.estimatedAmountOut.eq(
referenceResult.quote.estimatedAmountOut,
),
);
assert.ok(
result.poolData.tickCurrentIndex ===
referenceResult.poolData.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("twoHopSwap, b to a: 2816 --> 2816 + (64 * 88) * 2", () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
}> {
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const init = [init0, init1, init2];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool0.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays0[i].data === null);
tickArrays0[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays0[i].data!.whirlpool = pool0.getAddress();
assert.ok(tickArrays1[i].data === null);
tickArrays1[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays1[i].data!.whirlpool = pool1.getAddress();
} else {
assert.ok(tickArrays0[i].data !== null);
assert.ok(tickArrays1[i].data !== null);
}
});
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const params = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays1[0].address,
tickArrayOne1: tickArrays1[1].address,
tickArrayOne2: tickArrays1[2].address,
tickArrayTwo0: tickArrays0[0].address,
tickArrayTwo1: tickArrays0[1].address,
tickArrayTwo2: tickArrays0[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.twoHopSwapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool0.refreshData()).tickCurrentIndex >= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex >= targetTickIndex,
);
return {
quote0,
poolData0: pool0.getData(),
quote1,
poolData1: pool1.getData(),
};
}
let referenceResult: {
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
};
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta0}${ta1}${ta2} -> ${ta0}${ta1}${ta2}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote0.estimatedAmountIn.eq(
referenceResult.quote0.estimatedAmountIn,
),
);
assert.ok(
result.quote0.estimatedAmountOut.eq(
referenceResult.quote0.estimatedAmountOut,
),
);
assert.ok(
result.poolData0.tickCurrentIndex ===
referenceResult.poolData0.tickCurrentIndex,
);
assert.ok(
result.quote1.estimatedAmountIn.eq(
referenceResult.quote1.estimatedAmountIn,
),
);
assert.ok(
result.quote1.estimatedAmountOut.eq(
referenceResult.quote1.estimatedAmountOut,
),
);
assert.ok(
result.poolData1.tickCurrentIndex ===
referenceResult.poolData1.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
describe("twoHopSwap, a to b: 2816 + (64 * 88) * 2 <-- 2816", () => {
const aToB = true;
const initialTickIndex = 2816;
const targetTickIndex = 2816 - tickSpacing64 * 88 * 2; // <-- 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
async function runSwap(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
): Promise<{
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
}> {
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool0(a(0) -> b(1)) --> pool1(a(1) -> b(2)) (so pool1 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(7_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, -5632, -11264];
const init = [init0, init1, init2];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
const tickArrayIndexes: number[] = [];
init.forEach((v, i) => {
if (v) {
tickArrayIndexes.push(startTickIndexes[i]);
}
});
if (tickArrayIndexes.length > 0) {
await (await pool0.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
tickArrayIndexes,
))!.buildAndExecute();
}
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
// padding if needed
init.forEach((v, i) => {
if (!v) {
assert.ok(tickArrays0[i].data === null);
tickArrays0[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays0[i].data!.whirlpool = pool0.getAddress();
assert.ok(tickArrays1[i].data === null);
tickArrays1[i].data = buildTickArrayData(
startTickIndexes[i],
[],
).data;
tickArrays1[i].data!.whirlpool = pool1.getAddress();
} else {
assert.ok(tickArrays0[i].data !== null);
assert.ok(tickArrays1[i].data !== null);
}
});
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote0.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const params = {
amount: quote0.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays0[0].address,
tickArrayOne1: tickArrays0[1].address,
tickArrayOne2: tickArrays0[2].address,
tickArrayTwo0: tickArrays1[0].address,
tickArrayTwo1: tickArrays1[1].address,
tickArrayTwo2: tickArrays1[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool0.getAddress(),
whirlpoolTwo: pool1.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[1].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[2].account,
tokenVaultOneA: pool0.getData().tokenVaultA,
tokenVaultOneB: pool0.getData().tokenVaultB,
tokenVaultTwoA: pool1.getData().tokenVaultA,
tokenVaultTwoB: pool1.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[0].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[2].account,
tokenVaultOneInput: pool0.getData().tokenVaultA,
tokenVaultOneIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoOutput: pool1.getData().tokenVaultB,
tokenMintInput: pool0.getData().tokenMintA,
tokenMintIntermediate: pool0.getData().tokenMintB,
tokenMintOutput: pool1.getData().tokenMintB,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
!v2
? WhirlpoolIx.twoHopSwapIx(testCtx.whirlpoolCtx.program, params)
: WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok(
(await pool0.refreshData()).tickCurrentIndex <= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex <= targetTickIndex,
);
return {
quote0,
poolData0: pool0.getData(),
quote1,
poolData1: pool1.getData(),
};
}
let referenceResult: {
quote0: SwapQuote;
poolData0: WhirlpoolData;
quote1: SwapQuote;
poolData1: WhirlpoolData;
};
beforeAll(async () => {
referenceResult = await runSwap(true, true, true, false);
});
function runTest(
init0: boolean,
init1: boolean,
init2: boolean,
v2: boolean,
) {
const swap = v2 ? "v2" : "v1";
const ta0 = init0 ? "|****S***|" : "|----S---|";
const ta1 = init1 ? "********" : "--------";
const ta2 = init2 ? "|****T***|" : "|----T---|";
it(`${swap}: ${ta2}${ta1}${ta0} <- ${ta2}${ta1}${ta0}`, async () => {
const result = await runSwap(init0, init1, init2, v2);
assert.ok(
result.quote0.estimatedAmountIn.eq(
referenceResult.quote0.estimatedAmountIn,
),
);
assert.ok(
result.quote0.estimatedAmountOut.eq(
referenceResult.quote0.estimatedAmountOut,
),
);
assert.ok(
result.poolData0.tickCurrentIndex ===
referenceResult.poolData0.tickCurrentIndex,
);
assert.ok(
result.quote1.estimatedAmountIn.eq(
referenceResult.quote1.estimatedAmountIn,
),
);
assert.ok(
result.quote1.estimatedAmountOut.eq(
referenceResult.quote1.estimatedAmountOut,
),
);
assert.ok(
result.poolData1.tickCurrentIndex ===
referenceResult.poolData1.tickCurrentIndex,
);
});
}
for (const v2 of [false, true]) {
for (const init0 of [true, false]) {
for (const init1 of [true, false]) {
for (const init2 of [true, false]) {
runTest(init0, init1, init2, v2);
}
}
}
}
});
});
describe("supplemental TickArrays (v2 only)", () => {
describe("swapV2", () => {
async function buildTestEnvironment() {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(3000), // tickCurrentIndex = 3000
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
return { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB };
}
it("using 3 supplemental tick arrays", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
5632,
).publicKey;
const taStart0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
0,
).publicKey;
const taStartNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-5632,
).publicKey;
const taStartNeg11264 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-11264,
).publicKey;
const paramsWithoutSupplemental = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// TA starting with 5632 will not be used...
tickArray0: taStart5632,
tickArray1: taStart5632,
tickArray2: taStart5632,
};
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
const paramsWithSupplemental = {
...paramsWithoutSupplemental,
supplementalTickArrays: [
// should be adjusted at the program side
taStartNeg11264,
taStart0,
taStartNeg5632,
],
};
assert.ok((await pool.refreshData()).tickCurrentIndex >= 2944);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute(undefined, { skipPreflight: true });
// 3000 --> less than -5632
assert.ok((await pool.refreshData()).tickCurrentIndex < -5632);
});
it("fail: 4 supplemental tick arrays (too many)", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await buildTestEnvironment();
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(99_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
5632,
).publicKey;
const supplementalTickArrays = [
taStart5632,
taStart5632,
taStart5632,
taStart5632,
];
const params: SwapV2Params = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
// too many
supplementalTickArrays,
};
assert.throws(
() => WhirlpoolIx.swapV2Ix(testCtx.whirlpoolCtx.program, params),
/Too many supplemental tick arrays provided/, // SDK error
);
// bypass SDK
const supplementalTickArrayAccountMetas: AccountMeta[] =
supplementalTickArrays.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArrays,
supplementalTickArrayAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.swapV2(
params.amount,
params.otherAmountThreshold,
params.sqrtPriceLimit,
params.amountSpecifiedIsInput,
params.aToB,
remainingAccountsInfo,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
});
it("go back to the previous tick array", async () => {
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacing64,
PriceMath.tickIndexToSqrtPriceX64(-128), // tickCurrentIndex = -128
new BN(1_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// [-11264 ][-5632 ][0 ]
await (await pool.initTickArrayForTicks([
-11264, -5632, 0,
]))!.buildAndExecute();
// deposit [-9984, 2944], 100_000
const depositQuote = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(100_000), 0),
-9984,
2944,
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
await (
await pool.openPosition(-9984, 2944, depositQuote)
).tx.buildAndExecute();
await pool.refreshData();
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(80_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const taStart0 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
0,
).publicKey;
const taStartNeg5632 = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
-5632,
).publicKey;
const paramsWithoutSupplemental = {
...SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
),
// v2 required
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenProgramA: TOKEN_PROGRAM_ID,
tokenProgramB: TOKEN_PROGRAM_ID,
};
// it should start from TA with startTickIndex -5632
assert.ok(pool.getData().tickCurrentIndex == -128);
assert.ok(paramsWithoutSupplemental.tickArray0.equals(taStartNeg5632));
// another swap to push tickCurrentIndex to > 0
const anotherSwapQuote = await swapQuoteByInputToken(
pool,
poolInitInfo.tokenMintB,
new BN(10_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
assert.ok(anotherSwapQuote.estimatedEndTickIndex > 128);
await (await pool.swap(anotherSwapQuote)).buildAndExecute();
await pool.refreshData();
assert.ok(pool.getData().tickCurrentIndex > 128);
const preOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
paramsWithoutSupplemental.tokenOwnerAccountB,
);
// now tickCurrentIndex was push backed to > 128, so TickArray with startTickIndex 0 should be used as the first one
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
// If TickArray with startTickIndex 0 is included in supplementalTickArrays, it should work.
const paramsWithSupplemental = {
...paramsWithoutSupplemental,
supplementalTickArrays: [taStart0],
};
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute(undefined, { skipPreflight: true });
assert.ok((await pool.refreshData()).tickCurrentIndex < 0);
const postOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
paramsWithoutSupplemental.tokenOwnerAccountB,
);
// output balance should be increased (actual output will be better than quote due to the push back)
assert.ok(
new BN(postOutputBalance.value.amount)
.sub(new BN(preOutputBalance.value.amount))
.gte(swapQuote.estimatedAmountOut),
);
});
});
describe("twoHopSwapV2", () => {
it("using 3 supplemental tick arrays", async () => {
const aToB = false;
const initialTickIndex = 2816;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const wrongAddress = Keypair.generate().publicKey;
const paramsWithoutSupplemental = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: wrongAddress,
tickArrayOne1: wrongAddress,
tickArrayOne2: wrongAddress,
tickArrayTwo0: wrongAddress,
tickArrayTwo1: wrongAddress,
tickArrayTwo2: wrongAddress,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
const supplementalTickArraysOne = [
// should be adjusted at the program side
tickArrays1[2].address,
tickArrays1[0].address,
tickArrays1[1].address,
];
const supplementalTickArraysTwo = [
// should be adjusted at the program side
tickArrays0[2].address,
tickArrays0[0].address,
tickArrays0[1].address,
];
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
const paramsWithSupplemental: TwoHopSwapV2Params = {
...paramsWithoutSupplemental,
supplementalTickArraysOne,
supplementalTickArraysTwo,
};
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithSupplemental,
),
).buildAndExecute();
assert.ok(
(await pool0.refreshData()).tickCurrentIndex >= targetTickIndex,
);
assert.ok(
(await pool1.refreshData()).tickCurrentIndex >= targetTickIndex,
);
});
it("fail: 4 supplemental tick arrays (too many)", async () => {
const aToB = false;
const targetTickIndex = 2816 + tickSpacing64 * 88 * 2; // --> 2 tick arrays
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const wrongAddress = Keypair.generate().publicKey;
const supplementalTickArraysOne = [
wrongAddress,
wrongAddress,
wrongAddress,
wrongAddress,
];
const supplementalTickArraysTwo = [
wrongAddress,
wrongAddress,
wrongAddress,
wrongAddress,
];
const params = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: wrongAddress,
tickArrayOne1: wrongAddress,
tickArrayOne2: wrongAddress,
tickArrayTwo0: wrongAddress,
tickArrayTwo1: wrongAddress,
tickArrayTwo2: wrongAddress,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v1 specific
tokenOwnerAccountOneA: aquarium.tokenAccounts[1].account,
tokenOwnerAccountOneB: aquarium.tokenAccounts[2].account,
tokenOwnerAccountTwoA: aquarium.tokenAccounts[0].account,
tokenOwnerAccountTwoB: aquarium.tokenAccounts[1].account,
tokenVaultOneA: pool1.getData().tokenVaultA,
tokenVaultOneB: pool1.getData().tokenVaultB,
tokenVaultTwoA: pool0.getData().tokenVaultA,
tokenVaultTwoB: pool0.getData().tokenVaultB,
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
// too many
supplementalTickArraysOne,
supplementalTickArraysTwo,
};
assert.throws(
() =>
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, params),
/Too many supplemental tick arrays provided/, // SDK error
);
// bypass SDK
const supplementalTickArrayOneAccountMetas: AccountMeta[] =
supplementalTickArraysOne.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfoOne, remainingAccountsOne] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArraysOne,
supplementalTickArrayOneAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.twoHopSwapV2(
params.amount,
params.otherAmountThreshold,
params.amountSpecifiedIsInput,
params.aToBOne,
params.aToBTwo,
params.sqrtPriceLimitOne,
params.sqrtPriceLimitTwo,
remainingAccountsInfoOne,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: remainingAccountsOne,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
// bypass SDK
const supplementalTickArrayTwoAccountMetas: AccountMeta[] =
supplementalTickArraysTwo.map((pubkey) => ({
pubkey,
isSigner: false,
isWritable: true,
}));
const [remainingAccountsInfoTwo, remainingAccountsTwo] =
new RemainingAccountsBuilder()
.addSlice(
RemainingAccountsType.SupplementalTickArraysTwo,
supplementalTickArrayTwoAccountMetas,
)
.build();
await assert.rejects(
toTx(testCtx.whirlpoolCtx, {
cleanupInstructions: [],
signers: [],
instructions: [
testCtx.whirlpoolCtx.program.instruction.twoHopSwapV2(
params.amount,
params.otherAmountThreshold,
params.amountSpecifiedIsInput,
params.aToBOne,
params.aToBTwo,
params.sqrtPriceLimitOne,
params.sqrtPriceLimitTwo,
remainingAccountsInfoTwo,
{
accounts: {
...params,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts: remainingAccountsTwo,
},
),
],
}).buildAndExecute(),
/0x17a7/, // TooManySupplementalTickArrays
);
});
it("go back to the previous tick array", async () => {
const aToB = false;
const initialTickIndex = 256;
const targetTickIndex = 256 + tickSpacing64 * 88 * 1; // --> 1 tick array
const targetSqrtPrice =
PriceMath.tickIndexToSqrtPriceX64(targetTickIndex);
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(256),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(256),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (
await buildTestAquariums(testCtx.whirlpoolCtx, [aqConfig])
)[0];
const startTickIndexes = [-5632, 0, 5632, 11264];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await testCtx.whirlpoolClient.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await testCtx.whirlpoolClient.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// init tick arrays
await (await pool0.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
await (await pool1.initTickArrayForTicks(
startTickIndexes,
))!.buildAndExecute();
// fetch tick arrays
const tickArrays0 = await SwapUtils.getTickArrays(
pool0.getData().tickCurrentIndex,
pool0.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const tickArrays1 = await SwapUtils.getTickArrays(
pool1.getData().tickCurrentIndex,
pool1.getData().tickSpacing,
aToB,
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const quote1 = swapQuoteWithParams(
{
whirlpoolData: pool1.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: U64_MAX,
sqrtPriceLimit: targetSqrtPrice,
tickArrays: tickArrays1,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const quote0 = swapQuoteWithParams(
{
whirlpoolData: pool0.getData(),
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenAmount: quote1.estimatedAmountOut,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrays: tickArrays0,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
assert.ok(quote0.estimatedAmountIn.gtn(0));
assert.ok(quote0.estimatedAmountOut.gtn(0));
assert.ok(quote1.estimatedAmountIn.gtn(0));
assert.ok(quote1.estimatedAmountOut.gtn(0));
const taStart0One = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
0,
).publicKey;
const taStart0Two = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
0,
).publicKey;
const taStartNeg5632One = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
-5632,
).publicKey;
const taStartNeg5632Two = PDAUtil.getTickArray(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
-5632,
).publicKey;
const paramsWithoutSupplemental = {
amount: quote1.estimatedAmountIn,
amountSpecifiedIsInput: true,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
aToBOne: aToB,
aToBTwo: aToB,
oracleOne: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool1.getAddress(),
).publicKey,
oracleTwo: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool0.getAddress(),
).publicKey,
sqrtPriceLimitOne: SwapUtils.getDefaultSqrtPriceLimit(aToB),
sqrtPriceLimitTwo: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArrayOne0: tickArrays1[0].address,
tickArrayOne1: tickArrays1[1].address,
tickArrayOne2: tickArrays1[2].address,
tickArrayTwo0: tickArrays0[0].address,
tickArrayTwo1: tickArrays0[1].address,
tickArrayTwo2: tickArrays0[2].address,
tokenAuthority: testCtx.provider.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
// v2 specific
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
};
// it should start from TA with startTickIndex 0
assert.ok(
(await pool1.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(
(await pool0.refreshData()).tickCurrentIndex === initialTickIndex,
);
assert.ok(paramsWithoutSupplemental.tickArrayOne0.equals(taStart0One));
assert.ok(paramsWithoutSupplemental.tickArrayTwo0.equals(taStart0Two));
// another swap to push tickCurrentIndex to <= -128
const anotherSwapQuoteOne = await swapQuoteByInputToken(
pool1,
pool1.getData().tokenMintA,
new BN(200_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const anotherSwapQuoteTwo = await swapQuoteByInputToken(
pool0,
pool0.getData().tokenMintA,
new BN(90_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
anotherSwapQuoteOne,
testCtx.whirlpoolCtx,
pool1,
aquarium.tokenAccounts[1].account,
aquarium.tokenAccounts[2].account,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
anotherSwapQuoteTwo,
testCtx.whirlpoolCtx,
pool0,
aquarium.tokenAccounts[0].account,
aquarium.tokenAccounts[1].account,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
assert.ok((await pool1.refreshData()).tickCurrentIndex <= -128);
assert.ok((await pool0.refreshData()).tickCurrentIndex <= -128);
const preOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
aquarium.tokenAccounts[0].account,
);
// now tickCurrentIndex was push backed to <= -128, so TickArray with startTickIndex -5632 should be used as the first one
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(
testCtx.whirlpoolCtx.program,
paramsWithoutSupplemental,
),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysOne: [taStartNeg5632One],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysTwo: [taStartNeg5632Two],
}),
).buildAndExecute(),
/0x1787/, // InvalidTickArraySequence
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.twoHopSwapV2Ix(testCtx.whirlpoolCtx.program, {
...paramsWithoutSupplemental,
supplementalTickArraysOne: [taStartNeg5632One],
supplementalTickArraysTwo: [taStartNeg5632Two],
}),
).buildAndExecute();
const postOutputBalance =
await testCtx.whirlpoolCtx.connection.getTokenAccountBalance(
aquarium.tokenAccounts[0].account,
);
// output balance should be increased (actual output will be better than quote due to the push back)
assert.ok(
new BN(postOutputBalance.value.amount)
.sub(new BN(preOutputBalance.value.amount))
.gte(quote0.estimatedAmountOut),
);
assert.ok((await pool1.refreshData()).tickCurrentIndex > 0);
assert.ok((await pool0.refreshData()).tickCurrentIndex > 0);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/integration/multi-ix/splash_pool.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { DecimalUtil, Percentage, U64_MAX } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import type { WhirlpoolClient } from "../../../src";
import {
MAX_SQRT_PRICE_BN,
MAX_TICK_INDEX,
MIN_SQRT_PRICE_BN,
MIN_TICK_INDEX,
PDAUtil,
PriceMath,
SwapUtils,
TickUtil,
WhirlpoolIx,
buildWhirlpoolClient,
increaseLiquidityQuoteByInputToken,
increaseLiquidityQuoteByLiquidityWithParams,
swapQuoteByOutputToken,
swapQuoteWithParams,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { defaultConfirmOptions } from "../../utils/const";
import { initTestPoolWithTokens } from "../../utils/init-utils";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../src/utils/public/token-extension-util";
import { MAX_U64, getTokenBalance } from "../../utils";
interface SharedTestContext {
provider: anchor.AnchorProvider;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
const DEBUG_OUTPUT = false;
describe("splash pool tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
let testCtx: SharedTestContext;
beforeAll(() => {
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
whirlpoolCtx,
whirlpoolClient,
};
});
describe("trades on splash pool", () => {
type TestVariation = {
figure: string;
poolTickSpacing: number;
poolInitialTickIndex: number;
poolLiquidity: BN;
tradeMode: "exactIn" | "exactOut";
tradeDirection: "AtoB" | "BtoA";
tradeTokenAmount: BN;
expectedPartialFill: boolean;
};
const testVariations: TestVariation[] = [
// Notation
//
// l: lower tick index for FullRange
// u: upper tick index for FullRange
// m: MIN_TICK_INDEX (-443636)
// x: MAX_TICK_INDEX (+443636)
// *: liquidity (flat distribution)
// S: trade start
// T: trade end
//
// Limit
//
// 2^33 is almost max liquidity to realize single side deposit at tick index MIN_TICK_INDEX or MAX_TICK_INDEX
// 2^64 is almost max liquidity to realize 50:50 deposit at tick index 0
//
////////////////////////////////////////////////////////////////////////////////
// ExactIn
////////////////////////////////////////////////////////////////////////////////
// ExactIn, BtoA, min to ...
{
figure:
"(toB) |-----mS----l**********T*********|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(20000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|**********T*********u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(200000000000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|********************u----Tx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactIn, AtoB, max to ...
{
figure:
"(toB) |-----m-----l********************|**********T*********u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(20000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----m-----l**********T*********|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(200000000000),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mT----l********************|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactIn, BtoA, 1 to ...
{
figure:
"(toB) |-----m-----l********************|S****T**************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactIn",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64).divn(2),
expectedPartialFill: false,
},
// ExactIn, AtoB, 1 to ...
{
figure:
"(toB) |-----m-----l**************T****S|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactIn",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64).divn(2),
expectedPartialFill: false,
},
////////////////////////////////////////////////////////////////////////////////
// ExactOut
////////////////////////////////////////////////////////////////////////////////
// ExactOut, BtoA, min to ...
{
figure:
"(toB) |-----mS----l**********T*********|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("16583913771126114400"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|**********T*********u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("16587613395589958784"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mS----l********************|********************u----Tx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MIN_TICK_INDEX + 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactOut, AtoB, max to ...
{
figure:
"(toB) |-----m-----l********************|**********T*********u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("16583913770960970547"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----m-----l**********T*********|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("16587613395424814923"),
expectedPartialFill: false,
},
{
figure:
"(toB) |-----mT----l********************|********************u----Sx-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: MAX_TICK_INDEX - 1,
poolLiquidity: powBN(2, 33),
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN(MAX_U64), // partial fill
expectedPartialFill: true,
},
// ExactOut, BtoA, 1 to ...
{
figure:
"(toB) |-----m-----l********************|S****T**************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactOut",
tradeDirection: "BtoA",
tradeTokenAmount: new BN("4604758097518383314"),
expectedPartialFill: false,
},
// ExactOut, AtoB, 1 to ...
{
figure:
"(toB) |-----m-----l**************T****S|********************u-----x-----| (toA)",
poolTickSpacing: 32768 + 128,
poolInitialTickIndex: 0,
poolLiquidity: powBN(2, 63), // to use the remaining 2^63 amount in the trade
tradeMode: "exactOut",
tradeDirection: "AtoB",
tradeTokenAmount: new BN("4604758097518383314"),
expectedPartialFill: false,
},
];
testVariations.forEach((variation) => {
const caseName = `${variation.figure}, mode=${variation.tradeMode}, liq=${variation.poolLiquidity}, amount=${variation.tradeTokenAmount}`;
it(caseName, async () => {
const {
poolTickSpacing,
poolInitialTickIndex,
poolLiquidity,
tradeMode,
tradeDirection,
tradeTokenAmount,
} = variation;
const tradeAmountSpecifiedIsInput = tradeMode === "exactIn";
const tradeAToB = tradeDirection === "AtoB";
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
// SplashPool has only 2 TickArrays for negative and positive ticks
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
debug(
`pool state: tick = ${pool.getData().tickCurrentIndex}, liquidity = ${depositQuote.liquidityAmount.toString()}, tokenA = ${depositQuote.tokenEstA.toString()}, tokenB = ${depositQuote.tokenEstB.toString()}`,
);
const swapQuote = swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
);
const preTickIndex = pool.getData().tickCurrentIndex;
const [preOwnerA, preOwnerB] = await getTokenBalances(
tokenAccountA,
tokenAccountB,
);
const [preVaultA, preVaultB] = await getTokenBalances(
pool.getData().tokenVaultA,
pool.getData().tokenVaultB,
);
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(
testCtx.whirlpoolCtx.program,
SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
swapQuote.aToB ? tokenAccountA : tokenAccountB,
swapQuote.aToB ? tokenAccountB : tokenAccountA,
testCtx.provider.wallet.publicKey,
),
),
).buildAndExecute();
await pool.refreshData(); // reflect new tickCurrentIndex
const postTickIndex = pool.getData().tickCurrentIndex;
const [postOwnerA, postOwnerB] = await getTokenBalances(
tokenAccountA,
tokenAccountB,
);
const [postVaultA, postVaultB] = await getTokenBalances(
pool.getData().tokenVaultA,
pool.getData().tokenVaultB,
);
// display pre & post
debug(`amount: ${tradeTokenAmount.toString()}`);
debug(
`estimate: ${swapQuote.estimatedAmountIn.toString()} --> ${swapQuote.estimatedAmountOut.toString()}`,
);
debug(
`owner: A = ${preOwnerA.toString()} -> ${postOwnerA.toString()}, B = ${preOwnerB.toString()} -> ${postOwnerB.toString()}`,
);
debug(
`vault: A = ${preVaultA.toString()} -> ${postVaultA.toString()}, B = ${preVaultB.toString()} -> ${postVaultB.toString()}`,
);
debug(`tick index: ${preTickIndex} --> ${postTickIndex}`);
// verify: partial fill
const actualAmount = swapQuote.amountSpecifiedIsInput
? swapQuote.estimatedAmountIn
: swapQuote.estimatedAmountOut;
if (variation.expectedPartialFill) {
assert.ok(actualAmount.lt(tradeTokenAmount));
} else {
assert.ok(actualAmount.eq(tradeTokenAmount));
}
// verify: quote on SDK == realized trade
const diffOwnerA = postOwnerA.sub(preOwnerA);
const diffOwnerB = postOwnerB.sub(preOwnerB);
const diffVaultA = postVaultA.sub(preVaultA);
const diffVaultB = postVaultB.sub(preVaultB);
debug(
`diff: owner A = ${diffOwnerA.toString()}, owner B = ${diffOwnerB.toString()}`,
);
debug(
`estimated: in = ${swapQuote.estimatedAmountIn.toString()}, out = ${swapQuote.estimatedAmountOut.toString()}`,
);
debug(
`sqrtPrice: quote = ${swapQuote.estimatedEndSqrtPrice.toString()}, pool = ${pool.getData().sqrtPrice.toString()}`,
);
assert.ok(diffOwnerA.eq(diffVaultA.neg()));
assert.ok(diffOwnerB.eq(diffVaultB.neg()));
assert.ok(
diffOwnerA.eq(
tradeAToB
? swapQuote.estimatedAmountIn.neg()
: swapQuote.estimatedAmountOut,
),
);
assert.ok(
diffOwnerB.eq(
tradeAToB
? swapQuote.estimatedAmountOut
: swapQuote.estimatedAmountIn.neg(),
),
);
assert.ok(swapQuote.estimatedEndSqrtPrice.eq(pool.getData().sqrtPrice));
assert.ok(
swapQuote.estimatedEndTickIndex === pool.getData().tickCurrentIndex,
);
});
});
});
async function getTokenBalances(
tokenAccountA: PublicKey,
tokenAccountB: PublicKey,
): Promise<[BN, BN]> {
const tokenVaultA = new anchor.BN(
await getTokenBalance(provider, tokenAccountA),
);
const tokenVaultB = new anchor.BN(
await getTokenBalance(provider, tokenAccountB),
);
return [tokenVaultA, tokenVaultB];
}
describe("ExactOut overflow (required input token is over u64 max)", () => {
// Since trade mode is ExactOut, the outputt amount must be within u64 max, but the input token may over u64 max.
// It is okay to fail with overflow error because the trade is impossible.
// B to A (too much tokenB is required)
it("(toB) |-----m-----l********************|S******************Tu-----x-----| (toA), too much tokenB is required", async () => {
const poolTickSpacing = 32768 + 128;
const poolInitialTickIndex = 0;
const poolLiquidity = powBN(2, 34);
const tradeAmountSpecifiedIsInput = false;
const tradeAToB = false;
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
// try to output all tokenA
const tradeTokenAmount = depositQuote.tokenEstA;
await assert.rejects(
async () =>
swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
),
/MulShiftRight overflowed u128/, // at getAmountUnfixedDelta for tokenB (too much tokenB is required)
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
amount: tradeTokenAmount,
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tokenAuthority: testCtx.provider.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: pool.getData().tokenVaultA,
tokenVaultB: pool.getData().tokenVaultB,
whirlpool: pool.getAddress(),
tickArray0: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray1: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray2: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
oracle: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
).publicKey,
}),
).buildAndExecute(),
/MultiplicationShiftRightOverflow/, // at get_amount_unfixed_delta for tokenB (too much tokenB is required)
);
});
// A to B (too much tokenA is required)
it("(toB) |-----m-----lT******************S|********************u-----x-----| (toA), too much tokenA is required", async () => {
const poolTickSpacing = 32768 + 128;
const poolInitialTickIndex = 0;
const poolLiquidity = powBN(2, 34);
const tradeAmountSpecifiedIsInput = false;
const tradeAToB = true;
const { whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
poolTickSpacing,
PriceMath.tickIndexToSqrtPriceX64(poolInitialTickIndex),
MAX_U64,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
await (await pool.initTickArrayForTicks([-1, +1]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// provide liquidity
const depositQuote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity: poolLiquidity,
slippageTolerance: Percentage.fromFraction(0, 100),
sqrtPrice: pool.getData().sqrtPrice,
tickCurrentIndex: pool.getData().tickCurrentIndex,
tickLowerIndex: fullRange[0],
tickUpperIndex: fullRange[1],
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
});
const txAndMint = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuote,
);
await txAndMint.tx.buildAndExecute();
await pool.refreshData(); // reflect new liquidity
// try to output all tokenB
const tradeTokenAmount = depositQuote.tokenEstB;
await assert.rejects(
async () =>
swapQuoteWithParams(
{
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
tradeAmountSpecifiedIsInput,
),
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tickArrays: await SwapUtils.getTickArrays(
pool.getData().tickCurrentIndex,
pool.getData().tickSpacing,
tradeAToB,
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
),
tokenAmount: tradeTokenAmount,
whirlpoolData: pool.getData(),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT,
},
Percentage.fromFraction(0, 100),
),
/Results larger than U64/, // at getAmountUnfixedDelta for tokenA (too much tokenA is required)
);
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
amount: tradeTokenAmount,
amountSpecifiedIsInput: tradeAmountSpecifiedIsInput,
aToB: tradeAToB,
otherAmountThreshold: U64_MAX,
sqrtPriceLimit: tradeAToB ? MIN_SQRT_PRICE_BN : MAX_SQRT_PRICE_BN,
tokenAuthority: testCtx.provider.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: pool.getData().tokenVaultA,
tokenVaultB: pool.getData().tokenVaultB,
whirlpool: pool.getAddress(),
tickArray0: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
).publicKey,
tickArray1: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
-1,
).publicKey,
tickArray2: PDAUtil.getTickArrayFromTickIndex(
0,
poolTickSpacing,
pool.getAddress(),
testCtx.whirlpoolCtx.program.programId,
-1,
).publicKey,
oracle: PDAUtil.getOracle(
testCtx.whirlpoolCtx.program.programId,
pool.getAddress(),
).publicKey,
}),
).buildAndExecute(),
/TokenMaxExceeded/, // at get_amount_unfixed_delta for tokenA (too much tokenA is required)
);
});
});
it("ExactOut Sandwitch attack senario", async () => {
const tickSpacingSplash128 = 32768 + 128;
const { poolInitInfo, whirlpoolPda, tokenAccountA, tokenAccountB } =
await initTestPoolWithTokens(
testCtx.whirlpoolCtx,
tickSpacingSplash128,
PriceMath.tickIndexToSqrtPriceX64(0), // 1 B/A
new BN(2_000_000_000),
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
// [-2,894,848 ][0 ][
await (await pool.initTickArrayForTicks([
// SplashPool has only 2 TickArrays for negative and positive ticks
-1, +1,
]))!.buildAndExecute();
const fullRange = TickUtil.getFullRangeTickIndex(
pool.getData().tickSpacing,
);
// create 2 position (small & large)
const depositQuoteSmall = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(1), 0), // very thin liquidity
fullRange[0],
fullRange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
const small = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuoteSmall,
);
await small.tx.buildAndExecute();
const depositQuoteLarge = increaseLiquidityQuoteByInputToken(
poolInitInfo.tokenMintB,
DecimalUtil.fromBN(new BN(1_000_000_000), 0), // extremely larger than small position
fullRange[0],
fullRange[1],
Percentage.fromFraction(0, 100),
pool,
NO_TOKEN_EXTENSION_CONTEXT,
);
const large = await pool.openPosition(
fullRange[0],
fullRange[1],
depositQuoteLarge,
);
await large.tx.buildAndExecute();
await pool.refreshData();
const preLiquidity = pool.getData().liquidity;
// get quote with small and large position liquidity
const swapQuote = await swapQuoteByOutputToken(
pool,
poolInitInfo.tokenMintB,
new BN(800_000_000),
Percentage.fromFraction(0, 100),
testCtx.whirlpoolCtx.program.programId,
testCtx.whirlpoolCtx.fetcher,
IGNORE_CACHE,
);
const params = SwapUtils.getSwapParamsFromQuote(
swapQuote,
testCtx.whirlpoolCtx,
pool,
tokenAccountA,
tokenAccountB,
testCtx.provider.wallet.publicKey,
);
// close large position
const largePosition = PDAUtil.getPosition(
testCtx.whirlpoolCtx.program.programId,
large.positionMint,
).publicKey;
const closeTx = await pool.closePosition(
largePosition,
Percentage.fromFraction(0, 100),
);
for (const tx of closeTx) {
await tx.buildAndExecute();
}
// liquidity should be decreased
await pool.refreshData();
const postLiquidity = pool.getData().liquidity;
assert.ok(preLiquidity.gt(postLiquidity));
const [preA, preB] = await getTokenBalances(tokenAccountA, tokenAccountB);
// with sqrtPriceLimit = 0, partial fill will be rejected
// so trade will be protected from sandwich attack if sqrtPriceLimit = 0 is used.
await assert.rejects(
toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
sqrtPriceLimit: new BN(0),
}),
).buildAndExecute(),
/0x17a9/, // PartialFillError
);
// with sqrtPriceLimit != 0, partial fill will be allowed
await toTx(
testCtx.whirlpoolCtx,
WhirlpoolIx.swapIx(testCtx.whirlpoolCtx.program, {
...params,
sqrtPriceLimit: MIN_SQRT_PRICE_BN,
}),
).buildAndExecute();
const [postA, postB] = await getTokenBalances(tokenAccountA, tokenAccountB);
await pool.refreshData();
// input (partial)
assert.ok(preA.sub(postA).lt(swapQuote.estimatedAmountIn));
// output (partial)
assert.ok(postB.sub(preB).lt(swapQuote.estimatedAmountOut));
// hit min
assert.ok(pool.getData().sqrtPrice.eq(MIN_SQRT_PRICE_BN));
});
});
function powBN(base: number, exp: number): BN {
return new BN(base).pow(new BN(exp));
}
function debug(msg: string) {
if (!DEBUG_OUTPUT) return;
console.debug(msg);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/const.ts
|
import type { ConfirmOptions } from "@solana/web3.js";
export const defaultConfirmOptions: ConfirmOptions = {
commitment: "confirmed",
preflightCommitment: "confirmed",
};
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/testDataTypes.ts
|
import { ZERO } from "@orca-so/common-sdk";
import { Keypair, PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import invariant from "tiny-invariant";
import type {
PositionBundleData,
TickArray,
TickArrayData,
TickData,
WhirlpoolContext,
} from "../../src";
import {
PDAUtil,
POSITION_BUNDLE_SIZE,
PriceMath,
TICK_ARRAY_SIZE,
} from "../../src";
import type { WhirlpoolAccountFetcherInterface } from "../../src/network/public/fetcher";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
export const testWhirlpoolData = {
whirlpoolsConfig: Keypair.generate().publicKey,
whirlpoolBump: [],
feeRate: 300,
protocolFeeRate: 1800,
liquidity: new BN("32523523532"),
sqrtPrice: new BN("32523523532"),
tickCurrentIndex: PriceMath.sqrtPriceX64ToTickIndex(new BN("32523523532")),
protocolFeeOwedA: new BN("2314532532"),
protocolFeeOwedB: new BN("2314532532"),
tokenMintA: Keypair.generate().publicKey,
tokenVaultA: Keypair.generate().publicKey,
feeGrowthGlobalA: new BN("32532523523523523"),
tokenMintB: Keypair.generate().publicKey,
tokenVaultB: Keypair.generate().publicKey,
feeGrowthGlobalB: new BN("32532523523523523"),
rewardLastUpdatedTimestamp: new BN("3253252312412523523523"),
rewardInfos: [],
tickSpacing: 64,
};
export const testInitializedTickData: TickData = {
feeGrowthOutsideA: ZERO,
feeGrowthOutsideB: ZERO,
initialized: true,
liquidityGross: ZERO,
liquidityNet: ZERO,
rewardGrowthsOutside: [ZERO, ZERO],
};
export const testUninitializedTickData: TickData = {
feeGrowthOutsideA: ZERO,
feeGrowthOutsideB: ZERO,
liquidityGross: ZERO,
liquidityNet: ZERO,
initialized: false,
rewardGrowthsOutside: [ZERO, ZERO],
};
export const testTickArrayData: TickArrayData = {
startTickIndex: 0,
ticks: Array(TICK_ARRAY_SIZE).fill(testUninitializedTickData),
whirlpool: PublicKey.default,
};
export const buildTickArrayData = (
startTick: number,
initializedOffsets: number[],
): TickArray => {
const result = {
ticks: Array(TICK_ARRAY_SIZE).fill(testUninitializedTickData),
whirlpool: PublicKey.default,
startTickIndex: startTick,
};
initializedOffsets.forEach((offset) => {
if (offset >= TICK_ARRAY_SIZE) {
throw new Error(
`Cannot build tick-array with initialized offset - ${offset}`,
);
}
result.ticks[offset] = testInitializedTickData;
});
const randomAddr = Keypair.generate().publicKey;
return { address: randomAddr, startTickIndex: startTick, data: result };
};
export async function getTickArrays(
startIndices: number[],
ctx: WhirlpoolContext,
whirlpoolKey: PublicKey,
fetcher: WhirlpoolAccountFetcherInterface,
): Promise<TickArray[]> {
const tickArrayPdas = startIndices.map((value) =>
PDAUtil.getTickArray(ctx.program.programId, whirlpoolKey, value),
);
const tickArrayAddresses = tickArrayPdas.map((pda) => pda.publicKey);
const tickArrays = await fetcher.getTickArrays(
tickArrayAddresses,
IGNORE_CACHE,
);
return tickArrayAddresses.map((addr, index) => {
return {
address: addr,
startTickIndex: startIndices[index],
data: tickArrays[index],
};
});
}
export const buildPositionBundleData = (
occupiedBundleIndexes: number[],
): PositionBundleData => {
invariant(
POSITION_BUNDLE_SIZE % 8 == 0,
"POSITION_BUNDLE_SIZE should be multiple of 8",
);
const positionBundleMint = Keypair.generate().publicKey;
const positionBitmap: number[] = new Array(POSITION_BUNDLE_SIZE / 8).fill(0);
occupiedBundleIndexes.forEach((bundleIndex) => {
const index = Math.floor(bundleIndex / 8);
const offset = bundleIndex % 8;
positionBitmap[index] = positionBitmap[index] | (1 << offset);
});
return { positionBundleMint, positionBitmap };
};
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/test-consts.ts
|
import * as anchor from "@coral-xyz/anchor";
import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import BN from "bn.js";
export const TEST_TOKEN_PROGRAM_ID = new anchor.web3.PublicKey(
TOKEN_PROGRAM_ID.toString(),
);
export const TEST_TOKEN_2022_PROGRAM_ID = new anchor.web3.PublicKey(
TOKEN_2022_PROGRAM_ID.toString(),
);
// sdk/tests/external_program/transfer_hook_counter.so
export const TEST_TRANSFER_HOOK_PROGRAM_ID = new anchor.web3.PublicKey(
"EBZDYx7599krFc4m2govwBdZcicr4GgepqC78m71nsHS",
);
export const ZERO_BN = new anchor.BN(0);
export const ONE_SOL = 1000000000;
export const MAX_U64 = new BN(
new anchor.BN(2).pow(new anchor.BN(64)).sub(new anchor.BN(1)).toString(),
);
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/metaplex.ts
|
// To eliminate deps on @metaplex-foundation/mpl-token-metadata
// Copied from https://github.com/orca-so/orca-sdks/blob/main/packages/token-sdk/src/metadata/client/metaplex-client.ts
import { PublicKey } from "@solana/web3.js";
import invariant from "tiny-invariant";
const METADATA_PROGRAM_ID = new PublicKey(
"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s",
);
// Metadata should be a just tiny JSON file, 2000ms should be sufficient for most cases
const DEFAULT_GET_OFF_CHAIN_METADATA_TIMEOUT_MS = 2000;
interface Creator {
address: PublicKey;
verified: boolean;
share: number;
}
interface Collection {
verified: boolean;
key: PublicKey;
}
interface Uses {
useMethod: number;
remaining: bigint;
total: bigint;
}
interface OnChainMetadataPrefix {
key: number;
updateAuthority: PublicKey;
mint: PublicKey;
name: string;
symbol: string;
uri: string;
sellerFeeBasisPoints: number;
}
interface OnChainMetadataCreators {
creators: Creator[];
}
interface OnChainMetadataSuffix {
primarySaleHappened: boolean;
isMutable: boolean;
editionNonce: number | null;
tokenStandard: number | null;
collection: Collection | null;
uses: Uses | null;
}
export type OnChainMetadata = OnChainMetadataPrefix &
OnChainMetadataCreators &
OnChainMetadataSuffix;
export interface OffChainMetadata {
name?: string;
symbol?: string;
description?: string;
image?: string;
}
export interface MetaplexClient {
getMetadataAddress(mint: PublicKey): PublicKey;
parseOnChainMetadata(
mint: PublicKey,
buffer: Buffer | Uint8Array,
): OnChainMetadata | null;
getOffChainMetadata(
metadata: OnChainMetadata,
timeoutMs?: number,
): Promise<OffChainMetadata | null>;
}
export class MetaplexHttpClient implements MetaplexClient {
getMetadataAddress(mint: PublicKey): PublicKey {
const seeds = [
Buffer.from("metadata"),
METADATA_PROGRAM_ID.toBuffer(),
mint.toBuffer(),
];
return PublicKey.findProgramAddressSync(seeds, METADATA_PROGRAM_ID)[0];
}
parseOnChainMetadata(
mint: PublicKey,
data: Uint8Array | Buffer,
): OnChainMetadata | null {
try {
const buffer = Buffer.from(data);
const [prefix, creatorsOffset] = parseOnChainMetadataPrefix(buffer, 0);
const [creators, suffixOffset] = parseOnChainMetadataCreators(
buffer,
creatorsOffset,
);
const [suffix] = parseOnChainMetadataSuffix(buffer, suffixOffset);
return { ...prefix, ...creators, ...suffix };
} catch {
console.error(`Failed to parse onchain metadata for ${mint}`);
return null;
}
}
async getOffChainMetadata(
metadata: OnChainMetadata,
timeoutMs: number = DEFAULT_GET_OFF_CHAIN_METADATA_TIMEOUT_MS,
): Promise<OffChainMetadata | null> {
try {
if (metadata.uri === "") {
return null;
}
const response = await fetch(metadata.uri, {
signal: AbortSignal.timeout(timeoutMs),
});
if (response.status === 404) {
return null;
}
invariant(
response.ok,
`Unexpected status code fetching ${metadata.uri}: ${response.status}`,
);
const json = await response.json();
invariant(
isMetadataResponse(json),
"Unexpected offchain metadata response type",
);
return json;
} catch {
console.error(`Failed to fetch offchain metadata for ${metadata.mint}`);
return null;
}
}
}
function readString(buffer: Buffer, offset: number): string {
const readLength = buffer.readUInt32LE(offset);
const bytes = buffer.subarray(offset + 4, offset + 4 + readLength);
const nullIndex = bytes.indexOf(0);
return new TextDecoder().decode(
bytes.subarray(0, nullIndex === -1 ? undefined : nullIndex),
);
}
function parseOnChainMetadataPrefix(
buffer: Buffer,
offset: number,
): [OnChainMetadataPrefix, number] {
const key = buffer.readUInt8(offset);
offset += 1;
const updateAuthority = new PublicKey(buffer.subarray(offset, offset + 32));
offset += 32;
const mint = new PublicKey(buffer.subarray(offset, offset + 32));
offset += 32;
const name = readString(buffer, offset);
offset += 36;
const symbol = readString(buffer, offset);
offset += 14;
const uri = readString(buffer, offset);
offset += 204;
const sellerFeeBasisPoints = buffer.readUInt16LE(offset);
offset += 2;
return [
{ key, updateAuthority, mint, name, symbol, uri, sellerFeeBasisPoints },
offset,
];
}
function parseOnChainMetadataCreators(
buffer: Buffer,
offset: number,
): [OnChainMetadataCreators, number] {
const creatorsPresent = !!buffer.readUInt8(offset);
offset += 1;
if (!creatorsPresent) {
return [{ creators: [] }, offset];
}
const creatorCount = buffer.readUInt16LE(offset);
offset += 4;
let creators: Creator[] = [];
for (let i = 0; i < creatorCount; i++) {
const address = new PublicKey(buffer.subarray(offset, offset + 32));
offset += 32;
const verified = !!buffer.readUInt8(offset);
offset += 1;
const share = buffer.readUInt8(offset);
offset += 1;
creators.push({ address, verified, share });
}
return [{ creators }, offset];
}
function parseOnChainMetadataSuffix(
buffer: Buffer,
offset: number,
): [OnChainMetadataSuffix, number] {
const primarySaleHappened = !!buffer.readUInt8(offset);
offset += 1;
const isMutable = !!buffer.readUInt8(offset);
offset += 1;
const editionNoncePresent = !!buffer.readUInt8(offset);
offset += 1;
let editionNonce: number | null = null;
if (editionNoncePresent) {
editionNonce = editionNoncePresent ? buffer.readUInt8(offset) : null;
offset += 1;
}
const tokenStandardPresent = !!buffer.readUInt8(offset);
offset += 1;
let tokenStandard: number | null = null;
if (tokenStandardPresent) {
tokenStandard = tokenStandardPresent ? buffer.readUInt8(offset) : null;
offset += 1;
}
const collectionPresent = !!buffer.readUInt8(offset);
offset += 1;
let collection: Collection | null = null;
if (collectionPresent) {
const collectionVerified = !!buffer.readUInt8(offset);
offset += 1;
const collectionKey = new PublicKey(buffer.subarray(offset, offset + 32));
offset += 32;
collection = collectionPresent
? { verified: collectionVerified, key: collectionKey }
: null;
}
const usesPresent = !!buffer.readUInt8(offset);
offset += 1;
let uses: Uses | null = null;
if (usesPresent) {
const useMethod = buffer.readUInt8(offset);
offset += 1;
const remaining = buffer.readBigUInt64LE(offset);
offset += 8;
const total = buffer.readBigUInt64LE(offset);
offset += 8;
uses = usesPresent ? { useMethod, remaining, total } : null;
}
return [
{
primarySaleHappened,
isMutable,
editionNonce,
tokenStandard,
collection,
uses,
},
offset,
];
}
function isMetadataResponse(value: unknown): value is OffChainMetadata {
if (!value || typeof value !== "object") {
return false;
}
if ("name" in value && typeof value.name !== "string") {
return false;
}
if ("image" in value && typeof value.image !== "string") {
return false;
}
if ("description" in value && typeof value.description !== "string") {
return false;
}
if ("symbol" in value && typeof value.symbol !== "string") {
return false;
}
return true;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/test-builders.ts
|
import type { AnchorProvider } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { AddressUtil, MathUtil, Percentage } from "@orca-so/common-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import Decimal from "decimal.js";
import { createAndMintToAssociatedTokenAccount, createMint } from ".";
import type {
InitConfigParams,
InitFeeTierParams,
InitPoolParams,
InitTickArrayParams,
OpenBundledPositionParams,
OpenPositionParams,
Whirlpool,
} from "../../src";
import {
IGNORE_CACHE,
PDAUtil,
PoolUtil,
PriceMath,
increaseLiquidityQuoteByInputTokenUsingPriceSlippage,
} from "../../src";
import type { WhirlpoolContext } from "../../src/context";
import { TokenExtensionUtil } from "../../src/utils/public/token-extension-util";
import type { OpenPositionWithTokenExtensionsParams } from "../../src/instructions";
export interface TestWhirlpoolsConfigKeypairs {
feeAuthorityKeypair: Keypair;
collectProtocolFeesAuthorityKeypair: Keypair;
rewardEmissionsSuperAuthorityKeypair: Keypair;
}
export interface TestConfigParams {
configInitInfo: InitConfigParams;
configKeypairs: TestWhirlpoolsConfigKeypairs;
}
export const generateDefaultConfigParams = (
context: WhirlpoolContext,
funder?: PublicKey,
): TestConfigParams => {
const configKeypairs: TestWhirlpoolsConfigKeypairs = {
feeAuthorityKeypair: Keypair.generate(),
collectProtocolFeesAuthorityKeypair: Keypair.generate(),
rewardEmissionsSuperAuthorityKeypair: Keypair.generate(),
};
const configInitInfo = {
whirlpoolsConfigKeypair: Keypair.generate(),
feeAuthority: configKeypairs.feeAuthorityKeypair.publicKey,
collectProtocolFeesAuthority:
configKeypairs.collectProtocolFeesAuthorityKeypair.publicKey,
rewardEmissionsSuperAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
defaultProtocolFeeRate: 300,
funder: funder || context.wallet.publicKey,
};
return { configInitInfo, configKeypairs };
};
export const createInOrderMints = async (
context: WhirlpoolContext,
reuseTokenA?: PublicKey,
) => {
const provider = context.provider;
const tokenXMintPubKey = reuseTokenA ?? (await createMint(provider));
// ensure reuseTokenA is the first mint if reuseTokenA is provided
let ordered;
do {
const tokenYMintPubKey = await createMint(provider);
ordered = PoolUtil.orderMints(tokenXMintPubKey, tokenYMintPubKey).map(
AddressUtil.toPubKey,
);
} while (!!reuseTokenA && !ordered[0].equals(reuseTokenA));
return ordered;
};
export const generateDefaultInitPoolParams = async (
context: WhirlpoolContext,
configKey: PublicKey,
feeTierKey: PublicKey,
tickSpacing: number,
initSqrtPrice = MathUtil.toX64(new Decimal(5)),
funder?: PublicKey,
reuseTokenA?: PublicKey,
): Promise<InitPoolParams> => {
const [tokenAMintPubKey, tokenBMintPubKey] = await createInOrderMints(
context,
reuseTokenA,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
context.program.programId,
configKey,
tokenAMintPubKey,
tokenBMintPubKey,
tickSpacing,
);
return {
initSqrtPrice,
whirlpoolsConfig: configKey,
tokenMintA: tokenAMintPubKey,
tokenMintB: tokenBMintPubKey,
whirlpoolPda,
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
feeTierKey,
tickSpacing,
funder: funder || context.wallet.publicKey,
};
};
export const generateDefaultInitFeeTierParams = (
context: WhirlpoolContext,
whirlpoolsConfigKey: PublicKey,
whirlpoolFeeAuthority: PublicKey,
tickSpacing: number,
defaultFeeRate: number,
funder?: PublicKey,
): InitFeeTierParams => {
const feeTierPda = PDAUtil.getFeeTier(
context.program.programId,
whirlpoolsConfigKey,
tickSpacing,
);
return {
feeTierPda,
whirlpoolsConfig: whirlpoolsConfigKey,
tickSpacing,
defaultFeeRate,
feeAuthority: whirlpoolFeeAuthority,
funder: funder || context.wallet.publicKey,
};
};
export const generateDefaultInitTickArrayParams = (
context: WhirlpoolContext,
whirlpool: PublicKey,
startTick: number,
funder?: PublicKey,
): InitTickArrayParams => {
const tickArrayPda = PDAUtil.getTickArray(
context.program.programId,
whirlpool,
startTick,
);
return {
whirlpool,
tickArrayPda: tickArrayPda,
startTick,
funder: funder || context.wallet.publicKey,
};
};
export async function generateDefaultOpenPositionParams(
context: WhirlpoolContext,
whirlpool: PublicKey,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey,
funder?: PublicKey,
): Promise<{
params: Required<OpenPositionParams & { metadataPda: PDA }>;
mint: Keypair;
}> {
const positionMintKeypair = Keypair.generate();
const positionPda = PDAUtil.getPosition(
context.program.programId,
positionMintKeypair.publicKey,
);
const metadataPda = PDAUtil.getPositionMetadata(
positionMintKeypair.publicKey,
);
const positionTokenAccountAddress = getAssociatedTokenAddressSync(
positionMintKeypair.publicKey,
owner,
);
const params: Required<OpenPositionParams & { metadataPda: PDA }> = {
funder: funder || context.wallet.publicKey,
owner: owner,
positionPda,
metadataPda,
positionMintAddress: positionMintKeypair.publicKey,
positionTokenAccount: positionTokenAccountAddress,
whirlpool: whirlpool,
tickLowerIndex,
tickUpperIndex,
};
return {
params,
mint: positionMintKeypair,
};
}
export async function generateDefaultOpenPositionWithTokenExtensionsParams(
context: WhirlpoolContext,
whirlpool: PublicKey,
withTokenMetadataExtension: boolean,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey,
funder?: PublicKey,
): Promise<{
params: OpenPositionWithTokenExtensionsParams;
mint: Keypair;
}> {
const positionMintKeypair = Keypair.generate();
const positionPda = PDAUtil.getPosition(
context.program.programId,
positionMintKeypair.publicKey,
);
// Mint is based on Token-2022, so TokenAccount is also based on Token-2022.
const positionTokenAccount2022Address = getAssociatedTokenAddressSync(
positionMintKeypair.publicKey,
owner,
true,
TOKEN_2022_PROGRAM_ID, // token program id
);
return {
params: {
funder: funder || context.wallet.publicKey,
owner: owner,
positionPda,
positionMint: positionMintKeypair.publicKey,
positionTokenAccount: positionTokenAccount2022Address,
whirlpool: whirlpool,
tickLowerIndex,
tickUpperIndex,
withTokenMetadataExtension,
},
mint: positionMintKeypair,
};
}
export async function mintTokensToTestAccount(
provider: AnchorProvider,
tokenAMint: PublicKey,
tokenMintForA: number,
tokenBMint: PublicKey,
tokenMintForB: number,
destinationWallet?: PublicKey,
) {
const userTokenAAccount = await createAndMintToAssociatedTokenAccount(
provider,
tokenAMint,
tokenMintForA,
destinationWallet,
);
const userTokenBAccount = await createAndMintToAssociatedTokenAccount(
provider,
tokenBMint,
tokenMintForB,
destinationWallet,
);
return [userTokenAAccount, userTokenBAccount];
}
export async function initPosition(
ctx: WhirlpoolContext,
pool: Whirlpool,
lowerPrice: Decimal,
upperPrice: Decimal,
inputTokenMint: PublicKey,
inputTokenAmount: number,
sourceWallet?: Keypair,
withTokenExtensions: boolean = false,
) {
const sourceWalletKey = sourceWallet
? sourceWallet.publicKey
: ctx.wallet.publicKey;
const tokenADecimal = pool.getTokenAInfo().decimals;
const tokenBDecimal = pool.getTokenBInfo().decimals;
const tickSpacing = pool.getData().tickSpacing;
const lowerTick = PriceMath.priceToInitializableTickIndex(
lowerPrice,
tokenADecimal,
tokenBDecimal,
tickSpacing,
);
const upperTick = PriceMath.priceToInitializableTickIndex(
upperPrice,
tokenADecimal,
tokenBDecimal,
tickSpacing,
);
const quote = await increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
inputTokenMint,
new Decimal(inputTokenAmount),
lowerTick,
upperTick,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
// [Action] Open Position (and increase L)
const { positionMint, tx } = await pool.openPosition(
lowerTick,
upperTick,
quote,
sourceWalletKey,
ctx.wallet.publicKey,
undefined,
withTokenExtensions ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID,
);
if (sourceWallet) {
tx.addSigner(sourceWallet);
}
await tx.buildAndExecute();
return {
positionMint,
positionAddress: PDAUtil.getPosition(ctx.program.programId, positionMint),
};
}
export async function generateDefaultOpenBundledPositionParams(
context: WhirlpoolContext,
whirlpool: PublicKey,
positionBundleMint: PublicKey,
bundleIndex: number,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey,
funder?: PublicKey,
): Promise<{ params: Required<OpenBundledPositionParams> }> {
const bundledPositionPda = PDAUtil.getBundledPosition(
context.program.programId,
positionBundleMint,
bundleIndex,
);
const positionBundle = PDAUtil.getPositionBundle(
context.program.programId,
positionBundleMint,
).publicKey;
const positionBundleTokenAccount = getAssociatedTokenAddressSync(
positionBundleMint,
owner,
);
const params: Required<OpenBundledPositionParams> = {
bundleIndex,
bundledPositionPda,
positionBundle,
positionBundleAuthority: owner,
funder: funder || owner,
positionBundleTokenAccount,
whirlpool: whirlpool,
tickLowerIndex,
tickUpperIndex,
};
return {
params,
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/utils.ts
|
import type { AnchorProvider } from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { TransactionBuilder } from "@orca-so/common-sdk";
export function systemTransferTx(
provider: AnchorProvider,
toPubkey: web3.PublicKey,
lamports: number,
): TransactionBuilder {
return new TransactionBuilder(
provider.connection,
provider.wallet,
).addInstruction({
instructions: [
web3.SystemProgram.transfer({
fromPubkey: provider.wallet.publicKey,
toPubkey,
lamports,
}),
],
cleanupInstructions: [],
signers: [],
});
}
export function sleep(ms: number): Promise<unknown> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/pool-utils.test.ts
|
import { PublicKey } from "@solana/web3.js";
import { PoolUtil } from "../../src/utils/public/pool-utils";
import * as assert from "assert";
const MINTS: { [symbol: string]: PublicKey } = {
FTM: new PublicKey("EsPKhGTMf3bGoy4Qm7pCv3UCcWqAmbC1UGHBTDxRjjD4"),
SOL: new PublicKey("So11111111111111111111111111111111111111112"),
mSOL: new PublicKey("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So"),
USDH: new PublicKey("USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX"),
stSOL: new PublicKey("7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj"),
BTC: new PublicKey("9n4nbM75f5Ui33ZbPYXn59EwSgE8CGsHtAeTH5YFeJ9E"),
whETH: new PublicKey("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs"),
USDC: new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
USDT: new PublicKey("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"),
ORCA: new PublicKey("orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE"),
};
describe("determine base quote token ordering", () => {
it("USD stables", async () => {
// USDC/FTM => FTM/USDC
let pair = PoolUtil.toBaseQuoteOrder(MINTS.USDC, MINTS.FTM);
assert.equal(MINTS.FTM, pair[0]);
assert.equal(MINTS.USDC, pair[1]);
// USDT/USDC => USDC/USDT
pair = PoolUtil.toBaseQuoteOrder(MINTS.USDT, MINTS.USDC);
assert.equal(MINTS.USDC, pair[0]);
assert.equal(MINTS.USDT, pair[1]);
// USDH/stSOL => stSOL/USDH
pair = PoolUtil.toBaseQuoteOrder(MINTS.USDH, MINTS.stSOL);
assert.equal(MINTS.stSOL, pair[0]);
assert.equal(MINTS.USDH, pair[1]);
});
it("SOL variants", async () => {
// SOL/mSOL => mSOL/SOL
let pair = PoolUtil.toBaseQuoteOrder(MINTS.SOL, MINTS.mSOL);
assert.equal(MINTS.mSOL, pair[0]);
assert.equal(MINTS.SOL, pair[1]);
// mSOL/BTC => BTC/mSOL
pair = PoolUtil.toBaseQuoteOrder(MINTS.mSOL, MINTS.BTC);
assert.equal(MINTS.BTC, pair[0]);
assert.equal(MINTS.mSOL, pair[1]);
// mSOL/whETH => whETH/mSOL
pair = PoolUtil.toBaseQuoteOrder(MINTS.mSOL, MINTS.whETH);
assert.equal(MINTS.whETH, pair[0]);
assert.equal(MINTS.mSOL, pair[1]);
});
it("Order remains unchanged for exotic pairs", async () => {
// FTM/ORCA => FTM/ORCA (unchanged)
const pair = PoolUtil.toBaseQuoteOrder(MINTS.FTM, MINTS.ORCA);
assert.equal(MINTS.FTM, pair[0]);
assert.equal(MINTS.ORCA, pair[1]);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/assert.ts
|
import type { BN, Program } from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import { ONE } from "@orca-so/common-sdk";
import {
AccountLayout,
NATIVE_MINT,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import type { SwapQuote, WhirlpoolContext } from "../../src";
import type { Whirlpool } from "../../src/artifacts/whirlpool";
import type { DevFeeSwapQuote } from "../../src/quotes/public/dev-fee-swap-quote";
import type { TickData, WhirlpoolData } from "../../src/types/public";
import { TEST_TOKEN_PROGRAM_ID } from "./test-consts";
import { getTokenBalance } from "./token";
import type { VaultAmounts } from "./whirlpools-test-utils";
export function assertInputOutputQuoteEqual(
inputTokenQuote: SwapQuote,
outputTokenQuote: SwapQuote,
) {
assert.equal(inputTokenQuote.aToB, outputTokenQuote.aToB, "aToB not equal");
// TODO: Sometimes input & output estimated In is off by 1. Same goes for sqrt-price
assert.ok(
inputTokenQuote.estimatedAmountIn
.sub(outputTokenQuote.estimatedAmountIn)
.abs()
.lte(ONE),
`input estimated In ${inputTokenQuote.estimatedAmountIn} does not equal output estimated in ${outputTokenQuote.estimatedAmountIn}`,
);
assert.ok(
inputTokenQuote.estimatedAmountOut
.sub(outputTokenQuote.estimatedAmountOut)
.abs()
.lte(ONE),
`input estimated out ${inputTokenQuote.estimatedAmountOut} does not equal output estimated out ${outputTokenQuote.estimatedAmountOut}`,
);
assert.equal(
inputTokenQuote.estimatedEndTickIndex,
outputTokenQuote.estimatedEndTickIndex,
"estimatedEndTickIndex not equal",
);
assert.equal(
inputTokenQuote.estimatedFeeAmount.toString(),
outputTokenQuote.estimatedFeeAmount.toString(),
"estimatedFeeAmount not equal",
);
assert.notEqual(
inputTokenQuote.amountSpecifiedIsInput,
outputTokenQuote.amountSpecifiedIsInput,
"amountSpecifiedIsInput equals",
);
}
export function assertDevFeeQuotes(
inputQuote: SwapQuote,
postFeeInputQuote: SwapQuote,
devFeeQuote: DevFeeSwapQuote,
) {
assert.equal(inputQuote.aToB, devFeeQuote.aToB, "aToB not equal");
assert.ok(
devFeeQuote.estimatedAmountIn.eq(inputQuote.estimatedAmountIn),
`the devFeeQuote's estimatedAmountIn ${devFeeQuote.estimatedAmountIn} should equal the normal quote's estimatedAmountIn ${inputQuote.estimatedAmountIn}`,
);
assert.ok(
devFeeQuote.estimatedAmountIn.eq(
postFeeInputQuote.estimatedAmountIn.add(devFeeQuote.devFeeAmount),
),
`the devFeeQuote's estimatedAmountIn ${devFeeQuote.estimatedAmountIn} should equal the post-fee quote's estimatedAmountIn ${inputQuote.estimatedAmountIn} plus devFeeAmount ${devFeeQuote.devFeeAmount}`,
);
assert.ok(
postFeeInputQuote.estimatedAmountOut
.sub(devFeeQuote.estimatedAmountOut)
.abs()
.lte(ONE),
`post-fee input estimatedAmountOut ${inputQuote.estimatedAmountOut} does not equal devFee quote estimatedAmountOut - ${devFeeQuote.estimatedAmountOut}`,
);
assert.equal(
postFeeInputQuote.estimatedEndTickIndex,
devFeeQuote.estimatedEndTickIndex,
"estimatedEndTickIndex not equal",
);
assert.equal(
devFeeQuote.estimatedFeeAmount.toString(),
devFeeQuote.estimatedSwapFeeAmount.add(devFeeQuote.devFeeAmount).toString(),
"devFeeQuote estimatedFeeAmount is not the sum of estimatedSwapFeeAmount and devFeeAmount",
);
assert.equal(
devFeeQuote.estimatedSwapFeeAmount.toString(),
postFeeInputQuote.estimatedFeeAmount.toString(),
"devFeeQuote's estimatedSwapFeeAmount should equal the quote's total swap fee (without dev fee)",
);
assert.equal(
postFeeInputQuote.amountSpecifiedIsInput,
devFeeQuote.amountSpecifiedIsInput,
"amountSpecifiedIsInput not equal",
);
}
export async function assertDevTokenAmount(
ctx: WhirlpoolContext,
expectationQuote: DevFeeSwapQuote,
swapToken: PublicKey,
devWallet: PublicKey,
preDevWalletLamport = 0,
) {
if (swapToken.equals(NATIVE_MINT)) {
const walletAmount = await ctx.provider.connection.getBalance(devWallet);
assert.equal(
expectationQuote.devFeeAmount.toNumber() + preDevWalletLamport,
walletAmount,
);
return;
}
const tokenDevWalletAta = getAssociatedTokenAddressSync(swapToken, devWallet);
const afterDevWalletAmount = await getTokenBalance(
ctx.provider,
tokenDevWalletAta,
);
assert.equal(
expectationQuote.devFeeAmount,
afterDevWalletAmount,
"incorrect devFee amount sent to dev wallet.",
);
}
export function assertQuoteAndResults(
aToB: boolean,
quote: SwapQuote,
endData: WhirlpoolData,
beforeVaultAmounts: VaultAmounts,
afterVaultAmounts: VaultAmounts,
) {
const tokenADelta = beforeVaultAmounts.tokenA.sub(afterVaultAmounts.tokenA);
const tokenBDelta = beforeVaultAmounts.tokenB.sub(afterVaultAmounts.tokenB);
assert.equal(
quote.estimatedAmountIn.toString(),
(aToB ? tokenADelta : tokenBDelta).neg().toString(),
);
assert.equal(
quote.estimatedAmountOut.toString(),
(aToB ? tokenBDelta : tokenADelta).toString(),
);
assert.equal(endData.tickCurrentIndex, quote.estimatedEndTickIndex);
assert.equal(
quote.estimatedEndSqrtPrice.toString(),
endData.sqrtPrice.toString(),
);
}
// Helper for token vault assertion checks.
export async function asyncAssertTokenVault(
program: Program<Whirlpool>,
tokenVaultPublicKey: web3.PublicKey,
expectedValues: {
expectedOwner: web3.PublicKey;
expectedMint: web3.PublicKey;
},
) {
const tokenVault: web3.AccountInfo<Buffer> | null =
await program.provider.connection.getAccountInfo(tokenVaultPublicKey);
if (!tokenVault) {
assert.fail(
`token vault does not exist at ${tokenVaultPublicKey.toBase58()}`,
);
}
const tokenVaultAData = AccountLayout.decode(tokenVault.data);
assert.ok(tokenVault.owner.equals(TEST_TOKEN_PROGRAM_ID));
assert.ok(
expectedValues.expectedOwner.equals(
new web3.PublicKey(tokenVaultAData.owner),
),
);
assert.ok(
expectedValues.expectedMint.equals(
new web3.PublicKey(tokenVaultAData.mint),
),
);
}
export function assertTick(
tick: TickData,
initialized: boolean,
liquidityGross: BN,
liquidityNet: BN,
) {
assert.ok(tick.initialized == initialized);
assert.ok(tick.liquidityNet.eq(liquidityNet));
assert.ok(tick.liquidityGross.eq(liquidityGross));
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/swap-test-utils.ts
|
import type * as anchor from "@coral-xyz/anchor";
import type { Percentage } from "@orca-so/common-sdk";
import { NATIVE_MINT } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type BN from "bn.js";
import type { TickSpacing } from ".";
import type { Whirlpool, WhirlpoolClient, WhirlpoolContext } from "../../src";
import { TICK_ARRAY_SIZE } from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import type { FundedPositionParams } from "./init-utils";
import { fundPositionsWithClient, initTestPoolWithTokens } from "./init-utils";
export interface SwapTestPoolParams {
ctx: WhirlpoolContext;
client: WhirlpoolClient;
tickSpacing: TickSpacing;
initSqrtPrice: anchor.BN;
initArrayStartTicks: number[];
fundedPositions: FundedPositionParams[];
tokenMintAmount?: anchor.BN;
}
export interface SwapTestSwapParams {
swapAmount: BN;
aToB: boolean;
amountSpecifiedIsInput: boolean;
slippageTolerance: Percentage;
tickArrayAddresses: PublicKey[];
}
export interface SwapTestSetup {
whirlpool: Whirlpool;
tickArrayAddresses: PublicKey[];
}
export async function setupSwapTest(
setup: SwapTestPoolParams,
tokenAIsNative = false,
) {
const { whirlpoolPda } = await initTestPoolWithTokens(
setup.ctx,
setup.tickSpacing,
setup.initSqrtPrice,
setup.tokenMintAmount,
tokenAIsNative ? NATIVE_MINT : undefined,
);
const whirlpool = await setup.client.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
await (
await whirlpool.initTickArrayForTicks(setup.initArrayStartTicks)
)?.buildAndExecute();
await fundPositionsWithClient(
setup.client,
whirlpoolPda.publicKey,
setup.fundedPositions,
);
return whirlpool;
}
export interface ArrayTickIndex {
arrayIndex: number;
offsetIndex: number;
}
export function arrayTickIndexToTickIndex(
index: ArrayTickIndex,
tickSpacing: number,
) {
return (
index.arrayIndex * TICK_ARRAY_SIZE * tickSpacing +
index.offsetIndex * tickSpacing
);
}
export function buildPosition(
lower: ArrayTickIndex,
upper: ArrayTickIndex,
tickSpacing: number,
liquidityAmount: anchor.BN,
) {
return {
tickLowerIndex: arrayTickIndexToTickIndex(lower, tickSpacing),
tickUpperIndex: arrayTickIndexToTickIndex(upper, tickSpacing),
liquidityAmount,
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/graph-test-data.ts
|
import type { Address } from "@coral-xyz/anchor";
import type { PoolTokenPair } from "../../src";
export const solConnectedPools: PoolTokenPair[] = [
{
address: "7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm",
tokenMintA: "So11111111111111111111111111111111111111112",
tokenMintB: "RLBxxFkseAZ4RgJH3Sqn8jXxhmGoz9jWxDNJMh8pL7a",
},
{
address: "HQcY5n2zP6rW74fyFEhWeBd3LnJpBcZechkvJpmdb8cx",
tokenMintA: "So11111111111111111111111111111111111111112",
tokenMintB: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
},
{
address: "2AEWSvUds1wsufnsDPCXjFsJCMJH5SNNm7fSF4kxys9a",
tokenMintA: "So11111111111111111111111111111111111111112",
tokenMintB: "DUSTawucrTsGU8hcqRdHDCbuYhCPADMLM2VcCb8VnFnQ",
},
{
address: "CPsTfDvZYeVB5uTqQZcwwTTBJ7KPFvB6JKLGSWsFZEL7",
tokenMintA: "So11111111111111111111111111111111111111112",
tokenMintB: "7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj",
},
{
address: "HJPjoWUrhoZzkNfRpHuieeFk9WcZWjwy6PBjZ81ngndJ",
tokenMintA: "So11111111111111111111111111111111111111112",
tokenMintB: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
},
];
export const usdcConnectedPools: PoolTokenPair[] = [
{
address: "7PNQ9rfSGCbCC3XTeL6CwwAzevqQGvKXeXMxP2TjS7rM",
tokenMintA: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
tokenMintB: "RLBxxFkseAZ4RgJH3Sqn8jXxhmGoz9jWxDNJMh8pL7a",
},
{
address: "7A1R3L7AxcxuZHMJjFgskKGeBR5Rwst3Ai5bv5uAWZFG",
tokenMintA: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
tokenMintB: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
},
{
address: "BVXNG6BrL2Tn3NmppnMeXHjBHTaQSnSnLE99JKwZSWPg",
tokenMintA: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
tokenMintB: "DUSTawucrTsGU8hcqRdHDCbuYhCPADMLM2VcCb8VnFnQ",
},
];
export const oneRouteTwoHopsThroughSOL: [Address, Address] = [
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj",
];
export const feeTierPoolsGraphData: PoolTokenPair[] = [
{
address: "Gr7WKYBqRLt7oUkjZ54LSbiUf8EgNWcj3ogtN8dKbfeb",
tokenMintA: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
tokenMintB: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
},
{
address: "7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm",
tokenMintA: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
tokenMintB: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
},
{
address: "67S6KLCtgFZmRYzy6dCDc1v754mmcpK33pZd7Hg2yeVj",
tokenMintA: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
tokenMintB: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
},
];
export const oneRouteTwoHopsThroughmSOL: [Address, Address] = [
"So11111111111111111111111111111111111111112",
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
];
export const uniqueTokenMintsGraphData: PoolTokenPair[] = [
{
address: "5Z66YYYaTmmx1R4mATAGLSc8aV4Vfy5tNdJQzk1GP9RF",
tokenMintA: "USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX",
tokenMintB: "orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE",
},
];
export const uniqueTokenMintsGraphTokenUnsortedData: PoolTokenPair[] = [
{
address: "5Z66YYYaTmmx1R4mATAGLSc8aV4Vfy5tNdJQzk1GP9RF",
tokenMintA: "orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE",
tokenMintB: "USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX",
},
];
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/index.ts
|
export * from "./test-consts";
export * from "./token";
export * from "./utils";
export * from "./assert";
export enum TickSpacing {
One = 1,
Stable = 8,
ThirtyTwo = 32,
SixtyFour = 64,
Standard = 128,
FullRangeOnly = 32768,
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/token.ts
|
import type { AnchorProvider } from "@coral-xyz/anchor";
import { BN, web3 } from "@coral-xyz/anchor";
import { TokenUtil, TransactionBuilder } from "@orca-so/common-sdk";
import type { AuthorityType } from "@solana/spl-token";
import {
AccountLayout,
NATIVE_MINT,
TOKEN_PROGRAM_ID,
createApproveInstruction,
createAssociatedTokenAccountInstruction,
createBurnInstruction,
createInitializeAccount3Instruction,
createInitializeMintInstruction,
createMintToInstruction,
createSetAuthorityInstruction,
createTransferInstruction,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import { TEST_TOKEN_PROGRAM_ID } from "./test-consts";
export async function createMint(
provider: AnchorProvider,
authority?: web3.PublicKey,
): Promise<web3.PublicKey> {
if (authority === undefined) {
authority = provider.wallet.publicKey;
}
const mint = web3.Keypair.generate();
const instructions = await createMintInstructions(
provider,
authority,
mint.publicKey,
);
const tx = new web3.Transaction();
tx.add(...instructions);
await provider.sendAndConfirm(tx, [mint], { commitment: "confirmed" });
return mint.publicKey;
}
export async function createMintInstructions(
provider: AnchorProvider,
authority: web3.PublicKey,
mint: web3.PublicKey,
) {
let instructions = [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: mint,
space: 82,
lamports: await provider.connection.getMinimumBalanceForRentExemption(82),
programId: TEST_TOKEN_PROGRAM_ID,
}),
createInitializeMintInstruction(mint, 0, authority, null),
];
return instructions;
}
export async function createTokenAccount(
provider: AnchorProvider,
mint: web3.PublicKey,
owner: web3.PublicKey,
) {
const tokenAccount = web3.Keypair.generate();
const tx = new web3.Transaction();
tx.add(
...(await createTokenAccountInstrs(
provider,
tokenAccount.publicKey,
mint,
owner,
)),
);
await provider.sendAndConfirm(tx, [tokenAccount], {
commitment: "confirmed",
});
return tokenAccount.publicKey;
}
export async function createAssociatedTokenAccount(
provider: AnchorProvider,
mint: web3.PublicKey,
owner: web3.PublicKey,
payer: web3.PublicKey,
) {
const ataAddress = getAssociatedTokenAddressSync(mint, owner);
const instr = createAssociatedTokenAccountInstruction(
payer,
ataAddress,
owner,
mint,
);
const tx = new web3.Transaction();
tx.add(instr);
await provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
return ataAddress;
}
async function createTokenAccountInstrs(
provider: AnchorProvider,
newAccountPubkey: web3.PublicKey,
mint: web3.PublicKey,
owner: web3.PublicKey,
lamports?: number,
) {
if (lamports === undefined) {
lamports = await provider.connection.getMinimumBalanceForRentExemption(165);
}
return [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey,
space: 165,
lamports,
programId: TEST_TOKEN_PROGRAM_ID,
}),
createInitializeAccount3Instruction(newAccountPubkey, mint, owner),
];
}
/**
* Mints tokens to the specified destination token account.
* @param provider An anchor AnchorProvider object used to send transactions
* @param mint Mint address of the token
* @param destination Destination token account to receive tokens
* @param amount Number of tokens to mint
*/
export async function mintToDestination(
provider: AnchorProvider,
mint: web3.PublicKey,
destination: web3.PublicKey,
amount: number | BN,
): Promise<string> {
const tx = new web3.Transaction();
const amountVal = amount instanceof BN ? BigInt(amount.toString()) : amount;
tx.add(
createMintToInstruction(
mint,
destination,
provider.wallet.publicKey,
amountVal,
),
);
return provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
}
/**
* Creates a token account for the mint and mints the specified amount of tokens into the token account.
* The caller is assumed to be the mint authority.
* @param provider An anchor AnchorProvider object used to send transactions
* @param mint The mint address of the token
* @param amount Number of tokens to mint to the newly created token account
*/
export async function createAndMintToTokenAccount(
provider: AnchorProvider,
mint: web3.PublicKey,
amount: number | BN,
): Promise<web3.PublicKey> {
const tokenAccount = await createTokenAccount(
provider,
mint,
provider.wallet.publicKey,
);
await mintToDestination(
provider,
mint,
tokenAccount,
new BN(amount.toString()),
);
return tokenAccount;
}
export async function createAndMintToAssociatedTokenAccount(
provider: AnchorProvider,
mint: web3.PublicKey,
amount: number | BN,
destinationWallet?: web3.PublicKey,
payer?: web3.PublicKey,
): Promise<web3.PublicKey> {
const destinationWalletKey = destinationWallet
? destinationWallet
: provider.wallet.publicKey;
const payerKey = payer ? payer : provider.wallet.publicKey;
// Workaround For SOL - just create a wSOL account to satisfy the rest of the test building pipeline.
// Tests who want to test with SOL will have to request their own airdrop.
if (mint.equals(NATIVE_MINT)) {
const rentExemption =
await provider.connection.getMinimumBalanceForRentExemption(
AccountLayout.span,
"confirmed",
);
const txBuilder = new TransactionBuilder(
provider.connection,
provider.wallet,
);
const { address: tokenAccount, ...ix } =
TokenUtil.createWrappedNativeAccountInstruction(
destinationWalletKey,
new BN(amount.toString()),
rentExemption,
);
txBuilder.addInstruction({ ...ix, cleanupInstructions: [] });
await txBuilder.buildAndExecute();
return tokenAccount;
}
const tokenAccounts = await provider.connection.getParsedTokenAccountsByOwner(
destinationWalletKey,
{
programId: TOKEN_PROGRAM_ID,
},
);
let tokenAccount = tokenAccounts.value
.map((account) => {
if (account.account.data.parsed.info.mint === mint.toString()) {
return account.pubkey;
}
return undefined;
})
.filter(Boolean)[0];
if (!tokenAccount) {
tokenAccount = await createAssociatedTokenAccount(
provider,
mint,
destinationWalletKey,
payerKey,
);
}
await mintToDestination(
provider,
mint,
tokenAccount!,
new BN(amount.toString()),
);
return tokenAccount!;
}
export async function getTokenBalance(
provider: AnchorProvider,
vault: web3.PublicKey,
) {
return (await provider.connection.getTokenAccountBalance(vault, "confirmed"))
.value.amount;
}
export async function approveToken(
provider: AnchorProvider,
tokenAccount: web3.PublicKey,
delegate: web3.PublicKey,
amount: number | BN,
owner?: web3.Keypair,
tokenProgram: web3.PublicKey = TOKEN_PROGRAM_ID,
) {
const tx = new web3.Transaction();
const amountVal = amount instanceof BN ? BigInt(amount.toString()) : amount;
tx.add(
createApproveInstruction(
tokenAccount,
delegate,
owner?.publicKey || provider.wallet.publicKey,
amountVal,
undefined,
tokenProgram,
),
);
return provider.sendAndConfirm(tx, !!owner ? [owner] : [], {
commitment: "confirmed",
});
}
export async function setAuthority(
provider: AnchorProvider,
tokenAccount: web3.PublicKey,
newAuthority: web3.PublicKey,
authorityType: AuthorityType,
authority: web3.Keypair,
tokenProgram: web3.PublicKey = TOKEN_PROGRAM_ID,
) {
const tx = new web3.Transaction();
tx.add(
createSetAuthorityInstruction(
tokenAccount,
authority.publicKey,
authorityType,
newAuthority,
undefined,
tokenProgram,
),
);
return provider.sendAndConfirm(tx, [authority], { commitment: "confirmed" });
}
export async function transferToken(
provider: AnchorProvider,
source: web3.PublicKey,
destination: web3.PublicKey,
amount: number,
tokenProgram: web3.PublicKey = TOKEN_PROGRAM_ID,
) {
const tx = new web3.Transaction();
tx.add(
createTransferInstruction(
source,
destination,
provider.wallet.publicKey,
amount,
undefined,
tokenProgram,
),
);
return provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
}
export async function burnToken(
provider: AnchorProvider,
account: web3.PublicKey,
mint: web3.PublicKey,
amount: number | BN,
owner?: web3.PublicKey,
) {
const ownerKey = owner ?? provider.wallet.publicKey;
const tx = new web3.Transaction();
const amountVal = amount instanceof BN ? BigInt(amount.toString()) : amount;
tx.add(createBurnInstruction(account, mint, ownerKey, amountVal));
return provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/whirlpools-test-utils.ts
|
import BN from "bn.js";
import type { WhirlpoolContext, WhirlpoolData } from "../../src";
import { getTokenBalance } from "./token";
export type VaultAmounts = {
tokenA: BN;
tokenB: BN;
};
export async function getVaultAmounts(
ctx: WhirlpoolContext,
whirlpoolData: WhirlpoolData,
) {
return {
tokenA: new BN(
await getTokenBalance(ctx.provider, whirlpoolData.tokenVaultA),
),
tokenB: new BN(
await getTokenBalance(ctx.provider, whirlpoolData.tokenVaultB),
),
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/init-utils.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { AddressUtil, MathUtil } from "@orca-so/common-sdk";
import {
NATIVE_MINT,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import type BN from "bn.js";
import Decimal from "decimal.js";
import {
TickSpacing,
ZERO_BN,
createAndMintToAssociatedTokenAccount,
createMint,
mintToDestination,
} from ".";
import type {
InitConfigParams,
InitFeeTierParams,
InitPoolParams,
InitTickArrayParams,
InitializeRewardParams,
OpenPositionParams,
WhirlpoolClient,
WhirlpoolContext,
} from "../../src";
import {
PDAUtil,
PriceMath,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolIx,
toTx,
} from "../../src";
import { IGNORE_CACHE } from "../../src/network/public/fetcher";
import { PoolUtil } from "../../src/utils/public/pool-utils";
import type {
TestConfigParams,
TestWhirlpoolsConfigKeypairs,
} from "./test-builders";
import {
generateDefaultConfigParams,
generateDefaultInitFeeTierParams,
generateDefaultInitPoolParams,
generateDefaultInitTickArrayParams,
generateDefaultOpenBundledPositionParams,
generateDefaultOpenPositionParams,
generateDefaultOpenPositionWithTokenExtensionsParams,
} from "./test-builders";
interface TestPoolParams {
configInitInfo: InitConfigParams;
configKeypairs: TestWhirlpoolsConfigKeypairs;
poolInitInfo: InitPoolParams;
feeTierParams: { defaultFeeRate: number };
}
interface InitTestFeeTierParams {
tickSpacing: number;
feeRate?: number;
}
interface InitTestPoolParams {
mintIndices: [number, number];
tickSpacing: number;
feeTierIndex?: number;
initSqrtPrice?: anchor.BN;
}
interface InitTestMintParams {
// Default false
isNative?: boolean;
}
interface InitTestTokenAccParams {
mintIndex: number;
mintAmount?: anchor.BN;
}
interface InitTestTickArrayRangeParams {
poolIndex: number;
startTickIndex: number;
arrayCount: number;
aToB: boolean;
}
interface InitTestPositionParams {
poolIndex: number;
fundParams: FundedPositionParams[];
}
export interface InitAquariumParams {
// Single-ton per aquarium
configParams?: TestConfigParams;
initFeeTierParams: InitTestFeeTierParams[];
initMintParams: InitTestMintParams[];
initTokenAccParams: InitTestTokenAccParams[];
initPoolParams: InitTestPoolParams[];
initTickArrayRangeParams: InitTestTickArrayRangeParams[];
initPositionParams: InitTestPositionParams[];
}
export interface TestAquarium {
configParams: TestConfigParams;
feeTierParams: InitFeeTierParams[];
mintKeys: PublicKey[];
tokenAccounts: { mint: PublicKey; account: PublicKey }[];
pools: InitPoolParams[];
tickArrays: { params: InitTestTickArrayRangeParams; pdas: PDA[] }[];
}
const DEFAULT_FEE_RATE = 3000;
const DEFAULT_MINT_AMOUNT = new anchor.BN("15000000000");
const DEFAULT_SQRT_PRICE = MathUtil.toX64(new Decimal(5));
const DEFAULT_INIT_FEE_TIER = [{ tickSpacing: TickSpacing.Standard }];
const DEFAULT_INIT_MINT = [{}, {}];
const DEFAULT_INIT_TOKEN = [{ mintIndex: 0 }, { mintIndex: 1 }];
const DEFAULT_INIT_POOL: InitTestPoolParams[] = [
{ mintIndices: [0, 1], tickSpacing: TickSpacing.Standard },
];
const DEFAULT_INIT_TICK_ARR: InitTestTickArrayRangeParams[] = [];
const DEFAULT_INIT_POSITION: InitTestPositionParams[] = [];
export function getDefaultAquarium(): InitAquariumParams {
return {
initFeeTierParams: [...DEFAULT_INIT_FEE_TIER],
initMintParams: [...DEFAULT_INIT_MINT],
initTokenAccParams: [...DEFAULT_INIT_TOKEN],
initPoolParams: [...DEFAULT_INIT_POOL],
initTickArrayRangeParams: [...DEFAULT_INIT_TICK_ARR],
initPositionParams: [...DEFAULT_INIT_POSITION],
};
}
export async function buildTestAquariums(
ctx: WhirlpoolContext,
initParams: InitAquariumParams[],
): Promise<TestAquarium[]> {
const aquariums: TestAquarium[] = [];
// Airdrop SOL into provider wallet;
await ctx.connection.requestAirdrop(
ctx.provider.wallet.publicKey,
100_000_000_000_000,
);
for (const initParam of initParams) {
// Create configs
let configParams = initParam.configParams;
if (!configParams) {
configParams = generateDefaultConfigParams(ctx);
}
// Could batch
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, configParams.configInitInfo),
).buildAndExecute();
const {
initFeeTierParams,
initMintParams,
initTokenAccParams,
initPoolParams,
initTickArrayRangeParams,
initPositionParams,
} = initParam;
const feeTierParams: InitFeeTierParams[] = [];
for (const initFeeTierParam of initFeeTierParams) {
const { tickSpacing } = initFeeTierParam;
const feeRate =
initFeeTierParam.feeRate !== undefined
? initFeeTierParam.feeRate
: DEFAULT_FEE_RATE;
const { params } = await initFeeTier(
ctx,
configParams.configInitInfo,
configParams.configKeypairs.feeAuthorityKeypair,
tickSpacing,
feeRate,
);
feeTierParams.push(params);
}
// TODO: Handle native vs sorted mint keys
const mintKeys = (
await Promise.all(
initMintParams.map(({ isNative }) =>
isNative ? NATIVE_MINT : createMint(ctx.provider),
),
)
).sort(PoolUtil.compareMints);
const tokenAccounts = await Promise.all(
initTokenAccParams.map(async (initTokenAccParam) => {
const { mintIndex, mintAmount = DEFAULT_MINT_AMOUNT } =
initTokenAccParam;
const mintKey = mintKeys[mintIndex];
const account = await createAndMintToAssociatedTokenAccount(
ctx.provider,
mintKey,
mintAmount,
);
return { mint: mintKey, account };
}),
);
const pools = await Promise.all(
initPoolParams.map(async (initPoolParam) => {
const {
tickSpacing,
mintIndices,
initSqrtPrice = DEFAULT_SQRT_PRICE,
feeTierIndex = 0,
} = initPoolParam;
const [mintOne, mintTwo] = mintIndices.map((idx) => mintKeys[idx]);
const [tokenMintA, tokenMintB] = PoolUtil.orderMints(
mintOne,
mintTwo,
).map(AddressUtil.toPubKey);
const configKey =
configParams!.configInitInfo.whirlpoolsConfigKeypair.publicKey;
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configKey,
tokenMintA,
tokenMintB,
tickSpacing,
);
const poolParam = {
initSqrtPrice,
whirlpoolsConfig: configKey,
tokenMintA,
tokenMintB,
whirlpoolPda,
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
feeTierKey: feeTierParams[feeTierIndex].feeTierPda.publicKey,
tickSpacing,
// TODO: funder
funder: ctx.wallet.publicKey,
};
const tx = toTx(
ctx,
WhirlpoolIx.initializePoolIx(ctx.program, poolParam),
);
await tx.buildAndExecute();
return poolParam;
}),
);
const tickArrays = await Promise.all(
initTickArrayRangeParams.map(async (initTickArrayRangeParam) => {
const { poolIndex, startTickIndex, arrayCount, aToB } =
initTickArrayRangeParam;
const pool = pools[poolIndex];
const pdas = await initTickArrayRange(
ctx,
pool.whirlpoolPda.publicKey,
startTickIndex,
arrayCount,
pool.tickSpacing,
aToB,
);
return {
params: initTickArrayRangeParam,
pdas,
};
}),
);
await Promise.all(
initPositionParams.map(async (initPositionParam) => {
const { poolIndex, fundParams } = initPositionParam;
const pool = pools[poolIndex];
const tokenAccKeys = getTokenAccsForPools([pool], tokenAccounts);
await fundPositions(
ctx,
pool,
tokenAccKeys[0],
tokenAccKeys[1],
fundParams,
);
}),
);
aquariums.push({
configParams,
feeTierParams,
mintKeys,
tokenAccounts,
pools,
tickArrays,
});
}
return aquariums;
}
export function getTokenAccsForPools(
pools: InitPoolParams[],
tokenAccounts: { mint: PublicKey; account: PublicKey }[],
) {
const mints: PublicKey[] = [];
for (const pool of pools) {
mints.push(pool.tokenMintA);
mints.push(pool.tokenMintB);
}
return mints.map(
(mint) => tokenAccounts.find((acc) => acc.mint.equals(mint))!.account,
);
}
/**
* Initialize a brand new WhirlpoolsConfig account and construct a set of InitPoolParams
* that can be used to initialize a pool with.
* @param client - an instance of whirlpool client containing the program & provider
* @param initSqrtPrice - the initial sqrt-price for this newly generated pool
* @returns An object containing the params used to init the config account & the param that can be used to init the pool account.
*/
export async function buildTestPoolParams(
ctx: WhirlpoolContext,
tickSpacing: number,
defaultFeeRate = 3000,
initSqrtPrice = DEFAULT_SQRT_PRICE,
funder?: PublicKey,
reuseTokenA?: PublicKey,
) {
const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx);
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo),
).buildAndExecute();
const { params: feeTierParams } = await initFeeTier(
ctx,
configInitInfo,
configKeypairs.feeAuthorityKeypair,
tickSpacing,
defaultFeeRate,
);
const poolInitInfo = await generateDefaultInitPoolParams(
ctx,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
feeTierParams.feeTierPda.publicKey,
tickSpacing,
initSqrtPrice,
funder,
reuseTokenA,
);
return {
configInitInfo,
configKeypairs,
poolInitInfo,
feeTierParams,
};
}
/**
* Initialize a brand new set of WhirlpoolsConfig & Whirlpool account
* @param client - an instance of whirlpool client containing the program & provider
* @param initSqrtPrice - the initial sqrt-price for this newly generated pool
* @returns An object containing the params used to initialize both accounts.
*/
export async function initTestPool(
ctx: WhirlpoolContext,
tickSpacing: number,
initSqrtPrice = DEFAULT_SQRT_PRICE,
funder?: Keypair,
reuseTokenA?: PublicKey,
) {
const poolParams = await buildTestPoolParams(
ctx,
tickSpacing,
3000,
initSqrtPrice,
funder?.publicKey,
reuseTokenA,
);
return initTestPoolFromParams(ctx, poolParams, funder);
}
export async function initTestPoolFromParams(
ctx: WhirlpoolContext,
poolParams: TestPoolParams,
funder?: Keypair,
) {
const { configInitInfo, poolInitInfo, configKeypairs, feeTierParams } =
poolParams;
const tx = toTx(ctx, WhirlpoolIx.initializePoolIx(ctx.program, poolInitInfo));
if (funder) {
tx.addSigner(funder);
}
return {
txId: await tx.buildAndExecute(),
configInitInfo,
configKeypairs,
poolInitInfo,
feeTierParams,
};
}
export async function initFeeTier(
ctx: WhirlpoolContext,
configInitInfo: InitConfigParams,
feeAuthorityKeypair: Keypair,
tickSpacing: number,
defaultFeeRate: number,
funder?: Keypair,
) {
const params = generateDefaultInitFeeTierParams(
ctx,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
configInitInfo.feeAuthority,
tickSpacing,
defaultFeeRate,
funder?.publicKey,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializeFeeTierIx(ctx.program, params),
).addSigner(feeAuthorityKeypair);
if (funder) {
tx.addSigner(funder);
}
return {
txId: await tx.buildAndExecute(),
params,
};
}
export async function initializeReward(
ctx: WhirlpoolContext,
rewardAuthorityKeypair: anchor.web3.Keypair,
whirlpool: PublicKey,
rewardIndex: number,
funder?: Keypair,
): Promise<{ txId: string; params: InitializeRewardParams }> {
const provider = ctx.provider;
const rewardMint = await createMint(provider);
const rewardVaultKeypair = anchor.web3.Keypair.generate();
const params = {
rewardAuthority: rewardAuthorityKeypair.publicKey,
funder: funder?.publicKey || ctx.wallet.publicKey,
whirlpool,
rewardMint,
rewardVaultKeypair,
rewardIndex,
};
const tx = toTx(
ctx,
WhirlpoolIx.initializeRewardIx(ctx.program, params),
).addSigner(rewardAuthorityKeypair);
if (funder) {
tx.addSigner(funder);
}
return {
txId: await tx.buildAndExecute(),
params,
};
}
export async function initRewardAndSetEmissions(
ctx: WhirlpoolContext,
rewardAuthorityKeypair: anchor.web3.Keypair,
whirlpool: PublicKey,
rewardIndex: number,
vaultAmount: BN | number,
emissionsPerSecondX64: anchor.BN,
funder?: Keypair,
) {
const {
params: { rewardMint, rewardVaultKeypair },
} = await initializeReward(
ctx,
rewardAuthorityKeypair,
whirlpool,
rewardIndex,
funder,
);
await mintToDestination(
ctx.provider,
rewardMint,
rewardVaultKeypair.publicKey,
vaultAmount,
);
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsIx(ctx.program, {
rewardAuthority: rewardAuthorityKeypair.publicKey,
whirlpool,
rewardIndex,
rewardVaultKey: rewardVaultKeypair.publicKey,
emissionsPerSecondX64,
}),
)
.addSigner(rewardAuthorityKeypair)
.buildAndExecute();
return { rewardMint, rewardVaultKeypair };
}
export async function openPosition(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
withTokenExtensions: boolean = false,
): ReturnType<typeof openPositionWithOptMetadata> {
if (withTokenExtensions) {
const result = await openPositionWithTokenExtensions(
ctx,
whirlpool,
tickLowerIndex,
tickUpperIndex,
false,
owner,
funder,
);
// adjust return type for compatibility
return {
mint: result.mint,
txId: result.txId,
params: {
...result.params,
// rename
positionMintAddress: result.params.positionMint,
// add metadata
metadataPda: PDAUtil.getPositionMetadata(result.params.positionMint),
},
};
}
return openPositionWithOptMetadata(
ctx,
whirlpool,
tickLowerIndex,
tickUpperIndex,
false,
owner,
funder,
);
}
export async function openPositionWithMetadata(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
return openPositionWithOptMetadata(
ctx,
whirlpool,
tickLowerIndex,
tickUpperIndex,
true,
owner,
funder,
);
}
async function openPositionWithOptMetadata(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
tickLowerIndex: number,
tickUpperIndex: number,
withMetadata: boolean = false,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
const { params, mint } = await generateDefaultOpenPositionParams(
ctx,
whirlpool,
tickLowerIndex,
tickUpperIndex,
owner,
funder?.publicKey || ctx.provider.wallet.publicKey,
);
let tx = withMetadata
? toTx(ctx, WhirlpoolIx.openPositionWithMetadataIx(ctx.program, params))
: toTx(ctx, WhirlpoolIx.openPositionIx(ctx.program, params));
tx.addSigner(mint);
if (funder) {
tx.addSigner(funder);
}
const txId = await tx.buildAndExecute();
return { txId, params, mint };
}
async function openPositionWithTokenExtensions(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
tickLowerIndex: number,
tickUpperIndex: number,
withMetadata: boolean = false,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
const { params, mint } =
await generateDefaultOpenPositionWithTokenExtensionsParams(
ctx,
whirlpool,
withMetadata,
tickLowerIndex,
tickUpperIndex,
owner,
funder?.publicKey || ctx.provider.wallet.publicKey,
);
let tx = toTx(
ctx,
WhirlpoolIx.openPositionWithTokenExtensionsIx(ctx.program, params),
);
tx.addSigner(mint);
if (funder) {
tx.addSigner(funder);
}
const txId = await tx.buildAndExecute();
return { txId, params, mint };
}
export async function initTickArray(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
startTickIndex: number,
funder?: Keypair,
): Promise<{ txId: string; params: InitTickArrayParams }> {
const params = generateDefaultInitTickArrayParams(
ctx,
whirlpool,
startTickIndex,
funder?.publicKey,
);
const tx = toTx(ctx, WhirlpoolIx.initTickArrayIx(ctx.program, params));
if (funder) {
tx.addSigner(funder);
}
return { txId: await tx.buildAndExecute(), params };
}
export async function initTestPoolWithTokens(
ctx: WhirlpoolContext,
tickSpacing: number,
initSqrtPrice = DEFAULT_SQRT_PRICE,
mintAmount = new anchor.BN("15000000000"),
reuseTokenA?: PublicKey,
) {
const provider = ctx.provider;
const { poolInitInfo, configInitInfo, configKeypairs, feeTierParams } =
await initTestPool(ctx, tickSpacing, initSqrtPrice, undefined, reuseTokenA);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
// Airdrop SOL into provider's wallet for SOL native token testing.
const connection = ctx.provider.connection;
const airdropTx = await connection.requestAirdrop(
ctx.provider.wallet.publicKey,
100_000_000_000_000,
);
await ctx.connection.confirmTransaction(
{
signature: airdropTx,
...(await ctx.connection.getLatestBlockhash("confirmed")),
},
"confirmed",
);
const tokenAccountA = await createAndMintToAssociatedTokenAccount(
provider,
tokenMintA,
mintAmount,
);
const tokenAccountB = await createAndMintToAssociatedTokenAccount(
provider,
tokenMintB,
mintAmount,
);
return {
poolInitInfo,
configInitInfo,
configKeypairs,
feeTierParams,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
};
}
export async function initTickArrayRange(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
startTickIndex: number,
arrayCount: number,
tickSpacing: number,
aToB: boolean,
): Promise<PDA[]> {
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const direction = aToB ? -1 : 1;
const result: PDA[] = [];
for (let i = 0; i < arrayCount; i++) {
const { params } = await initTickArray(
ctx,
whirlpool,
startTickIndex + direction * ticksInArray * i,
);
result.push(params.tickArrayPda);
}
return result;
}
export type FundedPositionParams = {
tickLowerIndex: number;
tickUpperIndex: number;
liquidityAmount: anchor.BN;
isTokenExtensionsBasedPosition?: boolean;
};
export async function withdrawPositions(
ctx: WhirlpoolContext,
positionInfos: FundedPositionInfo[],
tokenOwnerAccountA: PublicKey,
tokenOwnerAccountB: PublicKey,
) {
const fetcher = ctx.fetcher;
await Promise.all(
positionInfos.map(async (info) => {
const pool = await fetcher.getPool(info.initParams.whirlpool);
const position = await fetcher.getPosition(
info.initParams.positionPda.publicKey,
);
if (!pool) {
throw new Error(`Failed to fetch pool - ${info.initParams.whirlpool}`);
}
if (!position) {
throw new Error(
`Failed to fetch position - ${info.initParams.whirlpool}`,
);
}
const priceLower = PriceMath.tickIndexToSqrtPriceX64(
position.tickLowerIndex,
);
const priceUpper = PriceMath.tickIndexToSqrtPriceX64(
position.tickUpperIndex,
);
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
position.liquidity,
pool.sqrtPrice,
priceLower,
priceUpper,
false,
);
const numTicksInTickArray = pool.tickSpacing * TICK_ARRAY_SIZE;
const lowerStartTick =
position.tickLowerIndex -
(position.tickLowerIndex % numTicksInTickArray);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
info.initParams.whirlpool,
lowerStartTick,
);
const upperStartTick =
position.tickUpperIndex -
(position.tickUpperIndex % numTicksInTickArray);
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
info.initParams.whirlpool,
upperStartTick,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityIx(ctx.program, {
liquidityAmount: position.liquidity,
tokenMinA: tokenA,
tokenMinB: tokenB,
whirlpool: info.initParams.whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: info.initParams.positionPda.publicKey,
positionTokenAccount: info.initParams.positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: pool.tokenVaultA,
tokenVaultB: pool.tokenVaultB,
tickArrayLower: tickArrayLower.publicKey,
tickArrayUpper: tickArrayUpper.publicKey,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.collectFeesIx(ctx.program, {
whirlpool: info.initParams.whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: info.initParams.positionPda.publicKey,
positionTokenAccount: info.initParams.positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: pool.tokenVaultA,
tokenVaultB: pool.tokenVaultB,
}),
).buildAndExecute();
}),
);
}
export interface FundedPositionInfo {
initParams: OpenPositionParams;
publicKey: PublicKey;
tokenAccount: PublicKey;
mintKeypair: Keypair;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
}
export async function fundPositionsWithClient(
client: WhirlpoolClient,
whirlpoolKey: PublicKey,
fundParams: FundedPositionParams[],
) {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
await Promise.all(
fundParams.map(async (param) => {
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
param.liquidityAmount,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(param.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(param.tickUpperIndex),
true,
);
const tokenProgramId =
(param.isTokenExtensionsBasedPosition ?? false)
? TOKEN_2022_PROGRAM_ID
: TOKEN_PROGRAM_ID;
const { tx } = await whirlpool.openPosition(
param.tickLowerIndex,
param.tickUpperIndex,
{
liquidityAmount: param.liquidityAmount,
tokenMaxA: tokenA,
tokenMaxB: tokenB,
},
undefined,
undefined,
undefined,
tokenProgramId,
);
await tx.buildAndExecute();
}),
);
}
export async function fundPositions(
ctx: WhirlpoolContext,
poolInitInfo: InitPoolParams,
tokenAccountA: PublicKey,
tokenAccountB: PublicKey,
fundParams: FundedPositionParams[],
): Promise<FundedPositionInfo[]> {
const {
whirlpoolPda: { publicKey: whirlpool },
tickSpacing,
tokenVaultAKeypair,
tokenVaultBKeypair,
initSqrtPrice,
} = poolInitInfo;
return await Promise.all(
fundParams.map(async (param): Promise<FundedPositionInfo> => {
const { params: positionInfo, mint } = await openPosition(
ctx,
whirlpool,
param.tickLowerIndex,
param.tickUpperIndex,
undefined,
undefined,
param.isTokenExtensionsBasedPosition ?? false,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
TickUtil.getStartTickIndex(param.tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
TickUtil.getStartTickIndex(param.tickUpperIndex, tickSpacing),
).publicKey;
if (param.liquidityAmount.gt(ZERO_BN)) {
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
param.liquidityAmount,
initSqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(param.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(param.tickUpperIndex),
true,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityIx(ctx.program, {
liquidityAmount: param.liquidityAmount,
tokenMaxA: tokenA,
tokenMaxB: tokenB,
whirlpool: whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: positionInfo.positionPda.publicKey,
positionTokenAccount: positionInfo.positionTokenAccount,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArrayLower,
tickArrayUpper,
}),
).buildAndExecute();
}
return {
initParams: positionInfo,
publicKey: positionInfo.positionPda.publicKey,
tokenAccount: positionInfo.positionTokenAccount,
mintKeypair: mint,
tickArrayLower,
tickArrayUpper,
};
}),
);
}
export async function initTestPoolWithLiquidity(
ctx: WhirlpoolContext,
initSqrtPrice = DEFAULT_SQRT_PRICE,
mintAmount = new anchor.BN("15000000000"),
reuseTokenA?: PublicKey,
) {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
feeTierParams,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokens(
ctx,
TickSpacing.Standard,
initSqrtPrice,
mintAmount,
reuseTokenA,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionParams[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 27904,
tickUpperIndex: 33408,
},
];
const positionInfos = await fundPositions(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
return {
poolInitInfo,
configInitInfo,
configKeypairs,
positionInfo: positionInfos[0].initParams,
tokenAccountA,
tokenAccountB,
tickArrays,
feeTierParams,
};
}
export async function initializePositionBundleWithMetadata(
ctx: WhirlpoolContext,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
const positionBundleMintKeypair = Keypair.generate();
const positionBundlePda = PDAUtil.getPositionBundle(
ctx.program.programId,
positionBundleMintKeypair.publicKey,
);
const positionBundleMetadataPda = PDAUtil.getPositionBundleMetadata(
positionBundleMintKeypair.publicKey,
);
const positionBundleTokenAccount = getAssociatedTokenAddressSync(
positionBundleMintKeypair.publicKey,
owner,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializePositionBundleWithMetadataIx(ctx.program, {
positionBundleMintKeypair,
positionBundlePda,
positionBundleMetadataPda,
owner,
positionBundleTokenAccount,
funder: !!funder ? funder.publicKey : owner,
}),
);
if (funder) {
tx.addSigner(funder);
}
const txId = await tx.buildAndExecute();
return {
txId,
positionBundleMintKeypair,
positionBundlePda,
positionBundleMetadataPda,
positionBundleTokenAccount,
};
}
export async function initializePositionBundle(
ctx: WhirlpoolContext,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
const positionBundleMintKeypair = Keypair.generate();
const positionBundlePda = PDAUtil.getPositionBundle(
ctx.program.programId,
positionBundleMintKeypair.publicKey,
);
const positionBundleTokenAccount = getAssociatedTokenAddressSync(
positionBundleMintKeypair.publicKey,
owner,
);
const tx = toTx(
ctx,
WhirlpoolIx.initializePositionBundleIx(ctx.program, {
positionBundleMintKeypair,
positionBundlePda,
owner,
positionBundleTokenAccount,
funder: !!funder ? funder.publicKey : owner,
}),
);
if (funder) {
tx.addSigner(funder);
}
const txId = await tx.buildAndExecute();
return {
txId,
positionBundleMintKeypair,
positionBundlePda,
positionBundleTokenAccount,
};
}
export async function openBundledPosition(
ctx: WhirlpoolContext,
whirlpool: PublicKey,
positionBundleMint: PublicKey,
bundleIndex: number,
tickLowerIndex: number,
tickUpperIndex: number,
owner: PublicKey = ctx.provider.wallet.publicKey,
funder?: Keypair,
) {
const { params } = await generateDefaultOpenBundledPositionParams(
ctx,
whirlpool,
positionBundleMint,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
owner,
funder?.publicKey || owner,
);
const tx = toTx(ctx, WhirlpoolIx.openBundledPositionIx(ctx.program, params));
if (funder) {
tx.addSigner(funder);
}
const txId = await tx.buildAndExecute();
return { txId, params };
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/fixture.ts
|
import type { BN } from "@coral-xyz/anchor";
import { NATIVE_MINT } from "@solana/spl-token";
import { Keypair, PublicKey } from "@solana/web3.js";
import { TickSpacing, ZERO_BN } from ".";
import type {
InitConfigParams,
InitPoolParams,
WhirlpoolContext,
} from "../../src";
import { TickUtil } from "../../src";
import type { FundedPositionInfo, FundedPositionParams } from "./init-utils";
import {
fundPositions,
initRewardAndSetEmissions,
initTestPoolWithTokens,
initTickArray,
} from "./init-utils";
interface InitFixtureParams {
tickSpacing: number;
initialSqrtPrice?: BN;
positions?: FundedPositionParams[];
rewards?: RewardParam[];
tokenAIsNative?: boolean;
}
interface RewardParam {
emissionsPerSecondX64: BN;
vaultAmount: BN;
}
interface InitializedRewardInfo {
rewardMint: PublicKey;
rewardVaultKeypair: Keypair;
}
export class WhirlpoolTestFixture {
private ctx: WhirlpoolContext;
private poolInitInfo: InitPoolParams = defaultPoolInitInfo;
private configInitInfo: InitConfigParams = defaultConfigInitInfo;
private configKeypairs = defaultConfigKeypairs;
private positions: FundedPositionInfo[] = [];
private rewards: InitializedRewardInfo[] = [];
private tokenAccountA = PublicKey.default;
private tokenAccountB = PublicKey.default;
private initialized = false;
constructor(ctx: WhirlpoolContext) {
this.ctx = ctx;
}
async init(params: InitFixtureParams): Promise<WhirlpoolTestFixture> {
const {
tickSpacing,
initialSqrtPrice,
positions,
rewards,
tokenAIsNative,
} = params;
const {
poolInitInfo,
configInitInfo,
configKeypairs,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokens(
this.ctx,
tickSpacing,
initialSqrtPrice,
undefined,
tokenAIsNative ? NATIVE_MINT : undefined,
);
this.poolInitInfo = poolInitInfo;
this.configInitInfo = configInitInfo;
this.configKeypairs = configKeypairs;
this.tokenAccountA = tokenAccountA;
this.tokenAccountB = tokenAccountB;
if (positions) {
await initTickArrays(this.ctx, poolInitInfo, positions);
this.positions = await fundPositions(
this.ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
positions,
);
}
if (rewards) {
const initRewards: InitializedRewardInfo[] = [];
for (let i = 0; i < rewards.length; i++) {
// Iterate because we enforce sequential initialization on the smart contract
initRewards.push(
await initRewardAndSetEmissions(
this.ctx,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolPda.publicKey,
i,
rewards[i].vaultAmount,
rewards[i].emissionsPerSecondX64,
),
);
}
this.rewards = initRewards;
}
this.initialized = true;
return this;
}
getInfos() {
if (!this.initialized) {
throw new Error("Test fixture is not initialized");
}
return {
poolInitInfo: this.poolInitInfo,
configInitInfo: this.configInitInfo,
configKeypairs: this.configKeypairs,
tokenAccountA: this.tokenAccountA,
tokenAccountB: this.tokenAccountB,
positions: this.positions,
rewards: this.rewards,
};
}
}
async function initTickArrays(
ctx: WhirlpoolContext,
poolInitInfo: InitPoolParams,
positions: FundedPositionParams[],
) {
const startTickSet = new Set<number>();
positions.forEach((p) => {
startTickSet.add(
TickUtil.getStartTickIndex(p.tickLowerIndex, poolInitInfo.tickSpacing),
);
startTickSet.add(
TickUtil.getStartTickIndex(p.tickUpperIndex, poolInitInfo.tickSpacing),
);
});
return Promise.all(
Array.from(startTickSet).map((startTick) =>
initTickArray(ctx, poolInitInfo.whirlpoolPda.publicKey, startTick),
),
);
}
const defaultPoolInitInfo: InitPoolParams = {
initSqrtPrice: ZERO_BN,
whirlpoolsConfig: PublicKey.default,
tokenMintA: PublicKey.default,
tokenMintB: PublicKey.default,
whirlpoolPda: { publicKey: PublicKey.default, bump: 0 },
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
tickSpacing: TickSpacing.Standard,
feeTierKey: PublicKey.default,
funder: PublicKey.default,
};
const defaultConfigInitInfo = {
whirlpoolsConfigKeypair: Keypair.generate(),
feeAuthority: PublicKey.default,
collectProtocolFeesAuthority: PublicKey.default,
rewardEmissionsSuperAuthority: PublicKey.default,
defaultProtocolFeeRate: 0,
funder: PublicKey.default,
};
const defaultConfigKeypairs = {
feeAuthorityKeypair: Keypair.generate(),
collectProtocolFeesAuthorityKeypair: Keypair.generate(),
rewardEmissionsSuperAuthorityKeypair: Keypair.generate(),
};
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/transfer-fee.ts
|
// [Mar 12, 2024] SetTransferFee instruction is not supported in @solana/spl-token, so we need to build instructions manually...
import {
TOKEN_2022_PROGRAM_ID,
TokenInstruction,
TokenUnsupportedInstructionError,
TransferFeeInstruction,
programSupportsExtensions,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import { TransactionInstruction } from "@solana/web3.js";
import { struct, u16, u8 } from "@solana/buffer-layout";
import { u64 } from "@solana/buffer-layout-utils";
export interface SetTransferFeeInstructionData {
instruction: TokenInstruction.TransferFeeExtension;
transferFeeInstruction: TransferFeeInstruction.SetTransferFee;
transferFeeBasisPoints: number;
maximumFee: bigint;
}
export const setTransferFeeInstructionData =
struct<SetTransferFeeInstructionData>([
u8("instruction"),
u8("transferFeeInstruction"),
u16("transferFeeBasisPoints"),
u64("maximumFee"),
]);
export function createSetTransferFeeInstruction(
mint: PublicKey,
newTransferFeeBasisPoints: number,
newMaximumFee: bigint,
transferFeeConfigAuthority: PublicKey,
programId: PublicKey = TOKEN_2022_PROGRAM_ID,
) {
if (!programSupportsExtensions(programId)) {
throw new TokenUnsupportedInstructionError();
}
const keys = [
{ pubkey: mint, isSigner: false, isWritable: true },
{ pubkey: transferFeeConfigAuthority, isSigner: true, isWritable: false },
];
const data = Buffer.alloc(setTransferFeeInstructionData.span);
setTransferFeeInstructionData.encode(
{
instruction: TokenInstruction.TransferFeeExtension,
transferFeeInstruction: TransferFeeInstruction.SetTransferFee,
transferFeeBasisPoints: newTransferFeeBasisPoints,
maximumFee: newMaximumFee,
},
data,
);
return new TransactionInstruction({ keys, programId, data });
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/test-transfer-hook-program.ts
|
import type { AnchorProvider } from "@coral-xyz/anchor";
import { web3 } from "@coral-xyz/anchor";
import type { AccountMeta } from "@solana/web3.js";
import { getExtraAccountMetasForHookProgram } from "./token-2022";
import {
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TRANSFER_HOOK_PROGRAM_ID,
} from "../test-consts";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
createUpdateTransferHookInstruction,
} from "@solana/spl-token";
export async function getExtraAccountMetasForTestTransferHookProgram(
provider: AnchorProvider,
mint: web3.PublicKey,
source: web3.PublicKey,
destination: web3.PublicKey,
owner: web3.PublicKey,
): Promise<AccountMeta[] | undefined> {
return getExtraAccountMetasForHookProgram(
provider,
TEST_TRANSFER_HOOK_PROGRAM_ID,
source,
mint,
destination,
owner,
0, // not used to derive addresses
);
}
export async function getTestTransferHookCounter(
provider: AnchorProvider,
mint: web3.PublicKey,
): Promise<number> {
const [counterAccountPDA] = web3.PublicKey.findProgramAddressSync(
[Buffer.from("counter"), mint.toBuffer()],
TEST_TRANSFER_HOOK_PROGRAM_ID,
);
const data = await provider.connection.getAccountInfo(counterAccountPDA);
return data!.data.readInt32LE(8);
}
export async function updateTransferHookProgram(
provider: AnchorProvider,
mint: web3.PublicKey,
newTransferHookProgramId: web3.PublicKey,
authority?: web3.Keypair,
) {
const tx = new web3.Transaction();
tx.add(
createUpdateTransferHookInstruction(
mint,
authority?.publicKey ?? provider.wallet.publicKey,
newTransferHookProgramId,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
return provider.sendAndConfirm(tx, !!authority ? [authority] : [], {
commitment: "confirmed",
});
}
export function createInitializeExtraAccountMetaListInstruction(
payer: web3.PublicKey,
mint: web3.PublicKey,
): web3.TransactionInstruction {
// create ExtraAccountMetaList account
const [extraAccountMetaListPDA] = web3.PublicKey.findProgramAddressSync(
[Buffer.from("extra-account-metas"), mint.toBuffer()],
TEST_TRANSFER_HOOK_PROGRAM_ID,
);
const [counterAccountPDA] = web3.PublicKey.findProgramAddressSync(
[Buffer.from("counter"), mint.toBuffer()],
TEST_TRANSFER_HOOK_PROGRAM_ID,
);
return {
programId: TEST_TRANSFER_HOOK_PROGRAM_ID,
keys: [
{ pubkey: payer, isSigner: true, isWritable: true },
{ pubkey: extraAccountMetaListPDA, isSigner: false, isWritable: true },
{ pubkey: mint, isSigner: false, isWritable: false },
{ pubkey: counterAccountPDA, isSigner: false, isWritable: true },
{
pubkey: TEST_TOKEN_2022_PROGRAM_ID,
isSigner: false,
isWritable: false,
},
{
pubkey: ASSOCIATED_TOKEN_PROGRAM_ID,
isSigner: false,
isWritable: false,
},
{
pubkey: web3.SystemProgram.programId,
isSigner: false,
isWritable: false,
},
],
data: Buffer.from([0x5c, 0xc5, 0xae, 0xc5, 0x29, 0x7c, 0x13, 0x03]), // InitializeExtraAccountMetaList
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/confidential-transfer.ts
|
// [Mar 6, 2024] ConfidentialTransfer is not supported in @solana/spl-token, so we need to build instructions manually...
import {
ExtensionType,
TOKEN_2022_PROGRAM_ID,
TokenInstruction,
TokenUnsupportedInstructionError,
getExtensionTypes,
getMint,
programSupportsExtensions,
} from "@solana/spl-token";
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
import { struct, u8 } from "@solana/buffer-layout";
import { publicKey } from "@solana/buffer-layout-utils";
import type { AnchorProvider } from "@coral-xyz/anchor";
import { TEST_TOKEN_2022_PROGRAM_ID } from "../test-consts";
enum ConfidentialTransferInstruction {
// We are interested in initilization only
InitializeMint = 0,
// ...
// https://github.com/solana-labs/solana-program-library/blob/d4bbd51b5167d3f0c8a247b5f304a92e6482cd6f/token/program-2022/src/extension/confidential_transfer/instruction.rs#L33
}
interface InitializeConfidentialTransferMintInstructionData {
instruction: TokenInstruction.ConfidentialTransferExtension;
confidentialTransferInstruction: ConfidentialTransferInstruction.InitializeMint;
authority: PublicKey | null;
autoApproveNewAccounts: boolean;
auditorElgamalPubkey: PublicKey | null;
}
/*
Sample transaction instruction data
1b 00 0c 8e 98 78 4f 83 30 4f 46 14 80 d7 86 b4
7b da 04 59 14 d2 21 b4 ac 77 74 02 97 af b6 71
53 35 01 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00
data length: 67 bytes
1: confidential transfer prefix
1: confidential transfer ix
32: authority
1: auto approve
32: elgamal
*/
const initializeConfidentialTransferMintInstructionData =
struct<InitializeConfidentialTransferMintInstructionData>([
u8("instruction"),
u8("confidentialTransferInstruction"),
publicKey("authority"),
u8("autoApproveNewAccounts"),
publicKey("auditorElgamalPubkey"),
]);
export function createInitializeConfidentialTransferMintInstruction(
mint: PublicKey,
authority: PublicKey,
autoApproveNewAccounts: boolean = true,
auditorElgamalPubkey: PublicKey = PublicKey.default,
programId: PublicKey = TOKEN_2022_PROGRAM_ID,
) {
if (!programSupportsExtensions(programId)) {
throw new TokenUnsupportedInstructionError();
}
const keys = [{ pubkey: mint, isSigner: false, isWritable: true }];
const data = Buffer.alloc(
initializeConfidentialTransferMintInstructionData.span,
);
initializeConfidentialTransferMintInstructionData.encode(
{
instruction: TokenInstruction.ConfidentialTransferExtension,
confidentialTransferInstruction:
ConfidentialTransferInstruction.InitializeMint,
authority,
auditorElgamalPubkey,
autoApproveNewAccounts,
},
data,
);
return new TransactionInstruction({ keys, programId, data });
}
export async function hasConfidentialTransferMintExtension(
provider: AnchorProvider,
mint: PublicKey,
): Promise<boolean> {
const account = await getMint(
provider.connection,
mint,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const extensions = getExtensionTypes(account.tlvData);
return extensions.includes(ExtensionType.ConfidentialTransferMint);
}
enum ConfidentialTransferFeeInstruction {
// We are interested in initilization only
InitializeConfidentialTransferFeeConfig = 0,
// ...
// https://github.com/solana-labs/solana-program-library/blob/d4bbd51b5167d3f0c8a247b5f304a92e6482cd6f/token/program-2022/src/extension/confidential_transfer_fee/instruction.rs#L37
}
const TOKEN_INSTRUCTION_CONFIDENTIAL_TRANSFER_FEE_CONFIG_EXTENSION = 37;
const EXTENSION_TYPE_CONFIDENTIAL_TRANSFER_FEE_CONFIG = 16 as ExtensionType;
interface InitializeConfidentialTransferFeeConfigInstructionData {
//TokenInstruction.ConfidentialTransferFeeExtension = 37 is commented out
//instruction: TokenInstruction.ConfidentialTransferFeeExtension;
instruction: 37;
confidentialTransferFeeInstruction: ConfidentialTransferFeeInstruction.InitializeConfidentialTransferFeeConfig;
authority: PublicKey | null;
withdrawWithheldAuthorityElgamalPubkey: PublicKey | null;
}
/*
Sample transaction instruction data
25 00 d1 4f 53 ad b4 2c 4c 61 09 57 13 38 5d 13
6b e7 d5 37 30 d4 38 4a 38 d3 4c 84 cd c6 a9 93
83 09 1c 37 e6 43 3b 73 04 dd 82 73 7a e4 0d 9b
8b f3 c4 9f 5b 0e 6c 49 a8 d5 33 28 b3 e5 06 90
1c 57
data length: 67 bytes
1: confidential transfer fee prefix
1: confidential transfer fee ix
32: authority
32: withdraw withheld authority elgamal pubkey
*/
const initializeConfidentialTransferFeeConfigInstructionData =
struct<InitializeConfidentialTransferFeeConfigInstructionData>([
u8("instruction"),
u8("confidentialTransferFeeInstruction"),
publicKey("authority"),
publicKey("withdrawWithheldAuthorityElgamalPubkey"),
]);
export function createInitializeConfidentialTransferFeeConfigInstruction(
mint: PublicKey,
authority: PublicKey,
withdrawWithheldAuthorityElgamalPubkey: PublicKey = PublicKey.default,
programId: PublicKey = TOKEN_2022_PROGRAM_ID,
) {
if (!programSupportsExtensions(programId)) {
throw new TokenUnsupportedInstructionError();
}
const keys = [{ pubkey: mint, isSigner: false, isWritable: true }];
const data = Buffer.alloc(
initializeConfidentialTransferFeeConfigInstructionData.span,
);
initializeConfidentialTransferFeeConfigInstructionData.encode(
{
instruction: TOKEN_INSTRUCTION_CONFIDENTIAL_TRANSFER_FEE_CONFIG_EXTENSION,
confidentialTransferFeeInstruction:
ConfidentialTransferFeeInstruction.InitializeConfidentialTransferFeeConfig,
authority,
withdrawWithheldAuthorityElgamalPubkey,
},
data,
);
return new TransactionInstruction({ keys, programId, data });
}
export async function hasConfidentialTransferFeeConfigExtension(
provider: AnchorProvider,
mint: PublicKey,
): Promise<boolean> {
const account = await getMint(
provider.connection,
mint,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const extensions = getExtensionTypes(account.tlvData);
return extensions.includes(EXTENSION_TYPE_CONFIDENTIAL_TRANSFER_FEE_CONFIG);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/token-2022.ts
|
import type { AnchorProvider } from "@coral-xyz/anchor";
import { BN, web3 } from "@coral-xyz/anchor";
import {
AddressUtil,
TokenUtil,
TransactionBuilder,
U64_MAX,
} from "@orca-so/common-sdk";
import type { Mint, TransferFee } from "@solana/spl-token";
import {
AccountLayout,
AccountState,
ExtensionType,
LENGTH_SIZE,
NATIVE_MINT,
NATIVE_MINT_2022,
TYPE_SIZE,
addExtraAccountMetasForExecute,
calculateFee,
createApproveInstruction,
createAssociatedTokenAccountInstruction,
createCreateNativeMintInstruction,
createDisableRequiredMemoTransfersInstruction,
createEnableRequiredMemoTransfersInstruction,
createInitializeAccount3Instruction,
createInitializeDefaultAccountStateInstruction,
createInitializeGroupMemberPointerInstruction,
createInitializeGroupPointerInstruction,
createInitializeInterestBearingMintInstruction,
createInitializeMetadataPointerInstruction,
createInitializeMintCloseAuthorityInstruction,
createInitializeMintInstruction,
createInitializeNonTransferableMintInstruction,
createInitializePermanentDelegateInstruction,
createInitializeTransferFeeConfigInstruction,
createInitializeTransferHookInstruction,
createMintToInstruction,
createReallocateInstruction,
getAccount,
getAccountLen,
getAccountTypeOfMintType,
getAssociatedTokenAddressSync,
getExtensionTypes,
getMemoTransfer,
getMint,
getMintLen,
getTypeLen,
} from "@solana/spl-token";
import type { TokenMetadata } from "@solana/spl-token-metadata";
import {
pack as packTokenMetadata,
createInitializeInstruction as createInitializeTokenMetadataInstruction,
} from "@solana/spl-token-metadata";
import type { TokenGroup, TokenGroupMember } from "@solana/spl-token-group";
import {
createInitializeGroupInstruction,
createInitializeMemberInstruction,
packTokenGroup,
packTokenGroupMember,
} from "@solana/spl-token-group";
import {
TEST_TOKEN_PROGRAM_ID,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TRANSFER_HOOK_PROGRAM_ID,
ZERO_BN,
} from "../test-consts";
import type { TokenTrait } from "./init-utils-v2";
import type { AccountMeta } from "@solana/web3.js";
import { Keypair, TransactionInstruction } from "@solana/web3.js";
import invariant from "tiny-invariant";
import { PoolUtil } from "../../../src";
import * as assert from "assert";
import { PublicKey } from "@solana/web3.js";
import { createInitializeExtraAccountMetaListInstruction } from "./test-transfer-hook-program";
import {
createInitializeConfidentialTransferFeeConfigInstruction,
createInitializeConfidentialTransferMintInstruction,
} from "./confidential-transfer";
export async function createMintV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
authority?: web3.PublicKey,
mintKeypair?: web3.Keypair,
): Promise<web3.PublicKey> {
if (authority === undefined) {
authority = provider.wallet.publicKey;
}
if (tokenTrait.isNativeMint) {
if (tokenTrait.isToken2022) {
await initializeNativeMint2022Idempotent(provider);
return NATIVE_MINT_2022;
}
return NATIVE_MINT;
}
const mint = mintKeypair ?? web3.Keypair.generate();
const instructions = await createMintInstructions(
provider,
tokenTrait,
authority,
mint.publicKey,
);
const tx = new web3.Transaction();
tx.add(...instructions);
await provider.sendAndConfirm(tx, [mint], { commitment: "confirmed" });
return mint.publicKey;
}
async function createMintInstructions(
provider: AnchorProvider,
tokenTrait: TokenTrait,
authority: web3.PublicKey,
mint: web3.PublicKey,
) {
invariant(
!tokenTrait.isNativeMint,
"Cannot create a mint for the native token",
);
if (!tokenTrait.isToken2022) {
const instructions = [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: mint,
space: 82,
lamports:
await provider.connection.getMinimumBalanceForRentExemption(82),
programId: TEST_TOKEN_PROGRAM_ID,
}),
createInitializeMintInstruction(
mint,
0,
authority,
tokenTrait.hasFreezeAuthority ? authority : null,
TEST_TOKEN_PROGRAM_ID,
),
];
return instructions;
} else {
const fixedLengthExtensions: ExtensionType[] = [];
const rentReservedSpace: number[] = [];
const extensions: TransactionInstruction[] = [];
const postInitialization: TransactionInstruction[] = [];
// PermanentDelegate
if (tokenTrait.hasPermanentDelegate) {
fixedLengthExtensions.push(ExtensionType.PermanentDelegate);
extensions.push(
createInitializePermanentDelegateInstruction(
mint,
authority,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// TransferFee
if (tokenTrait.hasTransferFeeExtension) {
fixedLengthExtensions.push(ExtensionType.TransferFeeConfig);
extensions.push(
createInitializeTransferFeeConfigInstruction(
mint,
authority,
authority,
tokenTrait.transferFeeInitialBps ?? 500, // default: 5%
tokenTrait.transferFeeInitialMax ?? BigInt(U64_MAX.toString()), // default: virtually unlimited
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// TransferHook
if (tokenTrait.hasTransferHookExtension) {
fixedLengthExtensions.push(ExtensionType.TransferHook);
extensions.push(
createInitializeTransferHookInstruction(
mint,
authority,
TEST_TRANSFER_HOOK_PROGRAM_ID,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
// create ExtraAccountMetaList account
postInitialization.push(
createInitializeExtraAccountMetaListInstruction(
provider.wallet.publicKey,
mint,
),
);
}
// ConfidentialTransfer
// [March 6, 2024] getTypeLen(ExtensionType.ConfidentialTransferMint) return 97, but 65 (2 pubkey + 1 bool) is valid
// https://github.com/solana-labs/solana-program-library/blob/d72289c79a04411c69a8bf1054f7156b6196f9b3/token/js/src/extensions/extensionType.ts#L74
let confidentialTransferMintSizePatch = 0;
if (tokenTrait.hasConfidentialTransferExtension) {
fixedLengthExtensions.push(ExtensionType.ConfidentialTransferMint);
confidentialTransferMintSizePatch =
65 - getTypeLen(ExtensionType.ConfidentialTransferMint);
extensions.push(
createInitializeConfidentialTransferMintInstruction(
mint,
authority,
true, // autoApproveNewAccounts
PublicKey.default, // auditorElgamal
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// ConfidentialTransferFeeConfig
// When both TransferFeeConfig and ConfidentialTransferMint are enabled, ConfidentialTransferFeeConfig is also required
let confidentialTransferFeeConfigSizePatch = 0;
if (
tokenTrait.hasTransferFeeExtension &&
tokenTrait.hasConfidentialTransferExtension
) {
// fixedLengthExtensions.push(ExtensionType.ConfidentialTransferFeeConfig);
// [May 25, 2024] ExtensionType.ConfidentialTransferFeeConfig is not yet supported in spl-token
// ConfidentialTransferFeeConfig struct fields:
// - authority: OptionalNonZeroPubkey (32 bytes)
// - withdraw_withheld_authority_elgamal_pubkey: ElGamalPubkey (32 bytes)
// - harvest_to_mint_enabled: bool (1 byte)
// - withheld_amount: EncryptedWithheldAmount (64 bytes)
confidentialTransferFeeConfigSizePatch = 2 + 2 + 129; // type + length + data
extensions.push(
createInitializeConfidentialTransferFeeConfigInstruction(
mint,
authority,
authority,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// InterestBearing
if (tokenTrait.hasInterestBearingExtension) {
fixedLengthExtensions.push(ExtensionType.InterestBearingConfig);
extensions.push(
createInitializeInterestBearingMintInstruction(
mint,
authority,
tokenTrait.interestBearingRate ?? 1, // default 1/10000
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// CloseMintAuthority
if (tokenTrait.hasMintCloseAuthorityExtension) {
fixedLengthExtensions.push(ExtensionType.MintCloseAuthority);
extensions.push(
createInitializeMintCloseAuthorityInstruction(
mint,
authority,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// DefaultAccountState
if (tokenTrait.hasDefaultAccountStateExtension) {
fixedLengthExtensions.push(ExtensionType.DefaultAccountState);
extensions.push(
createInitializeDefaultAccountStateInstruction(
mint,
tokenTrait.defaultAccountInitialState ?? AccountState.Frozen,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// NonTransferableMint
if (tokenTrait.hasNonTransferableExtension) {
fixedLengthExtensions.push(ExtensionType.NonTransferable);
extensions.push(
createInitializeNonTransferableMintInstruction(
mint,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// TokenMetadata
if (tokenTrait.hasTokenMetadataExtension) {
const identifier = mint.toBase58().slice(0, 8);
const metadata: TokenMetadata = {
mint,
updateAuthority: authority,
name: `test token ${identifier}`,
symbol: identifier,
uri: `https://test.orca.so/${identifier}.json`,
additionalMetadata: [],
};
const tokenMetadataSize = packTokenMetadata(metadata).length;
const tokenMetadataExtensionSize =
TYPE_SIZE + LENGTH_SIZE + tokenMetadataSize;
rentReservedSpace.push(tokenMetadataExtensionSize);
postInitialization.push(
createInitializeTokenMetadataInstruction({
metadata: mint,
mint,
mintAuthority: authority,
updateAuthority: metadata.updateAuthority!,
name: metadata.name,
symbol: metadata.symbol,
uri: metadata.uri,
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
);
}
// MetadataPointer
if (tokenTrait.hasMetadataPointerExtension) {
fixedLengthExtensions.push(ExtensionType.MetadataPointer);
extensions.push(
createInitializeMetadataPointerInstruction(
mint,
authority,
mint,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// GroupPointer
if (tokenTrait.hasGroupPointerExtension) {
fixedLengthExtensions.push(ExtensionType.GroupPointer);
extensions.push(
createInitializeGroupPointerInstruction(
mint,
authority,
mint,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// MemberPointer
if (tokenTrait.hasGroupMemberPointerExtension) {
fixedLengthExtensions.push(ExtensionType.GroupMemberPointer);
extensions.push(
createInitializeGroupMemberPointerInstruction(
mint,
authority,
null,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
}
// Group
if (tokenTrait.hasGroupExtension) {
const groupData: TokenGroup = {
mint,
updateAuthority: authority,
maxSize: 10n,
size: 10n,
};
const tokenGroupSize = packTokenGroup(groupData).length;
const tokenGroupExtensionSize = TYPE_SIZE + LENGTH_SIZE + tokenGroupSize;
rentReservedSpace.push(tokenGroupExtensionSize);
postInitialization.push(
createInitializeGroupInstruction({
// maybe this data is meaning less, but it is okay, because we use this to test rejecting it.
mint: mint,
mintAuthority: authority,
updateAuthority: PublicKey.default, // groupData.updateAuthority!,
group: mint,
maxSize: groupData.maxSize,
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
);
}
// Member
if (tokenTrait.hasGroupMemberExtension) {
const groupMemberData: TokenGroupMember = {
mint: mint,
group: mint,
memberNumber: 10n,
};
const tokenGroupMemberSize = packTokenGroupMember(groupMemberData).length;
const tokenGroupMemberExtensionSize =
TYPE_SIZE + LENGTH_SIZE + tokenGroupMemberSize;
rentReservedSpace.push(tokenGroupMemberExtensionSize);
postInitialization.push(
createInitializeMemberInstruction({
// maybe this data is meaning less, but it is okay, because we use this to test rejecting it.
group: mint,
memberMint: mint,
groupUpdateAuthority: authority,
member: mint,
memberMintAuthority: authority,
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
);
}
const space =
getMintLen(fixedLengthExtensions) +
confidentialTransferMintSizePatch +
confidentialTransferFeeConfigSizePatch;
const rentOnlySpace = rentReservedSpace.reduce((sum, n) => {
return sum + n;
}, 0);
const instructions = [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: mint,
space,
lamports: await provider.connection.getMinimumBalanceForRentExemption(
space + rentOnlySpace,
),
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
...extensions,
createInitializeMintInstruction(
mint,
0,
authority,
tokenTrait.hasFreezeAuthority ? authority : null,
TEST_TOKEN_2022_PROGRAM_ID,
),
...postInitialization,
];
return instructions;
}
}
export async function createTokenAccountV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
mint: web3.PublicKey,
owner: web3.PublicKey,
) {
const tokenAccount = web3.Keypair.generate();
const tx = new web3.Transaction();
tx.add(
...(await createTokenAccountInstructions(
provider,
tokenTrait,
tokenAccount.publicKey,
mint,
owner,
)),
);
await provider.sendAndConfirm(tx, [tokenAccount], {
commitment: "confirmed",
});
return tokenAccount.publicKey;
}
export async function createAssociatedTokenAccountV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
mint: web3.PublicKey,
owner: web3.PublicKey,
payer: web3.PublicKey,
) {
const tokenProgram = tokenTrait.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const ataAddress = getAssociatedTokenAddressSync(
mint,
owner,
undefined,
tokenProgram,
);
const instr = createAssociatedTokenAccountInstruction(
payer,
ataAddress,
owner,
mint,
tokenProgram,
);
const tx = new web3.Transaction();
tx.add(instr);
await provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
return ataAddress;
}
async function createTokenAccountInstructions(
provider: AnchorProvider,
tokenTrait: TokenTrait,
newAccountPubkey: web3.PublicKey,
mint: web3.PublicKey,
owner: web3.PublicKey,
lamports?: number,
) {
const mintAccountInfo = await provider.connection.getAccountInfo(mint);
const mintData = await getMint(
provider.connection,
mint,
undefined,
mintAccountInfo!.owner,
);
const isToken2022 = mintAccountInfo!.owner.equals(TEST_TOKEN_2022_PROGRAM_ID);
if (!isToken2022) {
if (lamports === undefined) {
lamports =
await provider.connection.getMinimumBalanceForRentExemption(165);
}
return [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey,
space: 165,
lamports,
programId: TEST_TOKEN_PROGRAM_ID,
}),
createInitializeAccount3Instruction(
newAccountPubkey,
mint,
owner,
TEST_TOKEN_PROGRAM_ID,
),
];
} else {
const accountLen = getAccountLenForMintHack(mintData);
if (lamports === undefined) {
lamports =
await provider.connection.getMinimumBalanceForRentExemption(accountLen);
}
return [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey,
space: accountLen,
lamports,
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
createInitializeAccount3Instruction(
newAccountPubkey,
mint,
owner,
TEST_TOKEN_2022_PROGRAM_ID,
),
];
}
}
export async function mintToDestinationV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
mint: web3.PublicKey,
destination: web3.PublicKey,
amount: number | BN,
): Promise<string> {
const tx = new web3.Transaction();
const amountVal = amount instanceof BN ? BigInt(amount.toString()) : amount;
tx.add(
createMintToInstruction(
mint,
destination,
provider.wallet.publicKey,
amountVal,
undefined,
tokenTrait.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
),
);
return provider.sendAndConfirm(tx, [], { commitment: "confirmed" });
}
export async function createAndMintToTokenAccountV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
mint: web3.PublicKey,
amount: number | BN,
): Promise<web3.PublicKey> {
const tokenAccount = await createTokenAccountV2(
provider,
tokenTrait,
mint,
provider.wallet.publicKey,
);
await mintToDestinationV2(
provider,
tokenTrait,
mint,
tokenAccount,
new BN(amount.toString()),
);
return tokenAccount;
}
export async function createAndMintToAssociatedTokenAccountV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
mint: web3.PublicKey,
amount: number | BN,
destinationWallet?: web3.PublicKey,
payer?: web3.PublicKey,
): Promise<web3.PublicKey> {
const destinationWalletKey = destinationWallet
? destinationWallet
: provider.wallet.publicKey;
const payerKey = payer ? payer : provider.wallet.publicKey;
// Workaround For SOL - just create a wSOL account to satisfy the rest of the test building pipeline.
// Tests who want to test with SOL will have to request their own airdrop.
if (mint.equals(NATIVE_MINT)) {
invariant(tokenTrait.isNativeMint, "Mint must be the native mint");
const rentExemption =
await provider.connection.getMinimumBalanceForRentExemption(
AccountLayout.span,
"confirmed",
);
const txBuilder = new TransactionBuilder(
provider.connection,
provider.wallet,
);
const { address: tokenAccount, ...ix } =
TokenUtil.createWrappedNativeAccountInstruction(
destinationWalletKey,
new BN(amount.toString()),
rentExemption,
);
txBuilder.addInstruction({ ...ix, cleanupInstructions: [] });
await txBuilder.buildAndExecute();
return tokenAccount;
}
if (mint.equals(NATIVE_MINT_2022)) {
invariant(tokenTrait.isNativeMint, "Mint must be the native mint");
const space = getAccountLen([]);
const rentExemption =
await provider.connection.getMinimumBalanceForRentExemption(
space,
"confirmed",
);
const tokenAccountKeypair = Keypair.generate();
const txBuilder = new TransactionBuilder(
provider.connection,
provider.wallet,
);
txBuilder.addInstruction({
instructions: [
web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: tokenAccountKeypair.publicKey,
space,
lamports: rentExemption,
programId: TEST_TOKEN_2022_PROGRAM_ID,
}),
createInitializeAccount3Instruction(
tokenAccountKeypair.publicKey,
mint,
destinationWalletKey,
TEST_TOKEN_2022_PROGRAM_ID,
),
],
cleanupInstructions: [],
signers: [tokenAccountKeypair],
});
await txBuilder.buildAndExecute();
return tokenAccountKeypair.publicKey;
}
const tokenAccounts = await provider.connection.getParsedTokenAccountsByOwner(
destinationWalletKey,
{
programId: tokenTrait.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
},
);
let tokenAccount = tokenAccounts.value
.map((account) => {
if (account.account.data.parsed.info.mint === mint.toString()) {
return account.pubkey;
}
return undefined;
})
.filter(Boolean)[0];
if (!tokenAccount) {
tokenAccount = await createAssociatedTokenAccountV2(
provider,
tokenTrait,
mint,
destinationWalletKey,
payerKey,
);
}
await mintToDestinationV2(
provider,
tokenTrait,
mint,
tokenAccount!,
new BN(amount.toString()),
);
return tokenAccount!;
}
export async function getTokenBalance(
provider: AnchorProvider,
vault: web3.PublicKey,
) {
return (await provider.connection.getTokenAccountBalance(vault, "confirmed"))
.value.amount;
}
export async function createInOrderMintsV2(
provider: AnchorProvider,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
) {
if (tokenTraitA.isNativeMint && !tokenTraitB.isNativeMint) {
const tokenXMintPubKey = tokenTraitA.isToken2022
? NATIVE_MINT_2022
: NATIVE_MINT;
let ordered;
do {
const tokenYMintPubKey = await createMintV2(provider, tokenTraitB);
ordered = PoolUtil.orderMints(tokenXMintPubKey, tokenYMintPubKey).map(
AddressUtil.toPubKey,
);
} while (!ordered[0].equals(tokenXMintPubKey));
return ordered;
} else if (!tokenTraitA.isNativeMint && tokenTraitB.isNativeMint) {
const tokenYMintPubKey = tokenTraitB.isToken2022
? NATIVE_MINT_2022
: NATIVE_MINT;
let ordered;
do {
const tokenXMintPubKey = await createMintV2(provider, tokenTraitA);
ordered = PoolUtil.orderMints(tokenXMintPubKey, tokenYMintPubKey).map(
AddressUtil.toPubKey,
);
} while (!ordered[1].equals(tokenYMintPubKey));
return ordered;
} else if (!tokenTraitA.isNativeMint && !tokenTraitB.isNativeMint) {
while (true) {
const tokenXMintPubKey = await createMintV2(provider, tokenTraitA);
const tokenYMintPubKey = await createMintV2(provider, tokenTraitB);
const ordered = PoolUtil.orderMints(
tokenXMintPubKey,
tokenYMintPubKey,
).map(AddressUtil.toPubKey);
if (ordered[0].equals(tokenXMintPubKey)) {
return ordered;
}
}
} else {
// A must be WSOL: So11111111111111111111111111111111111111112
// B must be WSOL-2022: 9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP
invariant(!tokenTraitA.isToken2022, "A must be the native mint");
invariant(tokenTraitB.isToken2022, "B must be the native mint 2022");
return [NATIVE_MINT, NATIVE_MINT_2022];
}
}
export async function initializeNativeMint2022Idempotent(
provider: AnchorProvider,
) {
const accountInfo = await provider.connection.getAccountInfo(
NATIVE_MINT_2022,
"confirmed",
);
// already initialized
if (accountInfo !== null) return;
const ix = createCreateNativeMintInstruction(
provider.wallet.publicKey,
NATIVE_MINT_2022,
TEST_TOKEN_2022_PROGRAM_ID,
);
const txBuilder = new TransactionBuilder(
provider.connection,
provider.wallet,
);
txBuilder.addInstruction({
instructions: [ix],
cleanupInstructions: [],
signers: [],
});
await txBuilder.buildAndExecute();
}
export async function approveTokenV2(
provider: AnchorProvider,
tokenTrait: TokenTrait,
tokenAccount: web3.PublicKey,
delegate: web3.PublicKey,
amount: number | BN,
owner?: web3.Keypair,
) {
const tx = new web3.Transaction();
const tokenProgram = tokenTrait.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const amountVal = amount instanceof BN ? BigInt(amount.toString()) : amount;
tx.add(
createApproveInstruction(
tokenAccount,
delegate,
owner?.publicKey || provider.wallet.publicKey,
amountVal,
undefined,
tokenProgram,
),
);
return provider.sendAndConfirm(tx, !!owner ? [owner] : [], {
commitment: "confirmed",
});
}
export async function enableRequiredMemoTransfers(
provider: AnchorProvider,
tokenAccount: web3.PublicKey,
owner?: web3.Keypair,
) {
const tx = new web3.Transaction();
tx.add(
createReallocateInstruction(
tokenAccount,
owner?.publicKey || provider.wallet.publicKey,
[ExtensionType.MemoTransfer],
owner?.publicKey || provider.wallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
tx.add(
createEnableRequiredMemoTransfersInstruction(
tokenAccount,
owner?.publicKey || provider.wallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
return provider.sendAndConfirm(tx, !!owner ? [owner] : [], {
commitment: "confirmed",
});
}
export async function disableRequiredMemoTransfers(
provider: AnchorProvider,
tokenAccount: web3.PublicKey,
owner?: web3.Keypair,
) {
const tx = new web3.Transaction();
tx.add(
createDisableRequiredMemoTransfersInstruction(
tokenAccount,
owner?.publicKey || provider.wallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
),
);
return provider.sendAndConfirm(tx, !!owner ? [owner] : [], {
commitment: "confirmed",
});
}
export async function isRequiredMemoTransfersEnabled(
provider: AnchorProvider,
tokenAccount: web3.PublicKey,
) {
const account = await getAccount(
provider.connection,
tokenAccount,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const extensions = getExtensionTypes(account.tlvData);
if (!extensions.includes(ExtensionType.MemoTransfer)) return false;
const memoTransferData = getMemoTransfer(account);
return memoTransferData?.requireIncomingTransferMemos;
}
export async function asyncAssertTokenVaultV2(
provider: AnchorProvider,
account: web3.PublicKey,
expectedMint: web3.PublicKey,
expectedAccountOwner: web3.PublicKey,
expectedTokenProgram: web3.PublicKey,
) {
const accountInfo = await provider.connection.getAccountInfo(account);
assert.ok(accountInfo);
assert.ok(accountInfo.owner.equals(expectedTokenProgram));
const parsedAccount = AccountLayout.decode(accountInfo.data);
assert.ok(parsedAccount.mint.equals(expectedMint));
assert.ok(parsedAccount.owner.equals(expectedAccountOwner));
}
export async function asyncAssertOwnerProgram(
provider: AnchorProvider,
account: web3.PublicKey,
programId: web3.PublicKey,
) {
const accountInfo = await provider.connection.getAccountInfo(account);
assert.ok(accountInfo);
assert.ok(accountInfo.owner.equals(programId));
}
export async function getExtraAccountMetasForHookProgram(
provider: AnchorProvider,
hookProgramId: web3.PublicKey,
source: web3.PublicKey,
mint: web3.PublicKey,
destination: web3.PublicKey,
owner: web3.PublicKey,
amount: number | bigint,
): Promise<AccountMeta[] | undefined> {
const instruction = new TransactionInstruction({
programId: TEST_TOKEN_2022_PROGRAM_ID,
keys: [
{ pubkey: source, isSigner: false, isWritable: false },
{ pubkey: mint, isSigner: false, isWritable: false },
{ pubkey: destination, isSigner: false, isWritable: false },
{ pubkey: owner, isSigner: false, isWritable: false },
{ pubkey: owner, isSigner: false, isWritable: false },
],
});
await addExtraAccountMetasForExecute(
provider.connection,
instruction,
hookProgramId,
source,
mint,
destination,
owner,
amount,
"confirmed",
);
const extraAccountMetas = instruction.keys.slice(5);
return extraAccountMetas.length > 0 ? extraAccountMetas : undefined;
}
function ceil_div_bn(num: BN, denom: BN): BN {
return num.add(denom.subn(1)).div(denom);
}
export function calculateTransferFeeIncludedAmount(
transferFee: TransferFee,
amount: BN,
): { amount: BN; fee: BN } {
// https://github.com/solana-labs/solana-program-library/blob/master/token/program-2022/src/extension/transfer_fee/mod.rs#L90
const ONE_IN_BASIS_POINTS = 10_000;
const maxFeeBN = new BN(transferFee.maximumFee.toString());
// edge cases
if (transferFee.transferFeeBasisPoints === 0) {
return {
amount,
fee: ZERO_BN,
};
}
if (amount.isZero()) {
return {
amount: ZERO_BN,
fee: ZERO_BN,
};
}
if (transferFee.transferFeeBasisPoints === ONE_IN_BASIS_POINTS) {
if (amount.add(maxFeeBN).gt(U64_MAX)) {
throw new Error("TransferFeeIncludedAmount exceeds U64_MAX");
}
return {
amount: amount.add(maxFeeBN),
fee: maxFeeBN,
};
}
// normal case
const num = amount.muln(ONE_IN_BASIS_POINTS);
const denom = new BN(
ONE_IN_BASIS_POINTS - transferFee.transferFeeBasisPoints,
);
const rawFeeIncludedAmount = ceil_div_bn(num, denom);
if (rawFeeIncludedAmount.sub(amount).gte(maxFeeBN)) {
if (amount.add(maxFeeBN).gt(U64_MAX)) {
throw new Error("TransferFeeIncludedAmount exceeds U64_MAX");
}
return {
amount: amount.add(maxFeeBN),
fee: maxFeeBN,
};
}
if (rawFeeIncludedAmount.gt(U64_MAX)) {
throw new Error("TransferFeeIncludedAmount exceeds U64_MAX");
}
return {
amount: rawFeeIncludedAmount,
fee: rawFeeIncludedAmount.sub(amount),
};
}
export function calculateTransferFeeExcludedAmount(
transferFee: TransferFee,
amount: BN,
): { amount: BN; fee: BN } {
const fee = calculateFee(transferFee, BigInt(amount.toString()));
const feeBN = new BN(fee.toString());
return {
amount: amount.sub(feeBN),
fee: feeBN,
};
}
export async function mintTokensToTestAccountV2(
provider: AnchorProvider,
tokenAMint: PublicKey,
tokenTraitA: TokenTrait,
tokenMintForA: number,
tokenBMint: PublicKey,
tokenTraitB: TokenTrait,
tokenMintForB: number,
destinationWallet?: PublicKey,
) {
const userTokenAAccount = await createAndMintToAssociatedTokenAccountV2(
provider,
tokenTraitA,
tokenAMint,
tokenMintForA,
destinationWallet,
);
const userTokenBAccount = await createAndMintToAssociatedTokenAccountV2(
provider,
tokenTraitB,
tokenBMint,
tokenMintForB,
destinationWallet,
);
return [userTokenAAccount, userTokenBAccount];
}
function getAccountLenForMintHack(mintData: Mint): number {
const extensionTypes = getExtensionTypes(mintData.tlvData);
// spl-token cannot handle ConfidentialTransferFeeConfig yet, so we need to patch...
// 16: ConfidentialTransferFeeConfig
if (!extensionTypes.includes(16 as ExtensionType)) {
return getAccountLen(extensionTypes.map(getAccountTypeOfMintType));
}
const confidentialTransferFeeAmountLen = 2 + 2 + 64;
return (
getAccountLen(
extensionTypes
.filter((type) => type !== (16 as ExtensionType))
.map(getAccountTypeOfMintType),
) + confidentialTransferFeeAmountLen
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/aquarium-v2.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import { AddressUtil, MathUtil } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import Decimal from "decimal.js";
import { TickSpacing } from "..";
import type {
InitFeeTierParams,
InitPoolV2Params,
WhirlpoolContext,
} from "../../../src";
import { PDAUtil, WhirlpoolIx, toTx } from "../../../src";
import { PoolUtil } from "../../../src/utils/public/pool-utils";
import type { TestConfigParams } from "../test-builders";
import { generateDefaultConfigParams } from "../test-builders";
import type { FundedPositionV2Params, TokenTrait } from "./init-utils-v2";
import {
fundPositionsV2,
generateDefaultConfigExtensionParams,
isTokenBadgeRequired,
} from "./init-utils-v2";
import { initFeeTier, initTickArrayRange } from "../init-utils";
import {
createAndMintToAssociatedTokenAccountV2,
createMintV2,
} from "./token-2022";
import invariant from "tiny-invariant";
interface InitTestFeeTierV2Params {
tickSpacing: number;
feeRate?: number;
}
interface InitTestPoolV2Params {
mintIndices: [number, number];
tickSpacing: number;
feeTierIndex?: number;
initSqrtPrice?: anchor.BN;
}
interface InitTestMintV2Params {
tokenTrait: TokenTrait;
}
interface InitTestTokenAccV2Params {
mintIndex: number;
mintAmount?: anchor.BN;
}
interface InitTestTickArrayRangeV2Params {
poolIndex: number;
startTickIndex: number;
arrayCount: number;
aToB: boolean;
}
interface InitTestPositionV2Params {
poolIndex: number;
fundParams: FundedPositionV2Params[];
}
export interface InitAquariumV2Params {
// Single-ton per aquarium
configParams?: TestConfigParams;
initFeeTierParams: InitTestFeeTierV2Params[];
initMintParams: InitTestMintV2Params[];
initTokenAccParams: InitTestTokenAccV2Params[];
initPoolParams: InitTestPoolV2Params[];
initTickArrayRangeParams: InitTestTickArrayRangeV2Params[];
initPositionParams: InitTestPositionV2Params[];
}
export interface TestAquarium {
configParams: TestConfigParams;
feeTierParams: InitFeeTierParams[];
mintKeys: PublicKey[];
tokenAccounts: {
mint: PublicKey;
account: PublicKey;
tokenTrait: TokenTrait;
}[];
pools: InitPoolV2Params[];
tickArrays: { params: InitTestTickArrayRangeV2Params; pdas: PDA[] }[];
}
const DEFAULT_FEE_RATE = 3000;
const DEFAULT_MINT_AMOUNT = new anchor.BN("15000000000");
const DEFAULT_SQRT_PRICE = MathUtil.toX64(new Decimal(5));
const DEFAULT_INIT_FEE_TIER = [{ tickSpacing: TickSpacing.Standard }];
const DEFAULT_INIT_MINT: InitTestMintV2Params[] = [
{ tokenTrait: { isToken2022: true } },
{ tokenTrait: { isToken2022: true } },
];
const DEFAULT_INIT_TOKEN = [{ mintIndex: 0 }, { mintIndex: 1 }];
const DEFAULT_INIT_POOL: InitTestPoolV2Params[] = [
{ mintIndices: [0, 1], tickSpacing: TickSpacing.Standard },
];
const DEFAULT_INIT_TICK_ARR: InitTestTickArrayRangeV2Params[] = [];
const DEFAULT_INIT_POSITION: InitTestPositionV2Params[] = [];
export function getDefaultAquariumV2(): InitAquariumV2Params {
return {
initFeeTierParams: [...DEFAULT_INIT_FEE_TIER],
initMintParams: [...DEFAULT_INIT_MINT],
initTokenAccParams: [...DEFAULT_INIT_TOKEN],
initPoolParams: [...DEFAULT_INIT_POOL],
initTickArrayRangeParams: [...DEFAULT_INIT_TICK_ARR],
initPositionParams: [...DEFAULT_INIT_POSITION],
};
}
export async function buildTestAquariumsV2(
ctx: WhirlpoolContext,
initParams: InitAquariumV2Params[],
): Promise<TestAquarium[]> {
const aquariums: TestAquarium[] = [];
// Airdrop SOL into provider wallet;
await ctx.connection.requestAirdrop(
ctx.provider.wallet.publicKey,
100_000_000_000_000,
);
for (const initParam of initParams) {
// Create configs
let configParams = initParam.configParams;
if (!configParams) {
configParams = generateDefaultConfigParams(ctx);
}
// Could batch
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, configParams.configInitInfo),
).buildAndExecute();
// initialize ConfigExtension
const {
configExtensionInitInfo,
configExtensionSetTokenBadgeAuthorityInfo,
configExtensionKeypairs,
} = generateDefaultConfigExtensionParams(
ctx,
configParams.configInitInfo.whirlpoolsConfigKeypair.publicKey,
configParams.configKeypairs.feeAuthorityKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(
ctx.program,
configExtensionInitInfo,
),
)
.addSigner(configParams.configKeypairs.feeAuthorityKeypair)
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(
ctx.program,
configExtensionSetTokenBadgeAuthorityInfo,
),
)
.addSigner(configParams.configKeypairs.feeAuthorityKeypair)
.buildAndExecute();
const {
initFeeTierParams,
initMintParams,
initTokenAccParams,
initPoolParams,
initTickArrayRangeParams,
initPositionParams,
} = initParam;
const feeTierParams: InitFeeTierParams[] = [];
for (const initFeeTierParam of initFeeTierParams) {
const { tickSpacing } = initFeeTierParam;
const feeRate =
initFeeTierParam.feeRate !== undefined
? initFeeTierParam.feeRate
: DEFAULT_FEE_RATE;
const { params } = await initFeeTier(
ctx,
configParams.configInitInfo,
configParams.configKeypairs.feeAuthorityKeypair,
tickSpacing,
feeRate,
);
feeTierParams.push(params);
}
// TODO: handle nativeMint
initMintParams.forEach((initMintParam) => {
invariant(
!initMintParam.tokenTrait.isNativeMint,
"Native mint not supported",
);
});
const mintKeypairs = initMintParams
.map(() => Keypair.generate())
.sort((a, b) => PoolUtil.compareMints(a.publicKey, b.publicKey));
const mintKeys = await Promise.all(
initMintParams.map(({ tokenTrait }, i) =>
createMintV2(ctx.provider, tokenTrait, undefined, mintKeypairs[i]),
),
);
// create TokenBadge if needed
await Promise.all(
initMintParams.map(({ tokenTrait }, i) => {
if (isTokenBadgeRequired(tokenTrait)) {
return toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
tokenMint: mintKeys[i],
tokenBadgeAuthority:
configExtensionKeypairs.tokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda: PDAUtil.getTokenBadge(
ctx.program.programId,
configParams!.configInitInfo.whirlpoolsConfigKeypair.publicKey,
mintKeys[i],
),
whirlpoolsConfig:
configParams!.configInitInfo.whirlpoolsConfigKeypair.publicKey,
whirlpoolsConfigExtension:
configExtensionInitInfo.whirlpoolsConfigExtensionPda.publicKey,
funder: ctx.wallet.publicKey,
}),
)
.addSigner(configExtensionKeypairs.tokenBadgeAuthorityKeypair)
.buildAndExecute();
}
return Promise.resolve();
}),
);
const tokenAccounts = await Promise.all(
initTokenAccParams.map(async (initTokenAccParam) => {
const { mintIndex, mintAmount = DEFAULT_MINT_AMOUNT } =
initTokenAccParam;
const mintKey = mintKeys[mintIndex];
const tokenTrait = initMintParams[mintIndex].tokenTrait;
const account = await createAndMintToAssociatedTokenAccountV2(
ctx.provider,
tokenTrait,
mintKey,
mintAmount,
);
return { mint: mintKey, account, tokenTrait };
}),
);
const pools = await Promise.all(
initPoolParams.map(async (initPoolParam) => {
const {
tickSpacing,
mintIndices,
initSqrtPrice = DEFAULT_SQRT_PRICE,
feeTierIndex = 0,
} = initPoolParam;
const [mintOne, mintTwo] = mintIndices.map((idx) => mintKeys[idx]);
const [tokenMintA, tokenMintB] = PoolUtil.orderMints(
mintOne,
mintTwo,
).map(AddressUtil.toPubKey);
const isInverted = mintOne.equals(tokenMintB);
invariant(!isInverted, "should not be inverted");
const configKey =
configParams!.configInitInfo.whirlpoolsConfigKeypair.publicKey;
const whirlpoolPda = PDAUtil.getWhirlpool(
ctx.program.programId,
configKey,
tokenMintA,
tokenMintB,
tickSpacing,
);
const tokenBadgeAPda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKey,
tokenMintA,
);
const tokenBadgeBPda = PDAUtil.getTokenBadge(
ctx.program.programId,
configKey,
tokenMintB,
);
const tokenProgramA = (await ctx.connection.getAccountInfo(tokenMintA))!
.owner;
const tokenProgramB = (await ctx.connection.getAccountInfo(tokenMintB))!
.owner;
const poolParam: InitPoolV2Params = {
initSqrtPrice,
whirlpoolsConfig: configKey,
tokenMintA,
tokenMintB,
tokenBadgeA: tokenBadgeAPda.publicKey,
tokenBadgeB: tokenBadgeBPda.publicKey,
tokenProgramA,
tokenProgramB,
whirlpoolPda,
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
feeTierKey: feeTierParams[feeTierIndex].feeTierPda.publicKey,
tickSpacing,
// TODO: funder
funder: ctx.wallet.publicKey,
};
const tx = toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, poolParam),
);
await tx.buildAndExecute();
return poolParam;
}),
);
const tickArrays = await Promise.all(
initTickArrayRangeParams.map(async (initTickArrayRangeParam) => {
const { poolIndex, startTickIndex, arrayCount, aToB } =
initTickArrayRangeParam;
const pool = pools[poolIndex];
const pdas = await initTickArrayRange(
ctx,
pool.whirlpoolPda.publicKey,
startTickIndex,
arrayCount,
pool.tickSpacing,
aToB,
);
return {
params: initTickArrayRangeParam,
pdas,
};
}),
);
await Promise.all(
initPositionParams.map(async (initPositionParam) => {
const { poolIndex, fundParams } = initPositionParam;
const pool = pools[poolIndex];
const tokenAccKeys = getTokenAccsForPoolsV2([pool], tokenAccounts);
await fundPositionsV2(
ctx,
pool,
tokenAccKeys[0],
tokenAccKeys[1],
fundParams,
);
}),
);
aquariums.push({
configParams,
feeTierParams,
mintKeys,
tokenAccounts,
pools,
tickArrays,
});
}
return aquariums;
}
export function getTokenAccsForPoolsV2(
pools: InitPoolV2Params[],
tokenAccounts: {
mint: PublicKey;
account: PublicKey;
tokenTrait: TokenTrait;
}[],
) {
const mints: PublicKey[] = [];
for (const pool of pools) {
mints.push(pool.tokenMintA);
mints.push(pool.tokenMintB);
}
return mints.map(
(mint) => tokenAccounts.find((acc) => acc.mint.equals(mint))!.account,
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/fixture-v2.ts
|
import type { BN } from "@coral-xyz/anchor";
import { Keypair, PublicKey } from "@solana/web3.js";
import { TickSpacing, ZERO_BN } from "..";
import type {
InitConfigParams,
InitPoolV2Params,
WhirlpoolContext,
} from "../../../src";
import { TickUtil } from "../../../src";
import { initTickArray } from "../init-utils";
import type {
FundedPositionV2Info,
FundedPositionV2Params,
TokenTrait,
} from "./init-utils-v2";
import {
initRewardAndSetEmissionsV2,
initTestPoolWithTokensV2,
fundPositionsV2,
} from "./init-utils-v2";
interface InitFixtureV2Params {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tickSpacing: number;
initialSqrtPrice?: BN;
mintAmount?: BN;
positions?: FundedPositionV2Params[];
rewards?: RewardV2Param[];
}
interface RewardV2Param {
rewardTokenTrait: TokenTrait;
emissionsPerSecondX64: BN;
vaultAmount: BN;
}
interface InitializedRewardV2Info {
rewardMint: PublicKey;
rewardVaultKeypair: Keypair;
tokenProgram: PublicKey;
}
export class WhirlpoolTestFixtureV2 {
private ctx: WhirlpoolContext;
private poolInitInfo: InitPoolV2Params = defaultPoolInitInfoV2;
private configInitInfo: InitConfigParams = defaultConfigInitInfoV2;
private configKeypairs = defaultConfigKeypairsV2;
private positions: FundedPositionV2Info[] = [];
private rewards: InitializedRewardV2Info[] = [];
private tokenAccountA = PublicKey.default;
private tokenAccountB = PublicKey.default;
private initialized = false;
constructor(ctx: WhirlpoolContext) {
this.ctx = ctx;
}
async init(params: InitFixtureV2Params): Promise<WhirlpoolTestFixtureV2> {
const {
tickSpacing,
initialSqrtPrice,
positions,
rewards,
tokenTraitA,
tokenTraitB,
mintAmount,
} = params;
const {
poolInitInfo,
configInitInfo,
configKeypairs,
configExtension,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokensV2(
this.ctx,
tokenTraitA,
tokenTraitB,
tickSpacing,
initialSqrtPrice,
mintAmount,
);
this.poolInitInfo = poolInitInfo;
this.configInitInfo = configInitInfo;
this.configKeypairs = configKeypairs;
this.tokenAccountA = tokenAccountA;
this.tokenAccountB = tokenAccountB;
if (positions) {
await initTickArraysV2(this.ctx, poolInitInfo, positions);
this.positions = await fundPositionsV2(
this.ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
positions,
);
}
if (rewards) {
const initRewards: InitializedRewardV2Info[] = [];
for (let i = 0; i < rewards.length; i++) {
// Iterate because we enforce sequential initialization on the smart contract
initRewards.push(
await initRewardAndSetEmissionsV2(
this.ctx,
rewards[i].rewardTokenTrait,
configKeypairs.rewardEmissionsSuperAuthorityKeypair,
poolInitInfo.whirlpoolsConfig,
poolInitInfo.whirlpoolPda.publicKey,
i,
rewards[i].vaultAmount,
rewards[i].emissionsPerSecondX64,
configExtension.configExtensionKeypairs.tokenBadgeAuthorityKeypair,
),
);
}
this.rewards = initRewards;
}
this.initialized = true;
return this;
}
getInfos() {
if (!this.initialized) {
throw new Error("Test fixture is not initialized");
}
return {
poolInitInfo: this.poolInitInfo,
configInitInfo: this.configInitInfo,
configKeypairs: this.configKeypairs,
tokenAccountA: this.tokenAccountA,
tokenAccountB: this.tokenAccountB,
positions: this.positions,
rewards: this.rewards,
};
}
}
async function initTickArraysV2(
ctx: WhirlpoolContext,
poolInitInfo: InitPoolV2Params,
positions: FundedPositionV2Params[],
) {
const startTickSet = new Set<number>();
positions.forEach((p) => {
startTickSet.add(
TickUtil.getStartTickIndex(p.tickLowerIndex, poolInitInfo.tickSpacing),
);
startTickSet.add(
TickUtil.getStartTickIndex(p.tickUpperIndex, poolInitInfo.tickSpacing),
);
});
return Promise.all(
Array.from(startTickSet).map((startTick) =>
initTickArray(ctx, poolInitInfo.whirlpoolPda.publicKey, startTick),
),
);
}
const defaultPoolInitInfoV2: InitPoolV2Params = {
initSqrtPrice: ZERO_BN,
whirlpoolsConfig: PublicKey.default,
tokenProgramA: PublicKey.default,
tokenProgramB: PublicKey.default,
tokenMintA: PublicKey.default,
tokenMintB: PublicKey.default,
tokenBadgeA: PublicKey.default,
tokenBadgeB: PublicKey.default,
whirlpoolPda: { publicKey: PublicKey.default, bump: 0 },
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
tickSpacing: TickSpacing.Standard,
feeTierKey: PublicKey.default,
funder: PublicKey.default,
};
const defaultConfigInitInfoV2 = {
whirlpoolsConfigKeypair: Keypair.generate(),
feeAuthority: PublicKey.default,
collectProtocolFeesAuthority: PublicKey.default,
rewardEmissionsSuperAuthority: PublicKey.default,
defaultProtocolFeeRate: 0,
funder: PublicKey.default,
};
const defaultConfigKeypairsV2 = {
feeAuthorityKeypair: Keypair.generate(),
collectProtocolFeesAuthorityKeypair: Keypair.generate(),
rewardEmissionsSuperAuthorityKeypair: Keypair.generate(),
};
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/init-utils-v2.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { MathUtil } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import { ComputeBudgetProgram, Keypair } from "@solana/web3.js";
import type BN from "bn.js";
import Decimal from "decimal.js";
import {
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "..";
import type {
InitConfigParams,
InitPoolV2Params,
InitializeRewardV2Params,
OpenPositionParams,
WhirlpoolContext,
} from "../../../src";
import {
PDAUtil,
PriceMath,
TICK_ARRAY_SIZE,
TickUtil,
WhirlpoolIx,
toTx,
} from "../../../src";
import { PoolUtil } from "../../../src/utils/public/pool-utils";
import type { TestWhirlpoolsConfigKeypairs } from "../test-builders";
import { generateDefaultConfigParams } from "../test-builders";
import { initFeeTier, openPosition, initTickArrayRange } from "../init-utils";
import {
calculateTransferFeeIncludedAmount,
createAndMintToAssociatedTokenAccountV2,
createInOrderMintsV2,
createMintV2,
mintToDestinationV2,
} from "./token-2022";
import type {
InitConfigExtensionParams,
SetTokenBadgeAuthorityParams,
} from "../../../src/instructions";
import { getExtraAccountMetasForTestTransferHookProgram } from "./test-transfer-hook-program";
import type { AccountState } from "@solana/spl-token";
import { getEpochFee, getMint, getTransferFeeConfig } from "@solana/spl-token";
export interface TokenTrait {
isToken2022: boolean;
isNativeMint?: boolean;
hasFreezeAuthority?: boolean;
hasPermanentDelegate?: boolean;
hasTransferFeeExtension?: boolean;
transferFeeInitialBps?: number;
transferFeeInitialMax?: bigint; // u64
hasTransferHookExtension?: boolean;
hasConfidentialTransferExtension?: boolean;
hasInterestBearingExtension?: boolean;
interestBearingRate?: number; // u16
hasMintCloseAuthorityExtension?: boolean;
hasDefaultAccountStateExtension?: boolean;
defaultAccountInitialState?: AccountState;
hasNonTransferableExtension?: boolean;
hasTokenMetadataExtension?: boolean;
hasMetadataPointerExtension?: boolean;
hasGroupExtension?: boolean;
hasGroupPointerExtension?: boolean;
hasGroupMemberExtension?: boolean;
hasGroupMemberPointerExtension?: boolean;
}
interface TestPoolV2Params {
configInitInfo: InitConfigParams;
configKeypairs: TestWhirlpoolsConfigKeypairs;
poolInitInfo: InitPoolV2Params;
feeTierParams: { defaultFeeRate: number };
configExtension: TestConfigExtensionParams;
}
export type FundedPositionV2Params = {
tickLowerIndex: number;
tickUpperIndex: number;
liquidityAmount: anchor.BN;
};
export interface FundedPositionV2Info {
initParams: OpenPositionParams;
publicKey: PublicKey;
tokenAccount: PublicKey;
mintKeypair: Keypair;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
}
const DEFAULT_SQRT_PRICE = MathUtil.toX64(new Decimal(5));
/*
export function getTokenAccsForPools(
pools: InitPoolParams[],
tokenAccounts: { mint: PublicKey; account: PublicKey }[]
) {
const mints = [];
for (const pool of pools) {
mints.push(pool.tokenMintA);
mints.push(pool.tokenMintB);
}
return mints.map((mint) =>
tokenAccounts.find((acc) => acc.mint.equals(mint))!.account
);
}
*/
export async function initTestPoolWithTokensV2(
ctx: WhirlpoolContext,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
tickSpacing: number,
initSqrtPrice = DEFAULT_SQRT_PRICE,
mintAmount = new anchor.BN("15000000000"),
) {
const provider = ctx.provider;
const {
poolInitInfo,
configInitInfo,
configKeypairs,
feeTierParams,
configExtension,
} = await initTestPoolV2(
ctx,
tokenTraitA,
tokenTraitB,
tickSpacing,
initSqrtPrice,
undefined,
);
const { tokenMintA, tokenMintB, whirlpoolPda } = poolInitInfo;
// Airdrop SOL into provider's wallet for SOL native token testing.
const connection = ctx.provider.connection;
const airdropTx = await connection.requestAirdrop(
ctx.provider.wallet.publicKey,
100_000_000_000_000,
);
await ctx.connection.confirmTransaction(
{
signature: airdropTx,
...(await ctx.connection.getLatestBlockhash("confirmed")),
},
"confirmed",
);
const tokenAccountA = await createAndMintToAssociatedTokenAccountV2(
provider,
tokenTraitA,
tokenMintA,
mintAmount,
);
const tokenAccountB = await createAndMintToAssociatedTokenAccountV2(
provider,
tokenTraitB,
tokenMintB,
mintAmount,
);
return {
poolInitInfo,
configInitInfo,
configKeypairs,
feeTierParams,
configExtension,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
};
}
export async function initTestPoolWithLiquidityV2(
ctx: WhirlpoolContext,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
initSqrtPrice = DEFAULT_SQRT_PRICE,
mintAmount = new anchor.BN("15000000000"),
) {
const {
poolInitInfo,
configInitInfo,
configKeypairs,
feeTierParams,
whirlpoolPda,
tokenAccountA,
tokenAccountB,
} = await initTestPoolWithTokensV2(
ctx,
tokenTraitA,
tokenTraitB,
TickSpacing.Standard,
initSqrtPrice,
mintAmount,
);
const tickArrays = await initTickArrayRange(
ctx,
whirlpoolPda.publicKey,
22528, // to 33792
3,
TickSpacing.Standard,
false,
);
const fundParams: FundedPositionV2Params[] = [
{
liquidityAmount: new anchor.BN(100_000),
tickLowerIndex: 27904,
tickUpperIndex: 33408,
},
];
const positionInfos = await fundPositionsV2(
ctx,
poolInitInfo,
tokenAccountA,
tokenAccountB,
fundParams,
);
return {
poolInitInfo,
configInitInfo,
configKeypairs,
positionInfo: positionInfos[0].initParams,
tokenAccountA,
tokenAccountB,
tickArrays,
feeTierParams,
};
}
export async function initTestPoolV2(
ctx: WhirlpoolContext,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
tickSpacing: number,
initSqrtPrice = DEFAULT_SQRT_PRICE,
funder?: Keypair,
) {
const poolParams = await buildTestPoolV2Params(
ctx,
tokenTraitA,
tokenTraitB,
tickSpacing,
3000,
initSqrtPrice,
funder?.publicKey,
);
return initTestPoolFromParamsV2(ctx, poolParams, funder);
}
export async function buildTestPoolV2Params(
ctx: WhirlpoolContext,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
tickSpacing: number,
defaultFeeRate = 3000,
initSqrtPrice = DEFAULT_SQRT_PRICE,
funder?: PublicKey,
createTokenBadgeIfNeededA: boolean = true,
createTokenBadgeIfNeededB: boolean = true,
): Promise<TestPoolV2Params> {
const { configInitInfo, configKeypairs } = generateDefaultConfigParams(ctx);
const {
configExtensionInitInfo,
configExtensionSetTokenBadgeAuthorityInfo,
configExtensionKeypairs,
} = generateDefaultConfigExtensionParams(
ctx,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
configKeypairs.feeAuthorityKeypair.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.initializeConfigIx(ctx.program, configInitInfo),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.initializeConfigExtensionIx(
ctx.program,
configExtensionInitInfo,
),
)
.addSigner(configKeypairs.feeAuthorityKeypair)
.buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.setTokenBadgeAuthorityIx(
ctx.program,
configExtensionSetTokenBadgeAuthorityInfo,
),
)
.addSigner(configKeypairs.feeAuthorityKeypair)
.buildAndExecute();
const { params: feeTierParams } = await initFeeTier(
ctx,
configInitInfo,
configKeypairs.feeAuthorityKeypair,
tickSpacing,
defaultFeeRate,
);
const poolInitInfo = await generateDefaultInitPoolV2Params(
ctx,
configInitInfo.whirlpoolsConfigKeypair.publicKey,
feeTierParams.feeTierPda.publicKey,
tokenTraitA,
tokenTraitB,
tickSpacing,
initSqrtPrice,
funder,
);
if (isTokenBadgeRequired(tokenTraitA) && createTokenBadgeIfNeededA) {
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
tokenMint: poolInitInfo.tokenMintA,
tokenBadgeAuthority:
configExtensionKeypairs.tokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda: {
publicKey: poolInitInfo.tokenBadgeA,
bump: 0 /* dummy */,
},
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpoolsConfigExtension:
configExtensionInitInfo.whirlpoolsConfigExtensionPda.publicKey,
funder: funder ?? ctx.wallet.publicKey,
}),
)
.addSigner(configExtensionKeypairs.tokenBadgeAuthorityKeypair)
.buildAndExecute();
}
if (isTokenBadgeRequired(tokenTraitB) && createTokenBadgeIfNeededB) {
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
tokenMint: poolInitInfo.tokenMintB,
tokenBadgeAuthority:
configExtensionKeypairs.tokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda: {
publicKey: poolInitInfo.tokenBadgeB,
bump: 0 /* dummy */,
},
whirlpoolsConfig: poolInitInfo.whirlpoolsConfig,
whirlpoolsConfigExtension:
configExtensionInitInfo.whirlpoolsConfigExtensionPda.publicKey,
funder: funder ?? ctx.wallet.publicKey,
}),
)
.addSigner(configExtensionKeypairs.tokenBadgeAuthorityKeypair)
.buildAndExecute();
}
return {
configInitInfo,
configKeypairs,
poolInitInfo,
feeTierParams,
configExtension: {
configExtensionInitInfo,
configExtensionSetTokenBadgeAuthorityInfo,
configExtensionKeypairs,
},
};
}
export async function initializeRewardV2(
ctx: WhirlpoolContext,
tokenTrait: TokenTrait,
whirlpoolsConfig: PublicKey,
rewardAuthorityKeypair: anchor.web3.Keypair,
whirlpool: PublicKey,
rewardIndex: number,
tokenBadgeAuthorityKeypair: anchor.web3.Keypair,
funder?: Keypair,
): Promise<{ txId: string; params: InitializeRewardV2Params }> {
const provider = ctx.provider;
const rewardMint = await createMintV2(provider, tokenTrait);
const rewardVaultKeypair = anchor.web3.Keypair.generate();
const rewardTokenBadgePda = PDAUtil.getTokenBadge(
ctx.program.programId,
whirlpoolsConfig,
rewardMint,
);
if (isTokenBadgeRequired(tokenTrait)) {
const configExtensionPda = PDAUtil.getConfigExtension(
ctx.program.programId,
whirlpoolsConfig,
);
await toTx(
ctx,
WhirlpoolIx.initializeTokenBadgeIx(ctx.program, {
tokenMint: rewardMint,
tokenBadgeAuthority: tokenBadgeAuthorityKeypair.publicKey,
tokenBadgePda: rewardTokenBadgePda,
whirlpoolsConfig: whirlpoolsConfig,
whirlpoolsConfigExtension: configExtensionPda.publicKey,
funder: funder?.publicKey ?? ctx.wallet.publicKey,
}),
)
.addSigner(tokenBadgeAuthorityKeypair)
.buildAndExecute();
}
const tokenProgram = tokenTrait.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const params: InitializeRewardV2Params = {
rewardAuthority: rewardAuthorityKeypair.publicKey,
funder: funder?.publicKey || ctx.wallet.publicKey,
whirlpool,
rewardMint,
rewardTokenBadge: rewardTokenBadgePda.publicKey,
rewardVaultKeypair,
rewardIndex,
rewardTokenProgram: tokenProgram,
};
const tx = toTx(
ctx,
WhirlpoolIx.initializeRewardV2Ix(ctx.program, params),
).addSigner(rewardAuthorityKeypair);
if (funder) {
tx.addSigner(funder);
}
return {
txId: await tx.buildAndExecute(),
params,
};
}
export async function initRewardAndSetEmissionsV2(
ctx: WhirlpoolContext,
tokenTrait: TokenTrait,
rewardAuthorityKeypair: anchor.web3.Keypair,
whirlpoolsConfig: PublicKey,
whirlpool: PublicKey,
rewardIndex: number,
vaultAmount: BN | number,
emissionsPerSecondX64: anchor.BN,
tokenBadgeAuthorityKeypair: anchor.web3.Keypair,
funder?: Keypair,
) {
const {
params: { rewardMint, rewardVaultKeypair, rewardTokenProgram },
} = await initializeRewardV2(
ctx,
tokenTrait,
whirlpoolsConfig,
rewardAuthorityKeypair,
whirlpool,
rewardIndex,
tokenBadgeAuthorityKeypair,
funder,
);
await mintToDestinationV2(
ctx.provider,
tokenTrait,
rewardMint,
rewardVaultKeypair.publicKey,
vaultAmount,
);
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
rewardAuthority: rewardAuthorityKeypair.publicKey,
whirlpool,
rewardIndex,
rewardVaultKey: rewardVaultKeypair.publicKey,
emissionsPerSecondX64,
}),
)
.addSigner(rewardAuthorityKeypair)
.buildAndExecute();
return { rewardMint, rewardVaultKeypair, tokenProgram: rewardTokenProgram };
}
////////////////////////////////////////////////////////////////////////////////
// private
////////////////////////////////////////////////////////////////////////////////
async function generateDefaultInitPoolV2Params(
context: WhirlpoolContext,
configKey: PublicKey,
feeTierKey: PublicKey,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
tickSpacing: number,
initSqrtPrice = MathUtil.toX64(new Decimal(5)),
funder?: PublicKey,
): Promise<InitPoolV2Params> {
const [tokenAMintPubKey, tokenBMintPubKey] = await createInOrderMintsV2(
context.provider,
tokenTraitA,
tokenTraitB,
);
const whirlpoolPda = PDAUtil.getWhirlpool(
context.program.programId,
configKey,
tokenAMintPubKey,
tokenBMintPubKey,
tickSpacing,
);
const tokenBadgeAPda = PDAUtil.getTokenBadge(
context.program.programId,
configKey,
tokenAMintPubKey,
);
const tokenBadgeBPda = PDAUtil.getTokenBadge(
context.program.programId,
configKey,
tokenBMintPubKey,
);
return {
initSqrtPrice,
whirlpoolsConfig: configKey,
tokenMintA: tokenAMintPubKey,
tokenMintB: tokenBMintPubKey,
tokenBadgeA: tokenBadgeAPda.publicKey,
tokenBadgeB: tokenBadgeBPda.publicKey,
tokenProgramA: tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
tokenProgramB: tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID,
whirlpoolPda,
tokenVaultAKeypair: Keypair.generate(),
tokenVaultBKeypair: Keypair.generate(),
feeTierKey,
tickSpacing,
funder: funder || context.wallet.publicKey,
};
}
async function initTestPoolFromParamsV2(
ctx: WhirlpoolContext,
poolParams: TestPoolV2Params,
funder?: Keypair,
) {
const {
configInitInfo,
poolInitInfo,
configKeypairs,
feeTierParams,
configExtension,
} = poolParams;
const tx = toTx(
ctx,
WhirlpoolIx.initializePoolV2Ix(ctx.program, poolInitInfo),
);
if (funder) {
tx.addSigner(funder);
}
return {
txId: await tx.buildAndExecute(),
configInitInfo,
configKeypairs,
poolInitInfo,
feeTierParams,
configExtension,
};
}
////////////////////////////////////////////////////////////////////////////////
// position related
////////////////////////////////////////////////////////////////////////////////
export async function withdrawPositionsV2(
ctx: WhirlpoolContext,
tokenTraitA: TokenTrait,
tokenTraitB: TokenTrait,
positionInfos: FundedPositionV2Info[],
tokenOwnerAccountA: PublicKey,
tokenOwnerAccountB: PublicKey,
) {
const fetcher = ctx.fetcher;
const tokenProgramA = tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const tokenProgramB = tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
await Promise.all(
positionInfos.map(async (info) => {
const pool = await fetcher.getPool(info.initParams.whirlpool);
const position = await fetcher.getPosition(
info.initParams.positionPda.publicKey,
);
if (!pool) {
throw new Error(`Failed to fetch pool - ${info.initParams.whirlpool}`);
}
if (!position) {
throw new Error(
`Failed to fetch position - ${info.initParams.whirlpool}`,
);
}
const priceLower = PriceMath.tickIndexToSqrtPriceX64(
position.tickLowerIndex,
);
const priceUpper = PriceMath.tickIndexToSqrtPriceX64(
position.tickUpperIndex,
);
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
position.liquidity,
pool.sqrtPrice,
priceLower,
priceUpper,
false,
);
const numTicksInTickArray = pool.tickSpacing * TICK_ARRAY_SIZE;
const lowerStartTick =
position.tickLowerIndex -
(position.tickLowerIndex % numTicksInTickArray);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
info.initParams.whirlpool,
lowerStartTick,
);
const upperStartTick =
position.tickUpperIndex -
(position.tickUpperIndex % numTicksInTickArray);
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
info.initParams.whirlpool,
upperStartTick,
);
await toTx(
ctx,
WhirlpoolIx.decreaseLiquidityV2Ix(ctx.program, {
liquidityAmount: position.liquidity,
tokenMinA: tokenA,
tokenMinB: tokenB,
whirlpool: info.initParams.whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: info.initParams.positionPda.publicKey,
positionTokenAccount: info.initParams.positionTokenAccount,
tokenMintA: pool.tokenMintA,
tokenMintB: pool.tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: pool.tokenVaultA,
tokenVaultB: pool.tokenVaultB,
tickArrayLower: tickArrayLower.publicKey,
tickArrayUpper: tickArrayUpper.publicKey,
}),
).buildAndExecute();
await toTx(
ctx,
WhirlpoolIx.collectFeesV2Ix(ctx.program, {
whirlpool: info.initParams.whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: info.initParams.positionPda.publicKey,
positionTokenAccount: info.initParams.positionTokenAccount,
tokenMintA: pool.tokenMintA,
tokenMintB: pool.tokenMintB,
tokenProgramA,
tokenProgramB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: pool.tokenVaultA,
tokenVaultB: pool.tokenVaultB,
}),
).buildAndExecute();
}),
);
}
export async function fundPositionsV2(
ctx: WhirlpoolContext,
poolInitInfo: InitPoolV2Params,
tokenAccountA: PublicKey,
tokenAccountB: PublicKey,
fundParams: FundedPositionV2Params[],
): Promise<FundedPositionV2Info[]> {
const {
whirlpoolPda: { publicKey: whirlpool },
tickSpacing,
tokenVaultAKeypair,
tokenVaultBKeypair,
initSqrtPrice,
} = poolInitInfo;
const mintA = await getMint(
ctx.provider.connection,
poolInitInfo.tokenMintA,
"confirmed",
poolInitInfo.tokenProgramA,
);
const mintB = await getMint(
ctx.provider.connection,
poolInitInfo.tokenMintB,
"confirmed",
poolInitInfo.tokenProgramB,
);
const feeConfigA = getTransferFeeConfig(mintA);
const feeConfigB = getTransferFeeConfig(mintB);
const epoch = await ctx.provider.connection.getEpochInfo("confirmed");
return await Promise.all(
fundParams.map(async (param): Promise<FundedPositionV2Info> => {
const { params: positionInfo, mint } = await openPosition(
ctx,
whirlpool,
param.tickLowerIndex,
param.tickUpperIndex,
);
const tickArrayLower = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
TickUtil.getStartTickIndex(param.tickLowerIndex, tickSpacing),
).publicKey;
const tickArrayUpper = PDAUtil.getTickArray(
ctx.program.programId,
whirlpool,
TickUtil.getStartTickIndex(param.tickUpperIndex, tickSpacing),
).publicKey;
if (param.liquidityAmount.gt(ZERO_BN)) {
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
param.liquidityAmount,
initSqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(param.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(param.tickUpperIndex),
true,
);
// transfer fee
const transferFeeA = !feeConfigA
? ZERO_BN
: calculateTransferFeeIncludedAmount(
getEpochFee(feeConfigA, BigInt(epoch.epoch)),
tokenA,
).fee;
const transferFeeB = !feeConfigB
? ZERO_BN
: calculateTransferFeeIncludedAmount(
getEpochFee(feeConfigB, BigInt(epoch.epoch)),
tokenB,
).fee;
//console.info("transfer feeA", transferFeeA.toString(), "/", tokenA.toString());
//console.info("transfer feeB", transferFeeB.toString(), "/", tokenB.toString());
// transfer hook
const tokenTransferHookAccountsA =
await getExtraAccountMetasForTestTransferHookProgram(
ctx.provider,
poolInitInfo.tokenMintA,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.provider.wallet.publicKey,
);
const tokenTransferHookAccountsB =
await getExtraAccountMetasForTestTransferHookProgram(
ctx.provider,
poolInitInfo.tokenMintB,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.provider.wallet.publicKey,
);
await toTx(
ctx,
WhirlpoolIx.increaseLiquidityV2Ix(ctx.program, {
liquidityAmount: param.liquidityAmount,
tokenMaxA: tokenA.add(transferFeeA),
tokenMaxB: tokenB.add(transferFeeB),
whirlpool: whirlpool,
positionAuthority: ctx.provider.wallet.publicKey,
position: positionInfo.positionPda.publicKey,
positionTokenAccount: positionInfo.positionTokenAccount,
tokenMintA: poolInitInfo.tokenMintA,
tokenMintB: poolInitInfo.tokenMintB,
tokenOwnerAccountA: tokenAccountA,
tokenOwnerAccountB: tokenAccountB,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
tokenProgramA: poolInitInfo.tokenProgramA,
tokenProgramB: poolInitInfo.tokenProgramB,
tickArrayLower,
tickArrayUpper,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
}),
)
.prependInstruction(useMaxCU())
.buildAndExecute();
}
return {
initParams: positionInfo,
publicKey: positionInfo.positionPda.publicKey,
tokenAccount: positionInfo.positionTokenAccount,
mintKeypair: mint,
tickArrayLower,
tickArrayUpper,
};
}),
);
}
export interface TestWhirlpoolsConfigExtensionKeypairs {
tokenBadgeAuthorityKeypair: Keypair;
}
export interface TestConfigExtensionParams {
configExtensionInitInfo: InitConfigExtensionParams;
configExtensionSetTokenBadgeAuthorityInfo: SetTokenBadgeAuthorityParams;
configExtensionKeypairs: TestWhirlpoolsConfigExtensionKeypairs;
}
export const generateDefaultConfigExtensionParams = (
context: WhirlpoolContext,
whirlpoolsConfig: PublicKey,
feeAuthority: PublicKey,
funder?: PublicKey,
): TestConfigExtensionParams => {
const configExtensionKeypairs: TestWhirlpoolsConfigExtensionKeypairs = {
tokenBadgeAuthorityKeypair: Keypair.generate(),
};
const configExtensionInitInfo: InitConfigExtensionParams = {
whirlpoolsConfig,
feeAuthority,
whirlpoolsConfigExtensionPda: PDAUtil.getConfigExtension(
context.program.programId,
whirlpoolsConfig,
),
funder: funder || context.wallet.publicKey,
};
const configExtensionSetTokenBadgeAuthorityInfo: SetTokenBadgeAuthorityParams =
{
whirlpoolsConfig,
whirlpoolsConfigExtension:
configExtensionInitInfo.whirlpoolsConfigExtensionPda.publicKey,
configExtensionAuthority: feeAuthority,
newTokenBadgeAuthority:
configExtensionKeypairs.tokenBadgeAuthorityKeypair.publicKey,
};
return {
configExtensionInitInfo,
configExtensionKeypairs,
configExtensionSetTokenBadgeAuthorityInfo,
};
};
export function isTokenBadgeRequired(tokenTrait: TokenTrait): boolean {
if (tokenTrait.hasFreezeAuthority) return true;
if (tokenTrait.hasPermanentDelegate) return true;
if (tokenTrait.hasTransferHookExtension) return true;
return false;
}
export function useCU(cu: number): Instruction {
return {
cleanupInstructions: [],
signers: [],
instructions: [
ComputeBudgetProgram.setComputeUnitLimit({
units: cu,
}),
],
};
}
export function useMaxCU(): Instruction {
return useCU(1_400_000);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/utils/v2/swap-test-utils-v2.ts
|
import type * as anchor from "@coral-xyz/anchor";
import type { Percentage } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type BN from "bn.js";
import type { TickSpacing } from "..";
import type {
Whirlpool,
WhirlpoolClient,
WhirlpoolContext,
} from "../../../src";
import { PoolUtil, PriceMath } from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import type { FundedPositionV2Params, TokenTrait } from "./init-utils-v2";
import { initTestPoolWithTokensV2 } from "./init-utils-v2";
export interface SwapTestPoolParams {
ctx: WhirlpoolContext;
client: WhirlpoolClient;
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tickSpacing: TickSpacing;
initSqrtPrice: anchor.BN;
initArrayStartTicks: number[];
fundedPositions: FundedPositionV2Params[];
tokenMintAmount?: anchor.BN;
}
export interface SwapTestSwapParams {
swapAmount: BN;
aToB: boolean;
amountSpecifiedIsInput: boolean;
slippageTolerance: Percentage;
tickArrayAddresses: PublicKey[];
}
export interface SwapTestSetup {
whirlpool: Whirlpool;
tickArrayAddresses: PublicKey[];
}
export async function setupSwapTestV2(setup: SwapTestPoolParams) {
const { whirlpoolPda } = await initTestPoolWithTokensV2(
setup.ctx,
setup.tokenTraitA,
setup.tokenTraitB,
setup.tickSpacing,
setup.initSqrtPrice,
setup.tokenMintAmount,
);
const whirlpool = await setup.client.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
await (
await whirlpool.initTickArrayForTicks(setup.initArrayStartTicks)
)?.buildAndExecute();
await fundPositionsWithClient(
setup.client,
whirlpoolPda.publicKey,
setup.fundedPositions,
);
return whirlpool;
}
export async function fundPositionsWithClient(
client: WhirlpoolClient,
whirlpoolKey: PublicKey,
fundParams: FundedPositionV2Params[],
) {
const whirlpool = await client.getPool(whirlpoolKey, IGNORE_CACHE);
const whirlpoolData = whirlpool.getData();
await Promise.all(
fundParams.map(async (param) => {
const { tokenA, tokenB } = PoolUtil.getTokenAmountsFromLiquidity(
param.liquidityAmount,
whirlpoolData.sqrtPrice,
PriceMath.tickIndexToSqrtPriceX64(param.tickLowerIndex),
PriceMath.tickIndexToSqrtPriceX64(param.tickUpperIndex),
true,
);
const { tx } = await whirlpool.openPosition(
param.tickLowerIndex,
param.tickUpperIndex,
{
liquidityAmount: param.liquidityAmount,
tokenMaxA: tokenA,
tokenMaxB: tokenB,
},
);
await tx.buildAndExecute();
}),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/types/anchor-types.test.ts
|
import * as assert from "assert";
import { AccountName, getAccountSize } from "../../../src";
describe("anchor-types", () => {
it("all whirlpool account names exist in IDL", async () => {
type ExpectedSize = { [a in AccountName]: number };
const expectedSizes: ExpectedSize = {
[AccountName.WhirlpoolsConfig]: 108,
[AccountName.Position]: 216,
[AccountName.TickArray]: 9988,
[AccountName.Whirlpool]: 653,
[AccountName.FeeTier]: 44,
[AccountName.PositionBundle]: 136,
[AccountName.WhirlpoolsConfigExtension]: 616,
[AccountName.TokenBadge]: 200,
};
Object.values(AccountName).forEach((name) => {
try {
const actualSize = getAccountSize(name);
assert.equal(
actualSize,
expectedSizes[name],
`For ${name} expected ${expectedSizes[name]} but got ${actualSize}`,
);
} catch (e) {
assert.fail(`Error fetching size for ${name}: ${e}`);
}
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/whirlpool-impl-closePosition.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import type { Account } from "@solana/spl-token";
import { getAssociatedTokenAddressSync } from "@solana/spl-token";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { Whirlpool, WhirlpoolClient } from "../../../src";
import {
NUM_REWARDS,
PDAUtil,
WhirlpoolContext,
buildWhirlpoolClient,
collectFeesQuote,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidity,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
TickSpacing,
ZERO_BN,
createAssociatedTokenAccount,
sleep,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import { useMaxCU, type TokenTrait } from "../../utils/v2/init-utils-v2";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("WhirlpoolImpl#closePosition()", () => {
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const vaultStartBalance = 1_000_000;
const tickSpacing = TickSpacing.Standard;
const liquidityAmount = new BN(10_000_000);
beforeAll(() => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
async function accrueFeesAndRewards(
fixture: WhirlpoolTestFixture | WhirlpoolTestFixtureV2,
) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolClient } = testCtx;
const { whirlpoolPda } = poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
// Accrue fees in token A
const pool = await whirlpoolClient.getPool(
whirlpoolPda.publicKey,
IGNORE_CACHE,
);
await (
await pool.swap({
amount: new BN(200_000),
amountSpecifiedIsInput: true,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
otherAmountThreshold: ZERO_BN,
aToB: true,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
})
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// Accrue fees in token B
await (
await pool.swap({
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
})
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// accrue rewards
await sleep(2000);
}
async function removeLiquidity(
fixture: WhirlpoolTestFixture | WhirlpoolTestFixtureV2,
) {
const {
poolInitInfo,
positions: [positionInfo],
} = fixture.getInfos();
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
IGNORE_CACHE,
);
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const liquidityCollectedQuote = await decreaseLiquidityQuoteByLiquidity(
position.getData().liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
const tx = await position.decreaseLiquidity(liquidityCollectedQuote);
// TransferHook require much CU
tx.prependInstruction(useMaxCU());
await tx.buildAndExecute();
}
async function collectFees(
fixture: WhirlpoolTestFixture | WhirlpoolTestFixtureV2,
) {
const { positions } = fixture.getInfos();
const { whirlpoolClient } = testCtx;
const position = await whirlpoolClient.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const hasL = !position.getData().liquidity.isZero();
await (
await position.collectFees(hasL)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
}
async function testClosePosition(
fixture: WhirlpoolTestFixture | WhirlpoolTestFixtureV2,
isWSOLTest = false,
) {
const { positions, poolInitInfo, rewards } = fixture.getInfos();
const { whirlpoolClient } = testCtx;
const ctx = whirlpoolClient.getContext();
const otherWallet = anchor.web3.Keypair.generate();
const pool = await whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const position = await whirlpoolClient.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const preClosePoolData = pool.getData();
const positionAccountBalance = await ctx.connection.getBalance(
positions[0].publicKey,
);
const txs = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
undefined,
ctx.wallet.publicKey,
);
// TODO: Our createWSOLAccountInstructions ignores payer and requires destinationWallet to sign
// We can remove this once we move to syncNative and wSOL becomes another ATA to handle.
if (isWSOLTest) {
txs[0].addSigner(otherWallet);
}
for (const tx of txs) {
await tx.buildAndExecute();
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
pool.getData(),
IGNORE_CACHE,
);
// Verify liquidity and fees collected
const liquidityCollectedQuote = decreaseLiquidityQuoteByLiquidity(
position.getData().liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
tokenExtensionCtx,
);
const feeQuote = collectFeesQuote({
position: position.getData(),
whirlpool: pool.getData(),
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx,
});
const accountAPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
);
const accountA = (await ctx.fetcher.getTokenInfo(
accountAPubkey,
IGNORE_CACHE,
)) as Account;
const expectAmountA = liquidityCollectedQuote.tokenMinA.add(
feeQuote.feeOwedA,
);
if (isWSOLTest) {
// If this is a WSOL test, we have to account for account rent retrieval
const solInOtherWallet = await ctx.connection.getBalance(
otherWallet.publicKey,
);
const minAccountExempt = await ctx.fetcher.getAccountRentExempt();
const expectedReceivedSol = liquidityCollectedQuote.tokenMinA
.add(feeQuote.feeOwedA)
.add(new BN(positionAccountBalance))
.add(new BN(minAccountExempt))
.add(new BN(minAccountExempt))
.toNumber();
assert.equal(solInOtherWallet, expectedReceivedSol);
} else if (expectAmountA.isZero()) {
assert.ok(!accountA || accountA.amount === 0n);
} else {
assert.equal(accountA?.amount.toString(), expectAmountA.toString());
}
const accountBPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
);
const accountB = await ctx.fetcher.getTokenInfo(
accountBPubkey,
IGNORE_CACHE,
);
const expectAmountB = liquidityCollectedQuote.tokenMinB.add(
feeQuote.feeOwedB,
);
if (expectAmountB.isZero()) {
assert.ok(!accountB || accountB.amount === 0n);
} else {
assert.equal(accountB?.amount.toString(), expectAmountB.toString());
}
// Verify reward collected. We use the same timestamp that the closePosition call used to collectRewards.
const postClosePoolData = await pool.refreshData();
const rewardQuote = collectRewardsQuote({
position: position.getData(),
whirlpool: preClosePoolData,
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx,
timeStampInSeconds: postClosePoolData.rewardLastUpdatedTimestamp,
});
for (let i = 0; i < NUM_REWARDS; i++) {
if (!!rewards[i]) {
const rewardATA = getAssociatedTokenAddressSync(
rewards[i].rewardMint,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.rewardTokenMintsWithProgram[i]!.tokenProgram,
);
const rewardTokenAccount = await ctx.fetcher.getTokenInfo(
rewardATA,
IGNORE_CACHE,
);
assert.equal(
rewardTokenAccount?.amount.toString(),
rewardQuote.rewardOwed[i]?.toString(),
);
}
}
}
describe("when the whirlpool is SPL-only", () => {
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
tokenTraitR: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tokenTraitR: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
tokenTraitR: { isToken2022: false },
},
{
// TransferHook is most difficult extension in transaction size
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitR: { isToken2022: true, hasTransferHookExtension: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}`, () => {
it("should close a position with no liquidity, fees, or rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
await removeLiquidity(fixture);
await testClosePosition(fixture);
});
it("should close a position with only liquidity", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
await testClosePosition(fixture);
});
it("should close a position with only fees", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
await accrueFeesAndRewards(fixture);
await removeLiquidity(fixture);
await testClosePosition(fixture);
});
it("should close a position with only rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
// accrue rewards
// closePosition does not attempt to create an ATA unless reward has accumulated.
await sleep(2000);
await removeLiquidity(fixture);
await collectFees(fixture);
await testClosePosition(fixture);
});
it("should close a position with only liquidity and fees", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
await accrueFeesAndRewards(fixture);
await testClosePosition(fixture);
});
it("should close a position with only liquidity and rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
// accrue rewards
// closePosition does not attempt to create an ATA unless reward has accumulated.
await sleep(2000);
await testClosePosition(fixture);
});
it("should close a position with only fees and rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
await accrueFeesAndRewards(fixture);
await removeLiquidity(fixture);
await testClosePosition(fixture);
});
it("should close a position with liquidity, fees, and rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
await accrueFeesAndRewards(fixture);
await testClosePosition(fixture);
});
it("should close a position with liquidity, fees, and rewards (no ATAs)", async () => {
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
...tokenTraits,
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: tokenTraits.tokenTraitR,
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const otherWallet = anchor.web3.Keypair.generate();
const positionData = fixture.getInfos().positions[0];
const position = await testCtx.whirlpoolClient.getPosition(
positionData.publicKey,
IGNORE_CACHE,
);
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionData.mintKeypair.publicKey,
testCtx.whirlpoolCtx.wallet.publicKey,
);
const newOwnerPositionTokenAccount =
await createAssociatedTokenAccount(
ctx.provider,
positionData.mintKeypair.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await accrueFeesAndRewards(fixture);
await transferToken(
testCtx.provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
const { poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const positionDataBefore =
await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataBefore, null);
const txs = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
for (const tx of txs) {
await tx.addSigner(otherWallet).buildAndExecute();
}
const positionDataAfter =
await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.equal(positionDataAfter, null);
});
});
});
});
describe("when the whirlpool is SOL-SPL", () => {
it("should close a position with liquidity, fees, and rewards", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
tokenAIsNative: true,
},
);
await accrueFeesAndRewards(fixture);
await testClosePosition(fixture, true);
});
it("should close a position with liquidity, fees, and rewards (no ATA)", async () => {
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
tokenAIsNative: true,
},
);
const otherWallet = anchor.web3.Keypair.generate();
const positionData = fixture.getInfos().positions[0];
const position = await testCtx.whirlpoolClient.getPosition(
positionData.publicKey,
IGNORE_CACHE,
);
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionData.mintKeypair.publicKey,
testCtx.whirlpoolCtx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionData.mintKeypair.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await accrueFeesAndRewards(fixture);
await transferToken(
testCtx.provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
const { poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const positionDataBefore = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataBefore, null);
const txs = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
for (const tx of txs) {
await tx.addSigner(otherWallet).buildAndExecute();
}
const positionDataAfter = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.equal(positionDataAfter, null);
});
});
it("should only create 2 transactions if absolutely necessary", async () => {
const ctx = testCtx.whirlpoolCtx;
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init({
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
tokenAIsNative: true,
});
const otherWallet = anchor.web3.Keypair.generate();
const positionData = fixture.getInfos().positions[0];
const position = await testCtx.whirlpoolClient.getPosition(
positionData.publicKey,
IGNORE_CACHE,
);
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionData.mintKeypair.publicKey,
testCtx.whirlpoolCtx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionData.mintKeypair.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await accrueFeesAndRewards(fixture);
await transferToken(
testCtx.provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
const { poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const txsWith4Ata = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
assert.equal(txsWith4Ata.length, 2);
await createAssociatedTokenAccount(
ctx.provider,
position.getWhirlpoolData().rewardInfos[0].mint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
const txsWith3Ata = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
assert.equal(txsWith3Ata.length, 2);
await createAssociatedTokenAccount(
ctx.provider,
position.getWhirlpoolData().rewardInfos[1].mint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
const txsWith2Ata = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
assert.equal(txsWith2Ata.length, 2);
await createAssociatedTokenAccount(
ctx.provider,
position.getWhirlpoolData().rewardInfos[2].mint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
const txsWith1Ata = await pool.closePosition(
position.getAddress(),
Percentage.fromFraction(10, 100),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
assert.equal(txsWith1Ata.length, 1);
await txsWith1Ata[0].addSigner(otherWallet).buildAndExecute();
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/position-impl.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
import * as assert from "assert";
import Decimal from "decimal.js";
import {
buildWhirlpoolClient,
decreaseLiquidityQuoteByLiquidity,
increaseLiquidityQuoteByInputTokenUsingPriceSlippage,
PriceMath,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
createAssociatedTokenAccount,
TickSpacing,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { initPosition } from "../../utils/test-builders";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { initTestPoolV2, useMaxCU } from "../../utils/v2/init-utils-v2";
import { mintTokensToTestAccountV2 } from "../../utils/v2/token-2022";
describe("position-impl", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
// TransferHook is most difficult extension in transaction size
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}`, () => {
it("increase and decrease liquidity on position", async () => {
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
// Create and mint tokens in this wallet
await mintTokensToTestAccountV2(
ctx.provider,
poolInitInfo.tokenMintA,
tokenTraits.tokenTraitA,
10_500_000_000,
poolInitInfo.tokenMintB,
tokenTraits.tokenTraitB,
10_500_000_000,
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
const lowerTick = PriceMath.priceToTickIndex(
new Decimal(89),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
const upperTick = PriceMath.priceToTickIndex(
new Decimal(120),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (await pool.initTickArrayForTicks([
lowerTick,
upperTick,
]))!;
await initTickArrayTx.buildAndExecute();
// [Action] Create a position at price 89, 120 with 50 token A
const lowerPrice = new Decimal(89);
const upperPrice = new Decimal(120);
const { positionAddress } = await initPosition(
ctx,
pool,
lowerPrice,
upperPrice,
poolInitInfo.tokenMintA,
50,
);
// [Action] Increase liquidity by 70 tokens of tokenB
const position = await client.getPosition(
positionAddress.publicKey,
IGNORE_CACHE,
);
const preIncreaseData = position.getData();
const increase_quote =
increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
poolInitInfo.tokenMintB,
new Decimal(70),
lowerTick,
upperTick,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.increaseLiquidity(
increase_quote,
false,
ctx.wallet.publicKey,
)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postIncreaseData = await position.refreshData();
const expectedPostIncreaseLiquidity = preIncreaseData.liquidity.add(
increase_quote.liquidityAmount,
);
assert.equal(
postIncreaseData.liquidity.toString(),
expectedPostIncreaseLiquidity.toString(),
);
// [Action] Withdraw half of the liquidity away from the position and verify
const withdrawHalf = postIncreaseData.liquidity.div(new anchor.BN(2));
const decrease_quote = decreaseLiquidityQuoteByLiquidity(
withdrawHalf,
Percentage.fromFraction(0, 100),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.decreaseLiquidity(decrease_quote, false)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postWithdrawData = await position.refreshData();
const expectedPostWithdrawLiquidity = postIncreaseData.liquidity.sub(
decrease_quote.liquidityAmount,
);
assert.equal(
postWithdrawData.liquidity.toString(),
expectedPostWithdrawLiquidity.toString(),
);
});
it("increase & decrease liquidity on position with a different destination, position wallet", async () => {
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
// Create and mint tokens in this wallet
await mintTokensToTestAccountV2(
ctx.provider,
poolInitInfo.tokenMintA,
tokenTraits.tokenTraitA,
10_500_000_000,
poolInitInfo.tokenMintB,
tokenTraits.tokenTraitB,
10_500_000_000,
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
const lowerTick = PriceMath.priceToTickIndex(
new Decimal(89),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
const upperTick = PriceMath.priceToTickIndex(
new Decimal(120),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (await pool.initTickArrayForTicks([
lowerTick,
upperTick,
]))!;
await initTickArrayTx.buildAndExecute();
// [Action] Create a position at price 89, 120 with 50 token A
const lowerPrice = new Decimal(89);
const upperPrice = new Decimal(120);
const { positionMint, positionAddress } = await initPosition(
ctx,
pool,
lowerPrice,
upperPrice,
poolInitInfo.tokenMintA,
50,
);
// [Action] Increase liquidity by 70 tokens of tokenB & create the ATA in the new source Wallet
const position = await client.getPosition(
positionAddress.publicKey,
IGNORE_CACHE,
);
const preIncreaseData = position.getData();
const increase_quote =
increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
poolInitInfo.tokenMintB,
new Decimal(70),
lowerTick,
upperTick,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.increaseLiquidity(increase_quote, false)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postIncreaseData = await position.refreshData();
const expectedPostIncreaseLiquidity = preIncreaseData.liquidity.add(
increase_quote.liquidityAmount,
);
assert.equal(
postIncreaseData.liquidity.toString(),
expectedPostIncreaseLiquidity.toString(),
);
// [Action] Withdraw half of the liquidity away from the position and verify
const withdrawHalf = postIncreaseData.liquidity.div(new anchor.BN(2));
const decrease_quote = await decreaseLiquidityQuoteByLiquidity(
withdrawHalf,
Percentage.fromFraction(0, 100),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
// Transfer the position token to another wallet
const otherWallet = anchor.web3.Keypair.generate();
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionMint,
ctx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionMint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await transferToken(
provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
// Mint to this other wallet and increase more tokens
await mintTokensToTestAccountV2(
ctx.provider,
poolInitInfo.tokenMintA,
tokenTraits.tokenTraitA,
10_500_000_000,
poolInitInfo.tokenMintB,
tokenTraits.tokenTraitB,
10_500_000_000,
otherWallet.publicKey,
);
const increaseQuoteFromOtherWallet =
increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
poolInitInfo.tokenMintB,
new Decimal(80),
lowerTick,
upperTick,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.increaseLiquidity(
increaseQuoteFromOtherWallet,
true,
otherWallet.publicKey,
otherWallet.publicKey,
)
)
.addSigner(otherWallet)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postSecondIncreaseData = await position.refreshData();
// Withdraw liquidity into another wallet
const destinationWallet = anchor.web3.Keypair.generate();
await (
await position.decreaseLiquidity(
decrease_quote,
true,
destinationWallet.publicKey,
otherWallet.publicKey,
)
)
.addSigner(otherWallet)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postWithdrawData = await position.refreshData();
const expectedPostWithdrawLiquidity =
postSecondIncreaseData.liquidity.sub(decrease_quote.liquidityAmount);
assert.equal(
postWithdrawData.liquidity.toString(),
expectedPostWithdrawLiquidity.toString(),
);
});
it("increase and decrease liquidity on position (position with TokenExtensions)", async () => {
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
// Create and mint tokens in this wallet
await mintTokensToTestAccountV2(
ctx.provider,
poolInitInfo.tokenMintA,
tokenTraits.tokenTraitA,
10_500_000_000,
poolInitInfo.tokenMintB,
tokenTraits.tokenTraitB,
10_500_000_000,
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
const lowerTick = PriceMath.priceToTickIndex(
new Decimal(89),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
const upperTick = PriceMath.priceToTickIndex(
new Decimal(120),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (await pool.initTickArrayForTicks([
lowerTick,
upperTick,
]))!;
await initTickArrayTx.buildAndExecute();
// [Action] Create a position at price 89, 120 with 50 token A
const lowerPrice = new Decimal(89);
const upperPrice = new Decimal(120);
const { positionAddress } = await initPosition(
ctx,
pool,
lowerPrice,
upperPrice,
poolInitInfo.tokenMintA,
50,
undefined,
true, // withTokenExtensions
);
// [Action] Increase liquidity by 70 tokens of tokenB
const position = await client.getPosition(
positionAddress.publicKey,
IGNORE_CACHE,
);
// Verify position mint is owned by Token-2022
const positionMint = await fetcher.getMintInfo(
position.getData().positionMint,
IGNORE_CACHE,
);
assert.ok(positionMint?.tokenProgram.equals(TOKEN_2022_PROGRAM_ID));
const preIncreaseData = position.getData();
const increase_quote =
increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
poolInitInfo.tokenMintB,
new Decimal(70),
lowerTick,
upperTick,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.increaseLiquidity(
increase_quote,
false,
ctx.wallet.publicKey,
)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postIncreaseData = await position.refreshData();
const expectedPostIncreaseLiquidity = preIncreaseData.liquidity.add(
increase_quote.liquidityAmount,
);
assert.equal(
postIncreaseData.liquidity.toString(),
expectedPostIncreaseLiquidity.toString(),
);
// [Action] Withdraw half of the liquidity away from the position and verify
const withdrawHalf = postIncreaseData.liquidity.div(new anchor.BN(2));
const decrease_quote = decreaseLiquidityQuoteByLiquidity(
withdrawHalf,
Percentage.fromFraction(0, 100),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
pool.getData(),
IGNORE_CACHE,
),
);
await (
await position.decreaseLiquidity(decrease_quote, false)
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const postWithdrawData = await position.refreshData();
const expectedPostWithdrawLiquidity = postIncreaseData.liquidity.sub(
decrease_quote.liquidityAmount,
);
assert.equal(
postWithdrawData.liquidity.toString(),
expectedPostWithdrawLiquidity.toString(),
);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/position-impl-collectRewards.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { Whirlpool, WhirlpoolClient } from "../../../src";
import {
NUM_REWARDS,
PDAUtil,
WhirlpoolContext,
buildWhirlpoolClient,
collectRewardsQuote,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
sleep,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("PositionImpl#collectRewards()", () => {
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const vaultStartBalance = 1_000_000;
const tickSpacing = TickSpacing.Standard;
const liquidityAmount = new BN(10_000_000);
beforeAll(() => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
describe("when the whirlpool is SPL-only", () => {
it("should collect rewards", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
},
);
const { positions, poolInitInfo, rewards } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const preCollectPoolData = pool.getData();
// accrue rewards
await sleep(2000);
const txs = await position.collectRewards(
rewards.map((r) => r.rewardMint),
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify the results fetched is the same as SDK estimate if the timestamp is the same
const postCollectPoolData = await pool.refreshData();
const quote = collectRewardsQuote({
whirlpool: preCollectPoolData,
position: position.getData(),
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
timeStampInSeconds: postCollectPoolData.rewardLastUpdatedTimestamp,
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!quote.rewardOwed[i]!.isZero());
}
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardATA = getAssociatedTokenAddressSync(
rewards[i].rewardMint,
otherWallet.publicKey,
);
const rewardTokenAccount =
await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
rewardATA,
IGNORE_CACHE,
);
assert.equal(
rewardTokenAccount?.amount.toString(),
quote.rewardOwed[i]?.toString(),
);
}
});
it("should collect rewards (TokenExtensions based Position", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position (dummy)
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
},
);
const { poolInitInfo, rewards } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
// open TokenExtensions based position
const positionWithTokenExtensions = await pool.openPosition(
tickLowerIndex,
tickUpperIndex,
{
liquidityAmount,
tokenMaxA: MAX_U64,
tokenMaxB: MAX_U64,
},
undefined,
undefined,
undefined,
TOKEN_2022_PROGRAM_ID,
);
await positionWithTokenExtensions.tx.buildAndExecute();
const positionAddress = PDAUtil.getPosition(
testCtx.whirlpoolCtx.program.programId,
positionWithTokenExtensions.positionMint,
).publicKey;
const position =
await testCtx.whirlpoolClient.getPosition(positionAddress);
assert.ok(
position.getPositionMintTokenProgramId().equals(TOKEN_2022_PROGRAM_ID),
);
const otherWallet = anchor.web3.Keypair.generate();
const preCollectPoolData = await pool.refreshData();
// accrue rewards
await sleep(2000);
const txs = await position.collectRewards(
rewards.map((r) => r.rewardMint),
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify the results fetched is the same as SDK estimate if the timestamp is the same
const postCollectPoolData = await pool.refreshData();
const quote = collectRewardsQuote({
whirlpool: preCollectPoolData,
position: position.getData(),
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
timeStampInSeconds: postCollectPoolData.rewardLastUpdatedTimestamp,
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!quote.rewardOwed[i]!.isZero());
}
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardATA = getAssociatedTokenAddressSync(
rewards[i].rewardMint,
otherWallet.publicKey,
);
const rewardTokenAccount =
await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
rewardATA,
IGNORE_CACHE,
);
assert.equal(
rewardTokenAccount?.amount.toString(),
quote.rewardOwed[i]?.toString(),
);
}
});
});
describe("when the whirlpool is SOL-SPL", () => {
it("should collect rewards", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
tokenAIsNative: true,
},
);
const { positions, poolInitInfo, rewards } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const preCollectPoolData = pool.getData();
// accrue rewards
await sleep(2000);
const txs = await position.collectRewards(
rewards.map((r) => r.rewardMint),
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify the results fetched is the same as SDK estimate if the timestamp is the same
const postCollectPoolData = await pool.refreshData();
const quote = collectRewardsQuote({
whirlpool: preCollectPoolData,
position: position.getData(),
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
timeStampInSeconds: postCollectPoolData.rewardLastUpdatedTimestamp,
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!quote.rewardOwed[i]!.isZero());
}
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardATA = getAssociatedTokenAddressSync(
rewards[i].rewardMint,
otherWallet.publicKey,
);
const rewardTokenAccount =
await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
rewardATA,
IGNORE_CACHE,
);
assert.equal(
rewardTokenAccount?.amount.toString(),
quote.rewardOwed[i]?.toString(),
);
}
});
});
describe("when the whirlpool is SPL-only (TokenExtension)", () => {
it("should collect rewards", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const { positions, poolInitInfo, rewards } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const preCollectPoolData = pool.getData();
// accrue rewards
await sleep(2000);
const txs = await position.collectRewards(
rewards.map((r) => r.rewardMint),
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify the results fetched is the same as SDK estimate if the timestamp is the same
const postCollectPoolData = await pool.refreshData();
const quote = collectRewardsQuote({
whirlpool: preCollectPoolData,
position: position.getData(),
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
pool.getData(),
IGNORE_CACHE,
),
timeStampInSeconds: postCollectPoolData.rewardLastUpdatedTimestamp,
});
// Check that the expectation is not zero
for (let i = 0; i < NUM_REWARDS; i++) {
assert.ok(!quote.rewardOwed[i]!.isZero());
}
for (let i = 0; i < NUM_REWARDS; i++) {
const rewardATA = getAssociatedTokenAddressSync(
rewards[i].rewardMint,
otherWallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const rewardTokenAccount =
await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
rewardATA,
IGNORE_CACHE,
);
assert.equal(
rewardTokenAccount?.amount.toString(),
quote.rewardOwed[i]?.toString(),
);
}
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/whirlpool-impl-collectFeesAndRewardsForPositions.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { SendTxRequest } from "@orca-so/common-sdk";
import {
MathUtil,
TransactionBuilder,
TransactionProcessor,
ZERO,
} from "@orca-so/common-sdk";
import {
NATIVE_MINT,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
createBurnInstruction,
createCloseAccountInstruction,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import type { Whirlpool, WhirlpoolClient } from "../../../src";
import {
NUM_REWARDS,
PDAUtil,
PoolUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
collectFeesQuote,
collectRewardsQuote,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import { TickSpacing, ZERO_BN } from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import type { FundedPositionInfo } from "../../utils/init-utils";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { useMaxCU } from "../../utils/v2/init-utils-v2";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("WhirlpoolImpl#collectFeesAndRewardsForPositions()", () => {
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const vaultStartBalance = 1_000_000;
const liquidityAmount = new BN(10_000_000);
const sleep = (second: number) =>
new Promise((resolve) => setTimeout(resolve, second * 1000));
beforeAll(() => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(
provider,
program,
undefined,
undefined,
{
userDefaultBuildOptions: {
maxSupportedTransactionVersion: "legacy",
},
},
);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
async function accrueFees(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, positions, tokenAccountA, tokenAccountB } =
fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// all position should get some fees
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
}
async function stopRewardsEmission(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, configKeypairs } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsIx(ctx.program, {
whirlpool: pool.getAddress(),
rewardVaultKey: pool.getData().rewardInfos[i].vault,
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
rewardIndex: i,
emissionsPerSecondX64: ZERO,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
}
}
async function burnAndCloseATAs(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
const mintA = pool.getTokenAInfo().mint;
const mintB = pool.getTokenBInfo().mint;
const ataA = getAssociatedTokenAddressSync(mintA, ctx.wallet.publicKey);
const ataB = getAssociatedTokenAddressSync(mintB, ctx.wallet.publicKey);
await burnAndCloseATA(ctx, ataA);
await burnAndCloseATA(ctx, ataB);
for (let i = 0; i < NUM_REWARDS; i++) {
if (PoolUtil.isRewardInitialized(pool.getRewardInfos()[i])) {
const mintReward = pool.getRewardInfos()[i].mint;
const ataReward = getAssociatedTokenAddressSync(
mintReward,
ctx.wallet.publicKey,
);
await burnAndCloseATA(ctx, ataReward);
}
}
}
async function burnAndCloseATA(ctx: WhirlpoolContext, ata: PublicKey) {
const account = await ctx.fetcher.getTokenInfo(ata, IGNORE_CACHE);
if (account === null) return;
const burnIx = createBurnInstruction(
ata,
account.mint,
ctx.wallet.publicKey,
account.amount,
);
const closeIx = createCloseAccountInstruction(
ata,
ctx.wallet.publicKey,
ctx.wallet.publicKey,
[],
);
const tx = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
tx.addInstruction({
instructions: [burnIx, closeIx],
cleanupInstructions: [],
signers: [],
});
await tx.buildAndExecute();
}
async function createATAs(
fixture: WhirlpoolTestFixture | WhirlpoolTestFixtureV2,
) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
const mintA = await testCtx.whirlpoolCtx.fetcher.getMintInfo(
pool.getTokenAInfo().mint,
);
const mintB = await testCtx.whirlpoolCtx.fetcher.getMintInfo(
pool.getTokenBInfo().mint,
);
const ataA = getAssociatedTokenAddressSync(
mintA!.address,
ctx.wallet.publicKey,
undefined,
mintA!.tokenProgram,
);
const ataB = getAssociatedTokenAddressSync(
mintB!.address,
ctx.wallet.publicKey,
undefined,
mintB!.tokenProgram,
);
await createATA(ctx, ataA, mintA!.address, mintA!.tokenProgram);
await createATA(ctx, ataB, mintB!.address, mintB!.tokenProgram);
for (let i = 0; i < NUM_REWARDS; i++) {
if (PoolUtil.isRewardInitialized(pool.getRewardInfos()[i])) {
const mintReward = await testCtx.whirlpoolCtx.fetcher.getMintInfo(
pool.getRewardInfos()[i].mint,
);
const ataReward = getAssociatedTokenAddressSync(
mintReward!.address,
ctx.wallet.publicKey,
undefined,
mintReward!.tokenProgram,
);
await createATA(
ctx,
ataReward,
mintReward!.address,
mintReward!.tokenProgram,
);
}
}
}
async function createATA(
ctx: WhirlpoolContext,
ata: PublicKey,
mint: PublicKey,
tokenProgram: PublicKey,
) {
if (mint.equals(NATIVE_MINT)) return;
const account = await ctx.fetcher.getTokenInfo(ata, IGNORE_CACHE);
if (account !== null) return;
const createATAIx = createAssociatedTokenAccountInstruction(
ctx.wallet.publicKey,
ata,
ctx.wallet.publicKey,
mint,
tokenProgram,
);
const tx = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
tx.addInstruction({
instructions: [createATAIx],
cleanupInstructions: [],
signers: [],
});
await tx.buildAndExecute();
}
async function baseTestSenario(
tokenAIsNative: boolean,
ataExists: boolean,
includeTokenExtensionBasedPosition: boolean,
) {
const fixtures: WhirlpoolTestFixture[] = [];
const positions: FundedPositionInfo[] = [];
const numOfPool = 3;
for (let i = 0; i < numOfPool; i++) {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tokenAIsNative,
tickSpacing,
positions: [
// 3 Positions / pool
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition:
includeTokenExtensionBasedPosition,
}, // In range position
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
}, // In range position
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition:
includeTokenExtensionBasedPosition,
}, // In range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
},
);
fixtures.push(fixture);
positions.push(...fixture.getInfos().positions);
}
const positionMints = positions.map((p) => p.mintKeypair.publicKey);
const positionMintInfos = await testCtx.whirlpoolCtx.fetcher.getMintInfos(
positionMints,
IGNORE_CACHE,
);
for (let i = 0; i < numOfPool; i++) {
const base = i * 3;
assert.ok(
positionMintInfos
.get(positionMints[base + 0].toBase58())
?.tokenProgram.equals(
includeTokenExtensionBasedPosition
? TOKEN_2022_PROGRAM_ID
: TOKEN_PROGRAM_ID,
),
);
assert.ok(
positionMintInfos
.get(positionMints[base + 1].toBase58())
?.tokenProgram.equals(TOKEN_PROGRAM_ID),
);
assert.ok(
positionMintInfos
.get(positionMints[base + 2].toBase58())
?.tokenProgram.equals(
includeTokenExtensionBasedPosition
? TOKEN_2022_PROGRAM_ID
: TOKEN_PROGRAM_ID,
),
);
}
await sleep(2); // accrueRewards
for (const fixture of fixtures) {
await accrueFees(fixture);
await (ataExists ? createATAs : burnAndCloseATAs)(fixture);
await stopRewardsEmission(fixture);
}
// check all positions have fees and rewards
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await testCtx.whirlpoolCtx.fetcher.getPool(
position.getData().whirlpool,
IGNORE_CACHE,
);
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const feeQuote = collectFeesQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
});
const rewardQuote = collectRewardsQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
timeStampInSeconds: poolData!.rewardLastUpdatedTimestamp,
});
assert.ok(feeQuote.feeOwedA.gt(ZERO));
assert.ok(feeQuote.feeOwedB.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[0]?.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[1]?.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[2]?.gt(ZERO));
}
const txs = await testCtx.whirlpoolClient.collectFeesAndRewardsForPositions(
positions.map((p) => p.publicKey),
IGNORE_CACHE,
);
assert.ok(txs.length >= 2);
// TODO: We should not depend on Transaction Processor for mass txn sending. SendTxRequest is also a hack.
// Remove when we have an official multi-transaction sending solution.
const requests: SendTxRequest[] = [];
for (const tx of txs) {
requests.push((await tx.build()) as SendTxRequest);
}
const parallel = true;
const processor = new TransactionProcessor(
testCtx.whirlpoolCtx.connection,
testCtx.whirlpoolCtx.wallet,
);
const { execute } = await processor.signAndConstructTransactions(
requests,
parallel,
);
const txResults = await execute();
for (const result of txResults) {
if (result.status === "rejected") {
console.debug(result.reason);
}
assert.equal(result.status, "fulfilled");
}
// check all positions have no fees and rewards
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await testCtx.whirlpoolCtx.fetcher.getPool(
position.getData().whirlpool,
IGNORE_CACHE,
);
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const feeQuote = collectFeesQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
});
const rewardQuote = collectRewardsQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
timeStampInSeconds: poolData!.rewardLastUpdatedTimestamp,
});
assert.ok(feeQuote.feeOwedA.eq(ZERO));
assert.ok(feeQuote.feeOwedB.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[0]?.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[1]?.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[2]?.eq(ZERO));
}
}
describe("when the whirlpool is SPL-only", () => {
it("should collect fees and rewards, create all ATAs", async () => {
const tokenAIsNative = false;
const ataExists = false;
await baseTestSenario(tokenAIsNative, ataExists, false);
});
it("should collect fees and rewards, all ATAs exists", async () => {
const tokenAIsNative = false;
const ataExists = true;
await baseTestSenario(tokenAIsNative, ataExists, false);
});
it("should collect fees and rewards, all ATAs exists (some Positions are TokenExtensions based)", async () => {
const tokenAIsNative = false;
const ataExists = true;
await baseTestSenario(tokenAIsNative, ataExists, true);
});
});
describe("when the whirlpool is SOL-SPL", () => {
it("should collect fees and rewards, create all ATAs", async () => {
const tokenAIsNative = true;
const ataExists = false;
await baseTestSenario(tokenAIsNative, ataExists, false);
});
it("should collect fees and rewards, all ATAs exists", async () => {
const tokenAIsNative = true;
const ataExists = true;
await baseTestSenario(tokenAIsNative, ataExists, false);
});
it("should collect fees and rewards, all ATAs exists (some Positions are TokenExtensions based)", async () => {
const tokenAIsNative = true;
const ataExists = true;
await baseTestSenario(tokenAIsNative, ataExists, true);
});
});
describe("when the whirlpool is TokenExtension-TokenExtension", () => {
async function accrueFeesV2(fixture: WhirlpoolTestFixtureV2) {
const ctx = testCtx.whirlpoolCtx;
const {
poolInitInfo,
positions: [positionInfo],
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
pool.getData(),
IGNORE_CACHE,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
async function stopRewardsEmissionV2(fixture: WhirlpoolTestFixtureV2) {
const ctx = testCtx.whirlpoolCtx;
const { poolInitInfo, configKeypairs } = fixture.getInfos();
const { whirlpoolPda } = poolInitInfo;
const pool = await testCtx.whirlpoolClient.getPool(
whirlpoolPda.publicKey,
);
for (let i = 0; i < NUM_REWARDS; i++) {
await toTx(
ctx,
WhirlpoolIx.setRewardEmissionsV2Ix(ctx.program, {
whirlpool: pool.getAddress(),
rewardVaultKey: pool.getData().rewardInfos[i].vault,
rewardAuthority:
configKeypairs.rewardEmissionsSuperAuthorityKeypair.publicKey,
rewardIndex: i,
emissionsPerSecondX64: ZERO,
}),
)
.addSigner(configKeypairs.rewardEmissionsSuperAuthorityKeypair)
.buildAndExecute();
}
}
it("should collect fees and rewards, create all ATAs", async () => {
const fixtures: WhirlpoolTestFixtureV2[] = [];
const positions: FundedPositionInfo[] = [];
const numOfPool = 3;
for (let i = 0; i < numOfPool; i++) {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing,
positions: [
// 3 Positions / pool
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasTransferHookExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
fixtures.push(fixture);
positions.push(...fixture.getInfos().positions);
}
await sleep(2); // accrueRewards
for (const fixture of fixtures) {
await accrueFeesV2(fixture);
await createATAs(fixture);
await stopRewardsEmissionV2(fixture);
}
// check all positions have fees and rewards
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await testCtx.whirlpoolCtx.fetcher.getPool(
position.getData().whirlpool,
IGNORE_CACHE,
);
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const feeQuote = collectFeesQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
});
const rewardQuote = collectRewardsQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
timeStampInSeconds: poolData!.rewardLastUpdatedTimestamp,
});
assert.ok(feeQuote.feeOwedA.gt(ZERO));
assert.ok(feeQuote.feeOwedB.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[0]?.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[1]?.gt(ZERO));
assert.ok(rewardQuote.rewardOwed[2]?.gt(ZERO));
}
const txs =
await testCtx.whirlpoolClient.collectFeesAndRewardsForPositions(
positions.map((p) => p.publicKey),
IGNORE_CACHE,
);
assert.ok(txs.length >= 2);
// TODO: We should not depend on Transaction Processor for mass txn sending. SendTxRequest is also a hack.
// Remove when we have an official multi-transaction sending solution.
const requests: SendTxRequest[] = [];
for (const tx of txs) {
requests.push((await tx.build()) as SendTxRequest);
}
const parallel = true;
const processor = new TransactionProcessor(
testCtx.whirlpoolCtx.connection,
testCtx.whirlpoolCtx.wallet,
);
const { execute } = await processor.signAndConstructTransactions(
requests,
parallel,
);
const txResults = await execute();
for (const result of txResults) {
if (result.status === "rejected") {
console.error(result.reason);
}
assert.equal(result.status, "fulfilled");
}
// check all positions have no fees and rewards
for (const positionInfo of positions) {
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const poolData = await testCtx.whirlpoolCtx.fetcher.getPool(
position.getData().whirlpool,
IGNORE_CACHE,
);
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const feeQuote = collectFeesQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
});
const rewardQuote = collectRewardsQuote({
whirlpool: poolData!,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData!,
IGNORE_CACHE,
),
timeStampInSeconds: poolData!.rewardLastUpdatedTimestamp,
});
assert.ok(feeQuote.feeOwedA.eq(ZERO));
assert.ok(feeQuote.feeOwedB.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[0]?.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[1]?.eq(ZERO));
assert.ok(rewardQuote.rewardOwed[2]?.eq(ZERO));
}
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/position-impl-collectFees.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { MathUtil } from "@orca-so/common-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
import * as assert from "assert";
import Decimal from "decimal.js";
import type { Whirlpool, WhirlpoolClient } from "../../../src";
import {
PDAUtil,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
collectFeesQuote,
toTx,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
MAX_U64,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
ZERO_BN,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { useMaxCU } from "../../utils/v2/init-utils-v2";
interface SharedTestContext {
provider: anchor.AnchorProvider;
program: Whirlpool;
whirlpoolCtx: WhirlpoolContext;
whirlpoolClient: WhirlpoolClient;
}
describe("PositionImpl#collectFees()", () => {
let testCtx: SharedTestContext;
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const liquidityAmount = new BN(10_000_000);
beforeAll(() => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
anchor.setProvider(provider);
const program = anchor.workspace.Whirlpool;
const whirlpoolCtx = WhirlpoolContext.fromWorkspace(provider, program);
const whirlpoolClient = buildWhirlpoolClient(whirlpoolCtx);
testCtx = {
provider,
program,
whirlpoolCtx,
whirlpoolClient,
};
});
async function accrueFees(fixture: WhirlpoolTestFixture) {
const ctx = testCtx.whirlpoolCtx;
const {
poolInitInfo,
positions: [positionInfo],
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
describe("when the whirlpool is SPL-only", () => {
it("should collect fees", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
},
);
await accrueFees(fixture);
const { positions, poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
);
const positionDataBefore = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.notEqual(positionDataBefore, null);
const tx = await position.collectFees(
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
await tx.buildAndExecute();
const positionDataAfter = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataAfter, null);
const accountAPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
otherWallet.publicKey,
);
const accountA = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountAPubkey,
IGNORE_CACHE,
);
assert.ok(
accountA && new BN(accountA.amount.toString()).eq(quote.feeOwedA),
);
const accountBPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
otherWallet.publicKey,
);
const accountB = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountBPubkey,
IGNORE_CACHE,
);
assert.ok(
accountB && new BN(accountB.amount.toString()).eq(quote.feeOwedB),
);
});
it("should collect fees (TokenExtensions based Position)", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position (dummy)
],
},
);
const { poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
// open TokenExtensions based position
const positionWithTokenExtensions = await pool.openPosition(
tickLowerIndex,
tickUpperIndex,
{
liquidityAmount,
tokenMaxA: MAX_U64,
tokenMaxB: MAX_U64,
},
undefined,
undefined,
undefined,
TOKEN_2022_PROGRAM_ID,
);
await positionWithTokenExtensions.tx.buildAndExecute();
const positionAddress = PDAUtil.getPosition(
testCtx.whirlpoolCtx.program.programId,
positionWithTokenExtensions.positionMint,
).publicKey;
const position =
await testCtx.whirlpoolClient.getPosition(positionAddress);
assert.ok(
position.getPositionMintTokenProgramId().equals(TOKEN_2022_PROGRAM_ID),
);
await accrueFees(fixture);
const positionDataBefore = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0));
assert.ok(quote.feeOwedB.gtn(0));
assert.notEqual(positionDataBefore, null);
const tx = await position.collectFees(
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
await tx.buildAndExecute();
const positionDataAfter = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataAfter, null);
const accountAPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
otherWallet.publicKey,
);
const accountA = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountAPubkey,
IGNORE_CACHE,
);
assert.ok(
accountA && new BN(accountA.amount.toString()).eq(quote.feeOwedA),
);
const accountBPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
otherWallet.publicKey,
);
const accountB = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountBPubkey,
IGNORE_CACHE,
);
assert.ok(
accountB && new BN(accountB.amount.toString()).eq(quote.feeOwedB),
);
});
});
describe("when the whirlpool is SOL-SPL", () => {
it("should collect fees", async () => {
const fixture = await new WhirlpoolTestFixture(testCtx.whirlpoolCtx).init(
{
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
tokenAIsNative: true,
},
);
await accrueFees(fixture);
const { positions, poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
);
const positionDataBefore = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData,
IGNORE_CACHE,
),
});
const solBalanceBefore = await testCtx.provider.connection.getBalance(
otherWallet.publicKey,
);
assert.notEqual(positionDataBefore, null);
const tx = await position.collectFees(
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
await tx.addSigner(otherWallet).buildAndExecute();
const positionDataAfter = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataAfter, null);
const solBalanceAfter = await testCtx.provider.connection.getBalance(
otherWallet.publicKey,
);
const minAccountExempt =
await testCtx.whirlpoolCtx.fetcher.getAccountRentExempt();
assert.equal(
solBalanceAfter - solBalanceBefore,
quote.feeOwedA.toNumber() + minAccountExempt,
);
const accountBPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
otherWallet.publicKey,
);
const accountB = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountBPubkey,
IGNORE_CACHE,
);
assert.ok(
accountB && new BN(accountB.amount.toString()).eq(quote.feeOwedB),
);
});
});
async function accrueFeesV2(fixture: WhirlpoolTestFixtureV2) {
const ctx = testCtx.whirlpoolCtx;
const {
poolInitInfo,
positions: [positionInfo],
tokenAccountA,
tokenAccountB,
} = fixture.getInfos();
const { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair } =
poolInitInfo;
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const pool = await testCtx.whirlpoolClient.getPool(whirlpoolPda.publicKey);
const position = await testCtx.whirlpoolClient.getPosition(
positionInfo.publicKey,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
pool.getData(),
IGNORE_CACHE,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.ok(quote.feeOwedA.gtn(0) || quote.feeOwedB.gtn(0));
}
describe("when the whirlpool is SPL-only (TokenExtension)", () => {
it("should collect fees", async () => {
const fixture = await new WhirlpoolTestFixtureV2(
testCtx.whirlpoolCtx,
).init({
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
await accrueFeesV2(fixture);
const { positions, poolInitInfo } = fixture.getInfos();
const pool = await testCtx.whirlpoolClient.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const position = await testCtx.whirlpoolClient.getPosition(
positions[0].publicKey,
);
const positionDataBefore = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
const otherWallet = anchor.web3.Keypair.generate();
const poolData = await pool.refreshData();
const positionData = await position.refreshData();
const tickLowerData = position.getLowerTickData();
const tickUpperData = position.getLowerTickData();
const quote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: tickLowerData,
tickUpper: tickUpperData,
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
testCtx.whirlpoolCtx.fetcher,
poolData,
IGNORE_CACHE,
),
});
assert.notEqual(positionDataBefore, null);
const tx = await position.collectFees(
true,
undefined,
otherWallet.publicKey,
testCtx.provider.wallet.publicKey,
testCtx.provider.wallet.publicKey,
IGNORE_CACHE,
);
await tx.buildAndExecute();
const positionDataAfter = await testCtx.whirlpoolCtx.fetcher.getPosition(
position.getAddress(),
IGNORE_CACHE,
);
assert.notEqual(positionDataAfter, null);
const accountAPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintA,
otherWallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const accountA = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountAPubkey,
IGNORE_CACHE,
);
assert.ok(
accountA && new BN(accountA.amount.toString()).eq(quote.feeOwedA),
);
const accountBPubkey = getAssociatedTokenAddressSync(
poolInitInfo.tokenMintB,
otherWallet.publicKey,
undefined,
TEST_TOKEN_2022_PROGRAM_ID,
);
const accountB = await testCtx.whirlpoolCtx.fetcher.getTokenInfo(
accountBPubkey,
IGNORE_CACHE,
);
assert.ok(
accountB && new BN(accountB.amount.toString()).eq(quote.feeOwedB),
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/whirlpool-client-impl.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import * as assert from "assert";
import Decimal from "decimal.js";
import {
buildWhirlpoolClient,
PDAUtil,
PriceMath,
SPLASH_POOL_TICK_SPACING,
TickUtil,
WhirlpoolContext,
} from "../../../src";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
ONE_SOL,
systemTransferTx,
TEST_TOKEN_2022_PROGRAM_ID,
TickSpacing,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { buildTestPoolParams, initTestPool } from "../../utils/init-utils";
import { buildTestPoolV2Params } from "../../utils/v2/init-utils-v2";
import {
getMint,
getTransferFeeConfig,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import {
initPosition,
mintTokensToTestAccount,
} from "../../utils/test-builders";
describe("whirlpool-client-impl", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const client = buildWhirlpoolClient(ctx);
describe("TokenProgram", () => {
let funderKeypair: anchor.web3.Keypair;
beforeEach(async () => {
funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
});
it("successfully creates a new whirpool account and initial tick array account", async () => {
const poolInitInfo = (
await buildTestPoolParams(
ctx,
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
const initalTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const { poolKey: actualPubkey, tx } = await client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
initalTick,
funderKeypair.publicKey,
);
const expectedPda = PDAUtil.getWhirlpool(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
);
const startTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
initalTick,
poolInitInfo.tickSpacing,
expectedPda.publicKey,
ctx.program.programId,
);
assert.ok(expectedPda.publicKey.equals(actualPubkey));
const [whirlpoolAccountBefore, tickArrayAccountBefore] =
await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountBefore === null);
assert.ok(tickArrayAccountBefore === null);
await tx.addSigner(funderKeypair).buildAndExecute();
const [whirlpoolAccountAfter, tickArrayAccountAfter] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountAfter !== null);
assert.ok(tickArrayAccountAfter !== null);
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalA.eqn(0));
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalB.eqn(0));
assert.ok(whirlpoolAccountAfter.feeRate === 3000);
assert.ok(whirlpoolAccountAfter.liquidity.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedA.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedB.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeRate === 300);
assert.ok(whirlpoolAccountAfter.rewardInfos.length === 3);
assert.ok(whirlpoolAccountAfter.rewardLastUpdatedTimestamp.eqn(0));
assert.ok(
whirlpoolAccountAfter.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(initalTick),
),
);
assert.ok(whirlpoolAccountAfter.tickCurrentIndex === initalTick);
assert.ok(whirlpoolAccountAfter.tickSpacing === poolInitInfo.tickSpacing);
assert.ok(
whirlpoolAccountAfter.tokenMintA.equals(poolInitInfo.tokenMintA),
);
assert.ok(
whirlpoolAccountAfter.tokenMintB.equals(poolInitInfo.tokenMintB),
);
assert.ok(whirlpoolAccountAfter.whirlpoolBump[0] === expectedPda.bump);
assert.ok(
whirlpoolAccountAfter.whirlpoolsConfig.equals(
poolInitInfo.whirlpoolsConfig,
),
);
assert.ok(
tickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(initalTick, poolInitInfo.tickSpacing),
);
assert.ok(tickArrayAccountAfter.ticks.length > 0);
assert.ok(tickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey));
});
it("throws an error when token order is incorrect", async () => {
const poolInitInfo = (
await buildTestPoolParams(
ctx,
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
const initalTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const invInitialTick = TickUtil.invertTick(initalTick);
await assert.rejects(
client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
poolInitInfo.tickSpacing,
invInitialTick,
funderKeypair.publicKey,
),
/Token order needs to be flipped to match the canonical ordering \(i.e. sorted on the byte repr. of the mint pubkeys\)/,
);
});
it("successfully creates a new splash pool whirlpool account and initial tick array account", async () => {
const poolInitInfo = (
await buildTestPoolParams(
ctx,
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
const [startTick, endTick] = TickUtil.getFullRangeTickIndex(
SPLASH_POOL_TICK_SPACING,
);
const { poolKey: actualPubkey, tx } = await client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
funderKeypair.publicKey,
);
const expectedPda = PDAUtil.getWhirlpool(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
SPLASH_POOL_TICK_SPACING,
);
const startTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
startTick,
SPLASH_POOL_TICK_SPACING,
expectedPda.publicKey,
ctx.program.programId,
);
const endTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
endTick,
SPLASH_POOL_TICK_SPACING,
expectedPda.publicKey,
ctx.program.programId,
);
assert.ok(expectedPda.publicKey.equals(actualPubkey));
const [
whirlpoolAccountBefore,
startTickArrayAccountBefore,
endTickArrayAccountBefore,
] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(endTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountBefore === null);
assert.ok(startTickArrayAccountBefore === null);
assert.ok(endTickArrayAccountBefore === null);
await tx.addSigner(funderKeypair).buildAndExecute();
const [
whirlpoolAccountAfter,
startTickArrayAccountAfter,
endTickArrayAccountAfter,
] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(endTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountAfter !== null);
assert.ok(startTickArrayAccountAfter !== null);
assert.ok(endTickArrayAccountAfter !== null);
const startSqrtPrice = PriceMath.priceToSqrtPriceX64(
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
6,
6,
);
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalA.eqn(0));
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalB.eqn(0));
assert.ok(whirlpoolAccountAfter.feeRate === 3000);
assert.ok(whirlpoolAccountAfter.liquidity.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedA.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedB.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeRate === 300);
assert.ok(whirlpoolAccountAfter.rewardInfos.length === 3);
assert.ok(whirlpoolAccountAfter.rewardLastUpdatedTimestamp.eqn(0));
assert.ok(whirlpoolAccountAfter.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolAccountAfter.tickCurrentIndex ===
PriceMath.sqrtPriceX64ToTickIndex(startSqrtPrice),
);
assert.ok(whirlpoolAccountAfter.tickSpacing === SPLASH_POOL_TICK_SPACING);
assert.ok(
whirlpoolAccountAfter.tokenMintA.equals(poolInitInfo.tokenMintA),
);
assert.ok(
whirlpoolAccountAfter.tokenMintB.equals(poolInitInfo.tokenMintB),
);
assert.ok(whirlpoolAccountAfter.whirlpoolBump[0] === expectedPda.bump);
assert.ok(
whirlpoolAccountAfter.whirlpoolsConfig.equals(
poolInitInfo.whirlpoolsConfig,
),
);
assert.ok(
startTickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(startTick, SPLASH_POOL_TICK_SPACING),
);
assert.ok(startTickArrayAccountAfter.ticks.length > 0);
assert.ok(
startTickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey),
);
assert.ok(
endTickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(endTick, SPLASH_POOL_TICK_SPACING),
);
assert.ok(endTickArrayAccountAfter.ticks.length > 0);
assert.ok(
endTickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey),
);
});
it("throws an error when token order is incorrect while creating splash pool", async () => {
const poolInitInfo = (
await buildTestPoolParams(
ctx,
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
await assert.rejects(
client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
funderKeypair.publicKey,
),
/Token order needs to be flipped to match the canonical ordering \(i.e. sorted on the byte repr. of the mint pubkeys\)/,
);
});
});
describe("TokenExtension", () => {
let funderKeypair: anchor.web3.Keypair;
beforeEach(async () => {
funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
});
it("successfully creates a new whirpool account and initial tick array account (without TokenBadge)", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{ isToken2022: true, hasTransferFeeExtension: true },
{ isToken2022: true, hasTransferFeeExtension: true },
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
// initialized with TransferFee extension
const mintDataA = await getMint(
provider.connection,
poolInitInfo.tokenMintA,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const mintDataB = await getMint(
provider.connection,
poolInitInfo.tokenMintB,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfigA = getTransferFeeConfig(mintDataA);
const transferFeeConfigB = getTransferFeeConfig(mintDataB);
assert.ok(transferFeeConfigA !== null);
assert.ok(transferFeeConfigB !== null);
const initalTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const { poolKey: actualPubkey, tx } = await client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
initalTick,
funderKeypair.publicKey,
);
const expectedPda = PDAUtil.getWhirlpool(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
);
const startTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
initalTick,
poolInitInfo.tickSpacing,
expectedPda.publicKey,
ctx.program.programId,
);
assert.ok(expectedPda.publicKey.equals(actualPubkey));
const [whirlpoolAccountBefore, tickArrayAccountBefore] =
await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountBefore === null);
assert.ok(tickArrayAccountBefore === null);
await tx.addSigner(funderKeypair).buildAndExecute();
const [whirlpoolAccountAfter, tickArrayAccountAfter] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountAfter !== null);
assert.ok(tickArrayAccountAfter !== null);
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalA.eqn(0));
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalB.eqn(0));
assert.ok(whirlpoolAccountAfter.feeRate === 3000);
assert.ok(whirlpoolAccountAfter.liquidity.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedA.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedB.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeRate === 300);
assert.ok(whirlpoolAccountAfter.rewardInfos.length === 3);
assert.ok(whirlpoolAccountAfter.rewardLastUpdatedTimestamp.eqn(0));
assert.ok(
whirlpoolAccountAfter.sqrtPrice.eq(
PriceMath.tickIndexToSqrtPriceX64(initalTick),
),
);
assert.ok(whirlpoolAccountAfter.tickCurrentIndex === initalTick);
assert.ok(whirlpoolAccountAfter.tickSpacing === poolInitInfo.tickSpacing);
assert.ok(
whirlpoolAccountAfter.tokenMintA.equals(poolInitInfo.tokenMintA),
);
assert.ok(
whirlpoolAccountAfter.tokenMintB.equals(poolInitInfo.tokenMintB),
);
assert.ok(whirlpoolAccountAfter.whirlpoolBump[0] === expectedPda.bump);
assert.ok(
whirlpoolAccountAfter.whirlpoolsConfig.equals(
poolInitInfo.whirlpoolsConfig,
),
);
assert.ok(
tickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(initalTick, poolInitInfo.tickSpacing),
);
assert.ok(tickArrayAccountAfter.ticks.length > 0);
assert.ok(tickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey));
});
it("successfully creates a new whirpool account (with TokenBadge)", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
}, // TokenBadge required
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
}, // TokenBadge required
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
ctx.wallet.publicKey,
true, // initialize TokenBadge
true, // initialize TokenBadge
)
).poolInitInfo;
const initialTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const tx = (
await client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
initialTick,
ctx.wallet.publicKey,
)
).tx;
await tx.buildAndExecute();
const whirlpool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpool !== null);
assert.ok(whirlpool.getData().tokenMintA.equals(poolInitInfo.tokenMintA));
assert.ok(whirlpool.getData().tokenMintB.equals(poolInitInfo.tokenMintB));
});
it("throws an error when token order is incorrect", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{ isToken2022: true, hasTransferFeeExtension: true },
{ isToken2022: true, hasTransferFeeExtension: true },
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
const initialTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const invInitialTick = TickUtil.invertTick(initialTick);
await assert.rejects(
client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
poolInitInfo.tickSpacing,
invInitialTick,
funderKeypair.publicKey,
),
/Token order needs to be flipped to match the canonical ordering \(i.e. sorted on the byte repr. of the mint pubkeys\)/,
);
});
it("throws an error when TokenBadge is not initialized", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
},
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
},
TickSpacing.Standard,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
ctx.wallet.publicKey,
false, // not initialize TokenBadge
false, // not initialize TokenBadge
)
).poolInitInfo;
const initialTick = TickUtil.getInitializableTickIndex(
PriceMath.sqrtPriceX64ToTickIndex(poolInitInfo.initSqrtPrice),
poolInitInfo.tickSpacing,
);
const tx = (
await client.createPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
poolInitInfo.tickSpacing,
initialTick,
ctx.wallet.publicKey,
)
).tx;
await assert.rejects(
tx.buildAndExecute(),
/0x179f/, // UnsupportedTokenMint
);
});
it("successfully creates a new whirpool account and initial tick array account (without TokenBadge) for splash pool", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{ isToken2022: true, hasTransferFeeExtension: true },
{ isToken2022: true, hasTransferFeeExtension: true },
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
// initialized with TransferFee extension
const mintDataA = await getMint(
provider.connection,
poolInitInfo.tokenMintA,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const mintDataB = await getMint(
provider.connection,
poolInitInfo.tokenMintB,
"confirmed",
TEST_TOKEN_2022_PROGRAM_ID,
);
const transferFeeConfigA = getTransferFeeConfig(mintDataA);
const transferFeeConfigB = getTransferFeeConfig(mintDataB);
assert.ok(transferFeeConfigA !== null);
assert.ok(transferFeeConfigB !== null);
const [startTick, endTick] = TickUtil.getFullRangeTickIndex(
SPLASH_POOL_TICK_SPACING,
);
const { poolKey: actualPubkey, tx } = await client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
funderKeypair.publicKey,
);
const expectedPda = PDAUtil.getWhirlpool(
ctx.program.programId,
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
SPLASH_POOL_TICK_SPACING,
);
const startTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
startTick,
SPLASH_POOL_TICK_SPACING,
expectedPda.publicKey,
ctx.program.programId,
);
const endTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
endTick,
SPLASH_POOL_TICK_SPACING,
expectedPda.publicKey,
ctx.program.programId,
);
assert.ok(expectedPda.publicKey.equals(actualPubkey));
const [
whirlpoolAccountBefore,
startTickArrayAccountBefore,
endTickArrayAccountBefore,
] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(endTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountBefore === null);
assert.ok(startTickArrayAccountBefore === null);
assert.ok(endTickArrayAccountBefore === null);
await tx.addSigner(funderKeypair).buildAndExecute();
const [
whirlpoolAccountAfter,
startTickArrayAccountAfter,
endTickArrayAccountAfter,
] = await Promise.all([
ctx.fetcher.getPool(expectedPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(startTickArrayPda.publicKey, IGNORE_CACHE),
ctx.fetcher.getTickArray(endTickArrayPda.publicKey, IGNORE_CACHE),
]);
assert.ok(whirlpoolAccountAfter !== null);
assert.ok(startTickArrayAccountAfter !== null);
assert.ok(endTickArrayAccountAfter !== null);
const startSqrtPrice = PriceMath.priceToSqrtPriceX64(
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
6,
6,
);
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalA.eqn(0));
assert.ok(whirlpoolAccountAfter.feeGrowthGlobalB.eqn(0));
assert.ok(whirlpoolAccountAfter.feeRate === 3000);
assert.ok(whirlpoolAccountAfter.liquidity.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedA.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeOwedB.eqn(0));
assert.ok(whirlpoolAccountAfter.protocolFeeRate === 300);
assert.ok(whirlpoolAccountAfter.rewardInfos.length === 3);
assert.ok(whirlpoolAccountAfter.rewardLastUpdatedTimestamp.eqn(0));
assert.ok(whirlpoolAccountAfter.sqrtPrice.eq(startSqrtPrice));
assert.ok(
whirlpoolAccountAfter.tickCurrentIndex ===
PriceMath.sqrtPriceX64ToTickIndex(startSqrtPrice),
);
assert.ok(whirlpoolAccountAfter.tickSpacing === SPLASH_POOL_TICK_SPACING);
assert.ok(
whirlpoolAccountAfter.tokenMintA.equals(poolInitInfo.tokenMintA),
);
assert.ok(
whirlpoolAccountAfter.tokenMintB.equals(poolInitInfo.tokenMintB),
);
assert.ok(whirlpoolAccountAfter.whirlpoolBump[0] === expectedPda.bump);
assert.ok(
whirlpoolAccountAfter.whirlpoolsConfig.equals(
poolInitInfo.whirlpoolsConfig,
),
);
assert.ok(
startTickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(startTick, SPLASH_POOL_TICK_SPACING),
);
assert.ok(startTickArrayAccountAfter.ticks.length > 0);
assert.ok(
startTickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey),
);
assert.ok(
endTickArrayAccountAfter.startTickIndex ===
TickUtil.getStartTickIndex(endTick, SPLASH_POOL_TICK_SPACING),
);
assert.ok(endTickArrayAccountAfter.ticks.length > 0);
assert.ok(
endTickArrayAccountAfter.whirlpool.equals(expectedPda.publicKey),
);
});
it("successfully creates a new whirpool account (with TokenBadge) for splash pool", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
}, // TokenBadge required
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
}, // TokenBadge required
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
ctx.wallet.publicKey,
true, // initialize TokenBadge
true, // initialize TokenBadge
)
).poolInitInfo;
const tx = (
await client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
ctx.wallet.publicKey,
)
).tx;
await tx.buildAndExecute();
const whirlpool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(whirlpool !== null);
assert.ok(whirlpool.getData().tokenMintA.equals(poolInitInfo.tokenMintA));
assert.ok(whirlpool.getData().tokenMintB.equals(poolInitInfo.tokenMintB));
});
it("throws an error when token order is incorrect for splash pool", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{ isToken2022: true, hasTransferFeeExtension: true },
{ isToken2022: true, hasTransferFeeExtension: true },
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
funderKeypair.publicKey,
)
).poolInitInfo;
await assert.rejects(
client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintB,
poolInitInfo.tokenMintA,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
funderKeypair.publicKey,
),
/Token order needs to be flipped to match the canonical ordering \(i.e. sorted on the byte repr. of the mint pubkeys\)/,
);
});
it("throws an error when TokenBadge is not initialized for splash pool", async () => {
const poolInitInfo = (
await buildTestPoolV2Params(
ctx,
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
},
{
isToken2022: true,
hasTransferHookExtension: true,
hasPermanentDelegate: true,
},
SPLASH_POOL_TICK_SPACING,
3000,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
ctx.wallet.publicKey,
false, // not initialize TokenBadge
false, // not initialize TokenBadge
)
).poolInitInfo;
const tx = (
await client.createSplashPool(
poolInitInfo.whirlpoolsConfig,
poolInitInfo.tokenMintA,
poolInitInfo.tokenMintB,
PriceMath.sqrtPriceX64ToPrice(poolInitInfo.initSqrtPrice, 6, 6),
ctx.wallet.publicKey,
)
).tx;
await assert.rejects(
tx.buildAndExecute(),
/0x179f/, // UnsupportedTokenMint
);
});
});
it("getPosition/getPositions for TokenExtensions based Position", async () => {
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
// Create and mint tokens in this wallet
await mintTokensToTestAccount(
ctx.provider,
poolInitInfo.tokenMintA,
10_000_000_000,
poolInitInfo.tokenMintB,
10_000_000_000,
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
const lowerTick = PriceMath.priceToTickIndex(
new Decimal(89),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
const upperTick = PriceMath.priceToTickIndex(
new Decimal(120),
pool.getTokenAInfo().decimals,
pool.getTokenBInfo().decimals,
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (await pool.initTickArrayForTicks([
lowerTick,
upperTick,
]))!;
await initTickArrayTx.buildAndExecute();
// [Action] Create a position at price 89, 120 with 50 token A
const lowerPrice = new Decimal(89);
const upperPrice = new Decimal(120);
const withTokenExtensions = [true, false, true, false];
const positions = await Promise.all(
withTokenExtensions.map((withTokenExtension) =>
initPosition(
ctx,
pool,
lowerPrice,
upperPrice,
poolInitInfo.tokenMintA,
50,
undefined,
withTokenExtension,
),
),
);
// check .getPosition
const position0 = await client.getPosition(
positions[0].positionAddress.publicKey,
IGNORE_CACHE,
);
assert.ok(
position0.getPositionMintTokenProgramId().equals(TOKEN_2022_PROGRAM_ID),
);
const position1 = await client.getPosition(
positions[1].positionAddress.publicKey,
IGNORE_CACHE,
);
assert.ok(
position1.getPositionMintTokenProgramId().equals(TOKEN_PROGRAM_ID),
);
// check .getPositions
const positionsFetched = await client.getPositions(
positions.map((p) => p.positionAddress.publicKey),
IGNORE_CACHE,
);
withTokenExtensions.forEach((withTokenExtension, i) => {
const position =
positionsFetched[positions[i].positionAddress.publicKey.toBase58()];
assert.ok(!!position);
assert.ok(
position
.getPositionMintTokenProgramId()
.equals(
withTokenExtension ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID,
),
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/whirlpool-impl.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import {
createBurnInstruction,
createCloseAccountInstruction,
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import {
PDAUtil,
PriceMath,
TickUtil,
WhirlpoolIx,
buildWhirlpoolClient,
collectFeesQuote,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidity,
increaseLiquidityQuoteByInputToken,
increaseLiquidityQuoteByInputTokenUsingPriceSlippage,
swapQuoteByInputToken,
toTx,
} from "../../../src";
import { WhirlpoolContext } from "../../../src/context";
import { IGNORE_CACHE } from "../../../src/network/public/fetcher";
import {
ONE_SOL,
TEST_TOKEN_2022_PROGRAM_ID,
TEST_TOKEN_PROGRAM_ID,
TickSpacing,
ZERO_BN,
createAssociatedTokenAccount,
getTokenBalance,
sleep,
systemTransferTx,
transferToken,
} from "../../utils";
import { defaultConfirmOptions } from "../../utils/const";
import { WhirlpoolTestFixture } from "../../utils/fixture";
import { TokenExtensionUtil } from "../../../src/utils/public/token-extension-util";
import type { TokenTrait } from "../../utils/v2/init-utils-v2";
import { initTestPoolV2, useMaxCU } from "../../utils/v2/init-utils-v2";
import { mintTokensToTestAccountV2 } from "../../utils/v2/token-2022";
import { WhirlpoolTestFixtureV2 } from "../../utils/v2/fixture-v2";
import { ASSOCIATED_PROGRAM_ID } from "@coral-xyz/anchor/dist/cjs/utils/token";
import { initTestPool } from "../../utils/init-utils";
import { mintTokensToTestAccount } from "../../utils/test-builders";
describe("whirlpool-impl", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
// TransferHook is most difficult extension in transaction size
tokenTraitA: { isToken2022: true, hasTransferHookExtension: true },
tokenTraitB: { isToken2022: true, hasTransferHookExtension: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}`, () => {
it("open and add liquidity to a position, then close [TokenAmount Slippage]", async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
// Verify token mint info is correct
const tokenAInfo = pool.getTokenAInfo();
const tokenBInfo = pool.getTokenBInfo();
assert.ok(tokenAInfo.mint.equals(poolInitInfo.tokenMintA));
assert.ok(tokenBInfo.mint.equals(poolInitInfo.tokenMintB));
// Create and mint tokens in this wallet
const mintedTokenAmount = 150_000_000;
const [userTokenAAccount, userTokenBAccount] =
await mintTokensToTestAccountV2(
ctx.provider,
tokenAInfo.mint,
tokenTraits.tokenTraitA,
mintedTokenAmount,
tokenBInfo.mint,
tokenTraits.tokenTraitB,
mintedTokenAmount,
);
// Open a position with no tick arrays initialized.
const lowerPrice = new Decimal(96);
const upperPrice = new Decimal(101);
const poolData = pool.getData();
const tokenADecimal = tokenAInfo.decimals;
const tokenBDecimal = tokenBInfo.decimals;
const tickLower = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(lowerPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const tickUpper = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(upperPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const inputTokenMint = poolData.tokenMintA;
const quote = increaseLiquidityQuoteByInputToken(
inputTokenMint,
new Decimal(50),
tickLower,
tickUpper,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (
await pool.initTickArrayForTicks(
[tickLower, tickUpper],
funderKeypair.publicKey,
)
)?.addSigner(funderKeypair);
assert.ok(!!initTickArrayTx);
// [Action] Open Position (and increase L)
const { positionMint, tx: openIx } = await pool.openPosition(
tickLower,
tickUpper,
quote,
ctx.wallet.publicKey,
funderKeypair.publicKey,
);
openIx.addSigner(funderKeypair);
await initTickArrayTx.buildAndExecute();
await openIx.buildAndExecute();
// Verify position exists and numbers fit input parameters
const positionAddress = PDAUtil.getPosition(
ctx.program.programId,
positionMint,
).publicKey;
const position = await client.getPosition(
positionAddress,
IGNORE_CACHE,
);
const positionData = position.getData();
const tickLowerIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
const tickUpperIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
assert.ok(positionData.liquidity.eq(quote.liquidityAmount));
assert.ok(positionData.tickLowerIndex === tickLowerIndex);
assert.ok(positionData.tickUpperIndex === tickUpperIndex);
assert.ok(positionData.positionMint.equals(positionMint));
assert.ok(
positionData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey),
);
// [Action] Close Position
const txs = await pool.closePosition(
positionAddress,
Percentage.fromFraction(1, 100),
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify position is closed and owner wallet has the tokens back
const postClosePosition = await fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
assert.ok(postClosePosition === null);
// TODO: we are leaking 1 decimal place of token?
assert.equal(
await getTokenBalance(ctx.provider, userTokenAAccount),
mintedTokenAmount - 1,
);
assert.equal(
await getTokenBalance(ctx.provider, userTokenBAccount),
mintedTokenAmount - 1,
);
});
it("open and add liquidity to a position, transfer position to another wallet, then close the tokens to another wallet [TokenAmount Slippage]", async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
// Verify token mint info is correct
const tokenAInfo = pool.getTokenAInfo();
const tokenBInfo = pool.getTokenBInfo();
assert.ok(tokenAInfo.mint.equals(poolInitInfo.tokenMintA));
assert.ok(tokenBInfo.mint.equals(poolInitInfo.tokenMintB));
// Create and mint tokens in this wallet
const mintedTokenAmount = 150_000_000;
await mintTokensToTestAccountV2(
ctx.provider,
tokenAInfo.mint,
tokenTraits.tokenTraitA,
mintedTokenAmount,
tokenBInfo.mint,
tokenTraits.tokenTraitB,
mintedTokenAmount,
);
// Open a position with no tick arrays initialized.
const lowerPrice = new Decimal(96);
const upperPrice = new Decimal(101);
const poolData = pool.getData();
const tokenADecimal = tokenAInfo.decimals;
const tokenBDecimal = tokenBInfo.decimals;
const tickLower = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(lowerPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const tickUpper = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(upperPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const inputTokenMint = poolData.tokenMintA;
const depositAmount = new Decimal(50);
const quote = increaseLiquidityQuoteByInputToken(
inputTokenMint,
depositAmount,
tickLower,
tickUpper,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (
await pool.initTickArrayForTicks(
[tickLower, tickUpper],
funderKeypair.publicKey,
)
)?.addSigner(funderKeypair);
assert.ok(!!initTickArrayTx);
// [Action] Open Position (and increase L)
const { positionMint, tx: openIx } = await pool.openPosition(
tickLower,
tickUpper,
quote,
ctx.wallet.publicKey,
funderKeypair.publicKey,
);
openIx.addSigner(funderKeypair);
await initTickArrayTx.buildAndExecute();
await openIx.buildAndExecute();
// Verify position exists and numbers fit input parameters
const positionAddress = PDAUtil.getPosition(
ctx.program.programId,
positionMint,
).publicKey;
const position = await client.getPosition(
positionAddress,
IGNORE_CACHE,
);
const positionData = position.getData();
const tickLowerIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
const tickUpperIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
assert.ok(positionData.liquidity.eq(quote.liquidityAmount));
assert.ok(positionData.tickLowerIndex === tickLowerIndex);
assert.ok(positionData.tickUpperIndex === tickUpperIndex);
assert.ok(positionData.positionMint.equals(positionMint));
assert.ok(
positionData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey),
);
// Transfer the position token to another wallet
const otherWallet = anchor.web3.Keypair.generate();
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionMint,
ctx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionMint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await transferToken(
provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
// [Action] Close Position
const expectationQuote = await decreaseLiquidityQuoteByLiquidity(
positionData.liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
const destinationWallet = anchor.web3.Keypair.generate();
const txs = await pool.closePosition(
positionAddress,
Percentage.fromFraction(1, 100),
destinationWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
for (const tx of txs) {
await tx.addSigner(otherWallet).buildAndExecute();
}
// Verify position is closed and owner wallet has the tokens back
const postClosePosition = await fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
assert.ok(postClosePosition === null);
const tokenProgramA = tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const tokenProgramB = tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const dWalletTokenAAccount = getAssociatedTokenAddressSync(
poolData.tokenMintA,
destinationWallet.publicKey,
undefined,
tokenProgramA,
);
const dWalletTokenBAccount = getAssociatedTokenAddressSync(
poolData.tokenMintB,
destinationWallet.publicKey,
undefined,
tokenProgramB,
);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenAAccount),
expectationQuote.tokenMinA.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenBAccount),
expectationQuote.tokenMinB.toString(),
);
});
it("open and add liquidity to a position, then close [Price Slippage]", async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
// Verify token mint info is correct
const tokenAInfo = pool.getTokenAInfo();
const tokenBInfo = pool.getTokenBInfo();
assert.ok(tokenAInfo.mint.equals(poolInitInfo.tokenMintA));
assert.ok(tokenBInfo.mint.equals(poolInitInfo.tokenMintB));
// Create and mint tokens in this wallet
const mintedTokenAmount = 150_000_000;
const [userTokenAAccount, userTokenBAccount] =
await mintTokensToTestAccountV2(
ctx.provider,
tokenAInfo.mint,
tokenTraits.tokenTraitA,
mintedTokenAmount,
tokenBInfo.mint,
tokenTraits.tokenTraitB,
mintedTokenAmount,
);
// Open a position with no tick arrays initialized.
const lowerPrice = new Decimal(96);
const upperPrice = new Decimal(101);
const poolData = pool.getData();
const tokenADecimal = tokenAInfo.decimals;
const tokenBDecimal = tokenBInfo.decimals;
const tickLower = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(lowerPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const tickUpper = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(upperPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const inputTokenMint = poolData.tokenMintA;
const quote = increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
inputTokenMint,
new Decimal(50),
tickLower,
tickUpper,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (
await pool.initTickArrayForTicks(
[tickLower, tickUpper],
funderKeypair.publicKey,
)
)?.addSigner(funderKeypair);
assert.ok(!!initTickArrayTx);
// [Action] Open Position (and increase L)
const { positionMint, tx: openIx } = await pool.openPosition(
tickLower,
tickUpper,
quote,
ctx.wallet.publicKey,
funderKeypair.publicKey,
);
openIx.addSigner(funderKeypair);
await initTickArrayTx.buildAndExecute();
await openIx.buildAndExecute();
// Verify position exists and numbers fit input parameters
const positionAddress = PDAUtil.getPosition(
ctx.program.programId,
positionMint,
).publicKey;
const position = await client.getPosition(
positionAddress,
IGNORE_CACHE,
);
const positionData = position.getData();
const tickLowerIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
const tickUpperIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
assert.ok(positionData.liquidity.eq(quote.liquidityAmount));
assert.ok(positionData.tickLowerIndex === tickLowerIndex);
assert.ok(positionData.tickUpperIndex === tickUpperIndex);
assert.ok(positionData.positionMint.equals(positionMint));
assert.ok(
positionData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey),
);
// [Action] Close Position
const txs = await pool.closePosition(
positionAddress,
Percentage.fromFraction(1, 100),
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify position is closed and owner wallet has the tokens back
const postClosePosition = await fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
assert.ok(postClosePosition === null);
// TODO: we are leaking 1 decimal place of token?
assert.equal(
await getTokenBalance(ctx.provider, userTokenAAccount),
mintedTokenAmount - 1,
);
assert.equal(
await getTokenBalance(ctx.provider, userTokenBAccount),
mintedTokenAmount - 1,
);
});
it("open and add liquidity to a position, transfer position to another wallet, then close the tokens to another wallet [Price Slippage]", async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
const { poolInitInfo } = await initTestPoolV2(
ctx,
tokenTraits.tokenTraitA,
tokenTraits.tokenTraitB,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
const pool = await client.getPool(poolInitInfo.whirlpoolPda.publicKey);
// Verify token mint info is correct
const tokenAInfo = pool.getTokenAInfo();
const tokenBInfo = pool.getTokenBInfo();
assert.ok(tokenAInfo.mint.equals(poolInitInfo.tokenMintA));
assert.ok(tokenBInfo.mint.equals(poolInitInfo.tokenMintB));
// Create and mint tokens in this wallet
const mintedTokenAmount = 150_000_000;
await mintTokensToTestAccountV2(
ctx.provider,
tokenAInfo.mint,
tokenTraits.tokenTraitA,
mintedTokenAmount,
tokenBInfo.mint,
tokenTraits.tokenTraitB,
mintedTokenAmount,
);
// Open a position with no tick arrays initialized.
const lowerPrice = new Decimal(96);
const upperPrice = new Decimal(101);
const poolData = pool.getData();
const tokenADecimal = tokenAInfo.decimals;
const tokenBDecimal = tokenBInfo.decimals;
const tickLower = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(lowerPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const tickUpper = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(upperPrice, tokenADecimal, tokenBDecimal),
poolData.tickSpacing,
);
const inputTokenMint = poolData.tokenMintA;
const depositAmount = new Decimal(50);
const quote = increaseLiquidityQuoteByInputTokenUsingPriceSlippage(
inputTokenMint,
depositAmount,
tickLower,
tickUpper,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (
await pool.initTickArrayForTicks(
[tickLower, tickUpper],
funderKeypair.publicKey,
)
)?.addSigner(funderKeypair);
assert.ok(!!initTickArrayTx);
// [Action] Open Position (and increase L)
const { positionMint, tx: openIx } = await pool.openPosition(
tickLower,
tickUpper,
quote,
ctx.wallet.publicKey,
funderKeypair.publicKey,
);
openIx.addSigner(funderKeypair);
await initTickArrayTx.buildAndExecute();
await openIx.buildAndExecute();
// Verify position exists and numbers fit input parameters
const positionAddress = PDAUtil.getPosition(
ctx.program.programId,
positionMint,
).publicKey;
const position = await client.getPosition(
positionAddress,
IGNORE_CACHE,
);
const positionData = position.getData();
const tickLowerIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
const tickUpperIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
assert.ok(positionData.liquidity.eq(quote.liquidityAmount));
assert.ok(positionData.tickLowerIndex === tickLowerIndex);
assert.ok(positionData.tickUpperIndex === tickUpperIndex);
assert.ok(positionData.positionMint.equals(positionMint));
assert.ok(
positionData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey),
);
// Transfer the position token to another wallet
const otherWallet = anchor.web3.Keypair.generate();
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionMint,
ctx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionMint,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await transferToken(
provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
// [Action] Close Position
const expectationQuote = await decreaseLiquidityQuoteByLiquidity(
positionData.liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
const destinationWallet = anchor.web3.Keypair.generate();
const txs = await pool.closePosition(
positionAddress,
Percentage.fromFraction(1, 100),
destinationWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
for (const tx of txs) {
await tx.addSigner(otherWallet).buildAndExecute();
}
// Verify position is closed and owner wallet has the tokens back
const postClosePosition = await fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
assert.ok(postClosePosition === null);
const tokenProgramA = tokenTraits.tokenTraitA.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const tokenProgramB = tokenTraits.tokenTraitB.isToken2022
? TEST_TOKEN_2022_PROGRAM_ID
: TEST_TOKEN_PROGRAM_ID;
const dWalletTokenAAccount = getAssociatedTokenAddressSync(
poolData.tokenMintA,
destinationWallet.publicKey,
undefined,
tokenProgramA,
);
const dWalletTokenBAccount = getAssociatedTokenAddressSync(
poolData.tokenMintB,
destinationWallet.publicKey,
undefined,
tokenProgramB,
);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenAAccount),
expectationQuote.tokenMinA.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenBAccount),
expectationQuote.tokenMinB.toString(),
);
});
it("open and add liquidity to a position, trade against it, transfer position to another wallet, then close the tokens to another wallet", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const vaultStartBalance = 1_000_000_000;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: tokenTraits.tokenTraitA,
tokenTraitB: tokenTraits.tokenTraitB,
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
rewards: [
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(5)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: { isToken2022: false },
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: {
whirlpoolPda,
tokenVaultAKeypair,
tokenVaultBKeypair,
},
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
(
await client.getPool(whirlpoolPda.publicKey, IGNORE_CACHE)
).getData(),
IGNORE_CACHE,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenAccountA,
tokenVaultAKeypair.publicKey,
ctx.wallet.publicKey,
tokenVaultBKeypair.publicKey,
tokenAccountB,
whirlpoolPda.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapV2Ix(ctx.program, {
amount: new BN(200_000),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
tokenVaultAKeypair.publicKey,
tokenAccountA,
whirlpoolPda.publicKey,
tokenAccountB,
tokenVaultBKeypair.publicKey,
ctx.wallet.publicKey,
)),
}),
)
.prependInstruction(useMaxCU()) // TransferHook require much CU
.buildAndExecute();
// accrue rewards
// closePosition does not attempt to create an ATA unless reward has accumulated.
await sleep(1200);
const [positionWithFees] = positions;
// Transfer the position token to another wallet
const otherWallet = anchor.web3.Keypair.generate();
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionWithFees.mintKeypair.publicKey,
ctx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionWithFees.mintKeypair.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await transferToken(
provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
const pool = await client.getPool(whirlpoolPda.publicKey, IGNORE_CACHE);
const position = await client.getPosition(
positionWithFees.publicKey,
IGNORE_CACHE,
);
const positionData = position.getData();
const poolData = pool.getData();
const txs = await pool.closePosition(
positionWithFees.publicKey,
new Percentage(new BN(10), new BN(100)),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
const expectationQuote = decreaseLiquidityQuoteByLiquidity(
position.getData().liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
const dWalletTokenAAccount = getAssociatedTokenAddressSync(
poolData.tokenMintA,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
);
const dWalletTokenBAccount = getAssociatedTokenAddressSync(
poolData.tokenMintB,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
);
const rewardAccount0 = getAssociatedTokenAddressSync(
poolData.rewardInfos[0].mint,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.rewardTokenMintsWithProgram[0]!.tokenProgram,
);
const rewardAccount1 = getAssociatedTokenAddressSync(
poolData.rewardInfos[1].mint,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.rewardTokenMintsWithProgram[1]!.tokenProgram,
);
const rewardAccount2 = getAssociatedTokenAddressSync(
poolData.rewardInfos[2].mint,
otherWallet.publicKey,
undefined,
tokenExtensionCtx.rewardTokenMintsWithProgram[2]!.tokenProgram,
);
const feesQuote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
});
const signatures: string[] = [];
for (const tx of txs) {
signatures.push(await tx.addSigner(otherWallet).buildAndExecute());
}
// To calculate the rewards that have accumulated up to the timing of the close (strictly, decreaseLiquidity),
// the block time at transaction execution is used.
// TODO: maxSupportedTransactionVersion needs to come from ctx
const tx = await ctx.provider.connection.getTransaction(signatures[0], {
maxSupportedTransactionVersion: 0,
});
const closeTimestampInSeconds = new anchor.BN(
tx!.blockTime!.toString(),
);
const rewardsQuote = collectRewardsQuote({
whirlpool: poolData,
position: positionData,
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx:
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
timeStampInSeconds: closeTimestampInSeconds,
});
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenAAccount),
expectationQuote.tokenMinA.add(feesQuote.feeOwedA).toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenBAccount),
expectationQuote.tokenMinB.add(feesQuote.feeOwedB).toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount0),
rewardsQuote.rewardOwed[0]?.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount1),
rewardsQuote.rewardOwed[1]?.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount2),
rewardsQuote.rewardOwed[2]?.toString(),
);
});
});
});
describe("open and close position with TokenExtensions", () => {
const withMetadataVariations = [true, false];
withMetadataVariations.forEach((withMetadata) => {
it(
withMetadata ? "openPositionWithMetadata" : "openPosition",
async () => {
const funderKeypair = anchor.web3.Keypair.generate();
await systemTransferTx(
provider,
funderKeypair.publicKey,
ONE_SOL,
).buildAndExecute();
const { poolInitInfo } = await initTestPool(
ctx,
TickSpacing.Standard,
PriceMath.priceToSqrtPriceX64(new Decimal(100), 6, 6),
);
const pool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
// Verify token mint info is correct
const tokenAInfo = pool.getTokenAInfo();
const tokenBInfo = pool.getTokenBInfo();
assert.ok(tokenAInfo.mint.equals(poolInitInfo.tokenMintA));
assert.ok(tokenBInfo.mint.equals(poolInitInfo.tokenMintB));
// Create and mint tokens in this wallet
const mintedTokenAmount = 150_000_000;
const [userTokenAAccount, userTokenBAccount] =
await mintTokensToTestAccount(
ctx.provider,
tokenAInfo.mint,
mintedTokenAmount,
tokenBInfo.mint,
mintedTokenAmount,
);
// Open a position with no tick arrays initialized.
const lowerPrice = new Decimal(96);
const upperPrice = new Decimal(101);
const poolData = pool.getData();
const tokenADecimal = tokenAInfo.decimals;
const tokenBDecimal = tokenBInfo.decimals;
const tickLower = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenADecimal,
tokenBDecimal,
),
poolData.tickSpacing,
);
const tickUpper = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenADecimal,
tokenBDecimal,
),
poolData.tickSpacing,
);
const inputTokenMint = poolData.tokenMintA;
const quote = increaseLiquidityQuoteByInputToken(
inputTokenMint,
new Decimal(50),
tickLower,
tickUpper,
Percentage.fromFraction(1, 100),
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
// [Action] Initialize Tick Arrays
const initTickArrayTx = (
await pool.initTickArrayForTicks(
[tickLower, tickUpper],
funderKeypair.publicKey,
)
)?.addSigner(funderKeypair);
assert.ok(!!initTickArrayTx);
// [Action] Open Position (and increase L)
const openMethod = withMetadata
? pool.openPositionWithMetadata.bind(pool)
: pool.openPosition.bind(pool);
const { positionMint, tx: openIx } = await openMethod(
tickLower,
tickUpper,
quote,
ctx.wallet.publicKey,
funderKeypair.publicKey,
undefined,
TOKEN_2022_PROGRAM_ID,
);
openIx.addSigner(funderKeypair);
await initTickArrayTx.buildAndExecute();
await openIx.buildAndExecute();
// Verify position exists and numbers fit input parameters
const positionAddress = PDAUtil.getPosition(
ctx.program.programId,
positionMint,
).publicKey;
const position = await client.getPosition(
positionAddress,
IGNORE_CACHE,
);
const positionData = position.getData();
const tickLowerIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
lowerPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
const tickUpperIndex = TickUtil.getInitializableTickIndex(
PriceMath.priceToTickIndex(
upperPrice,
tokenAInfo.decimals,
tokenBInfo.decimals,
),
poolData.tickSpacing,
);
assert.ok(positionData.liquidity.eq(quote.liquidityAmount));
assert.ok(positionData.tickLowerIndex === tickLowerIndex);
assert.ok(positionData.tickUpperIndex === tickUpperIndex);
assert.ok(positionData.positionMint.equals(positionMint));
assert.ok(
positionData.whirlpool.equals(poolInitInfo.whirlpoolPda.publicKey),
);
// [Action] Close Position
const txs = await pool.closePosition(
positionAddress,
Percentage.fromFraction(1, 100),
);
for (const tx of txs) {
await tx.buildAndExecute();
}
// Verify position is closed and owner wallet has the tokens back
const postClosePosition = await fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
assert.ok(postClosePosition === null);
// TODO: we are leaking 1 decimal place of token?
assert.equal(
await getTokenBalance(ctx.provider, userTokenAAccount),
mintedTokenAmount - 1,
);
assert.equal(
await getTokenBalance(ctx.provider, userTokenBAccount),
mintedTokenAmount - 1,
);
},
);
});
});
it("open and add liquidity to a position with SOL as token A, trade against it, transfer position to another wallet, then close the tokens to another wallet", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const vaultStartBalance = 1_000_000_000;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000_000),
}, // Out of range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
tokenAIsNative: true,
});
const {
poolInitInfo: { whirlpoolPda, tokenVaultAKeypair, tokenVaultBKeypair },
tokenAccountA,
tokenAccountB,
positions,
} = fixture.getInfos();
const tickArrayPda = PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolPda.publicKey,
22528,
);
const oraclePda = PDAUtil.getOracle(
ctx.program.programId,
whirlpoolPda.publicKey,
);
// Accrue fees in token A
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000_00),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(4)),
amountSpecifiedIsInput: true,
aToB: true,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// Accrue fees in token B
await toTx(
ctx,
WhirlpoolIx.swapIx(ctx.program, {
amount: new BN(200_000_00),
otherAmountThreshold: ZERO_BN,
sqrtPriceLimit: MathUtil.toX64(new Decimal(5)),
amountSpecifiedIsInput: true,
aToB: false,
whirlpool: whirlpoolPda.publicKey,
tokenAuthority: ctx.wallet.publicKey,
tokenOwnerAccountA: tokenAccountA,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenOwnerAccountB: tokenAccountB,
tokenVaultB: tokenVaultBKeypair.publicKey,
tickArray0: tickArrayPda.publicKey,
tickArray1: tickArrayPda.publicKey,
tickArray2: tickArrayPda.publicKey,
oracle: oraclePda.publicKey,
}),
).buildAndExecute();
// accrue rewards
// closePosition does not attempt to create an ATA unless reward has accumulated.
await sleep(1200);
const [positionWithFees] = positions;
// Transfer the position token to another wallet
const otherWallet = anchor.web3.Keypair.generate();
const walletPositionTokenAccount = getAssociatedTokenAddressSync(
positionWithFees.mintKeypair.publicKey,
ctx.wallet.publicKey,
);
const newOwnerPositionTokenAccount = await createAssociatedTokenAccount(
ctx.provider,
positionWithFees.mintKeypair.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
await transferToken(
provider,
walletPositionTokenAccount,
newOwnerPositionTokenAccount,
1,
);
const pool = await client.getPool(whirlpoolPda.publicKey, IGNORE_CACHE);
const position = await client.getPosition(
positionWithFees.publicKey,
IGNORE_CACHE,
);
const positionData = position.getData();
const poolData = pool.getData();
const decreaseLiquidityQuote = decreaseLiquidityQuoteByLiquidity(
position.getData().liquidity,
Percentage.fromDecimal(new Decimal(0)),
position,
pool,
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
);
const feesQuote = collectFeesQuote({
whirlpool: poolData,
position: positionData,
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
});
const dWalletTokenBAccount = getAssociatedTokenAddressSync(
poolData.tokenMintB,
otherWallet.publicKey,
);
const rewardAccount0 = getAssociatedTokenAddressSync(
poolData.rewardInfos[0].mint,
otherWallet.publicKey,
);
const rewardAccount1 = getAssociatedTokenAddressSync(
poolData.rewardInfos[1].mint,
otherWallet.publicKey,
);
const rewardAccount2 = getAssociatedTokenAddressSync(
poolData.rewardInfos[2].mint,
otherWallet.publicKey,
);
const txs = await pool.closePosition(
positionWithFees.publicKey,
new Percentage(new BN(10), new BN(100)),
otherWallet.publicKey,
otherWallet.publicKey,
ctx.wallet.publicKey,
);
// This test case is TokenProgram/TokenProgram, so at most 2 is appropriate
if (txs.length > 2) {
throw new Error(`Invalid length for txs ${txs}`);
}
const otherWalletBalanceBefore = await ctx.connection.getBalance(
otherWallet.publicKey,
);
const positionAccountBalance = await ctx.connection.getBalance(
positionWithFees.publicKey,
);
const signatures: string[] = [];
for (const tx of txs) {
signatures.push(await tx.addSigner(otherWallet).buildAndExecute());
}
// To calculate the rewards that have accumulated up to the timing of the close (strictly, decreaseLiquidity),
// the block time at transaction execution is used.
// TODO: maxSupportedTransactionVersion needs to come from ctx
const tx = await ctx.provider.connection.getTransaction(signatures[0], {
maxSupportedTransactionVersion: 0,
});
const closeTimestampInSeconds = new anchor.BN(tx!.blockTime!.toString());
const rewardsQuote = collectRewardsQuote({
whirlpool: poolData,
position: positionData,
tickLower: position.getLowerTickData(),
tickUpper: position.getUpperTickData(),
tokenExtensionCtx: await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
poolData,
IGNORE_CACHE,
),
timeStampInSeconds: closeTimestampInSeconds,
});
const otherWalletBalanceAfter = await ctx.connection.getBalance(
otherWallet.publicKey,
);
const minAccountExempt = await ctx.fetcher.getAccountRentExempt();
const solReceived = otherWalletBalanceAfter - otherWalletBalanceBefore;
/**
* Expected tokenA (SOL) returns on other wallet
* 1. withdraw value from decrease_liq (decrease_quote, though not always accurate)
* 2. accrrued fees from trade (fee_quote)
* 3. Position PDA account rent return (balance from position address account)
* 4. wSOL rent-exemption close (getAccountExemption)
* 5. Position token account rent return (getAccountExemption)
*
* Other costs from payer, but not received by other wallet
* 1. close_position tx cost
* 2. ATA account initialization
*/
const expectedtokenA = decreaseLiquidityQuote.tokenMinA
.add(feesQuote.feeOwedA)
.add(new BN(positionAccountBalance))
.add(new BN(minAccountExempt))
.add(new BN(minAccountExempt))
.toNumber();
assert.ok(solReceived === expectedtokenA);
assert.equal(
await getTokenBalance(ctx.provider, dWalletTokenBAccount),
decreaseLiquidityQuote.tokenMinB.add(feesQuote.feeOwedB).toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount0),
rewardsQuote.rewardOwed[0]?.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount1),
rewardsQuote.rewardOwed[1]?.toString(),
);
assert.equal(
await getTokenBalance(ctx.provider, rewardAccount2),
rewardsQuote.rewardOwed[2]?.toString(),
);
});
it("swap with idempotent", async () => {
// In same tick array - start index 22528
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const vaultStartBalance = 1_000_000_000;
const tickSpacing = TickSpacing.Standard;
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount: new anchor.BN(10_000_000),
}, // In range position
{
tickLowerIndex: 0,
tickUpperIndex: 128,
liquidityAmount: new anchor.BN(1_000_000),
}, // Out of range position
],
rewards: [
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(5)),
vaultAmount: new BN(vaultStartBalance),
},
{
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
const {
poolInitInfo: { whirlpoolPda },
tokenAccountB,
} = fixture.getInfos();
const pool = await client.getPool(whirlpoolPda.publicKey, IGNORE_CACHE);
// close ATA for token B
const balanceB = await getTokenBalance(ctx.provider, tokenAccountB);
await toTx(ctx, {
instructions: [
createBurnInstruction(
tokenAccountB,
pool.getData().tokenMintB,
ctx.wallet.publicKey,
BigInt(balanceB.toString()),
),
createCloseAccountInstruction(
tokenAccountB,
ctx.wallet.publicKey,
ctx.wallet.publicKey,
),
],
cleanupInstructions: [],
signers: [],
}).buildAndExecute();
const tokenAccountBData = await ctx.connection.getAccountInfo(
tokenAccountB,
"confirmed",
);
assert.ok(tokenAccountBData === null);
const quote = await swapQuoteByInputToken(
pool,
pool.getData().tokenMintA,
new BN(200_000),
Percentage.fromFraction(1, 100),
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
const tx = await pool.swap(quote);
// check generated instructions
const instructions = tx.compressIx(true).instructions;
const createIxs = instructions.filter((ix) =>
ix.programId.equals(ASSOCIATED_PROGRAM_ID),
);
assert.ok(createIxs.length === 1);
assert.ok(createIxs[0].keys[1].pubkey.equals(tokenAccountB));
assert.ok(createIxs[0].data.length === 1);
assert.ok(createIxs[0].data[0] === 1); // Idempotent
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/quote/decrease-liquidity-quote.test.ts
|
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import type { DecreaseLiquidityQuoteParam } from "../../../../src";
import {
MAX_SQRT_PRICE_BN,
MAX_TICK_INDEX,
MIN_SQRT_PRICE_BN,
MIN_TICK_INDEX,
PriceMath,
decreaseLiquidityQuoteByLiquidityWithParams,
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage,
} from "../../../../src";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../../src/utils/public/token-extension-util";
describe("edge cases", () => {
it("sqrtPrice on lower bound", async () => {
const quote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new BN(100000),
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.tokenEstA.gtn(0));
assert.ok(quote.tokenEstB.isZero());
assert.ok(quote.tokenMinA.gtn(0));
assert.ok(quote.tokenMinB.isZero());
});
it("tickCurrentIndex on lower bound but sqrtPrice not on lower bound", async () => {
assert.ok(
PriceMath.tickIndexToSqrtPriceX64(1)
.subn(1)
.gt(PriceMath.tickIndexToSqrtPriceX64(0)),
);
const quote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new BN(100000),
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1).subn(1),
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.tokenEstA.gtn(0));
assert.ok(quote.tokenEstB.gtn(0));
assert.ok(quote.tokenMinA.gtn(0));
assert.ok(quote.tokenMinB.gtn(0));
});
it("sqrtPrice on upper bound", async () => {
const quote = decreaseLiquidityQuoteByLiquidityWithParams({
liquidity: new BN(100000),
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(64),
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 64,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.tokenEstA.isZero());
assert.ok(quote.tokenEstB.gtn(0));
assert.ok(quote.tokenMinA.isZero());
assert.ok(quote.tokenMinB.gtn(0));
});
});
describe("decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage", () => {
it("normal price, 1.5% slippage", () => {
const params: DecreaseLiquidityQuoteParam = {
liquidity: new BN(100000),
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1).subn(1),
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(15, 1000), //1.5%
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
};
const quote =
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage(params);
const { lowerBound, upperBound } = PriceMath.getSlippageBoundForSqrtPrice(
params.sqrtPrice,
params.slippageTolerance,
);
const quoteAtPlusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: upperBound[0],
tickCurrentIndex: upperBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const quoteAtMinusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: lowerBound[0],
tickCurrentIndex: lowerBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const expectedTokenMinA = BN.min(
BN.min(quote.tokenEstA, quoteAtPlusSlippage.tokenEstA),
quoteAtMinusSlippage.tokenEstA,
);
const expectedTokenMinB = BN.min(
BN.min(quote.tokenEstB, quoteAtPlusSlippage.tokenEstB),
quoteAtMinusSlippage.tokenEstB,
);
assert.ok(quote.tokenMinA.eq(expectedTokenMinA));
assert.ok(quote.tokenMinB.eq(expectedTokenMinB));
});
it("normal price, 0 slippage", () => {
const params: DecreaseLiquidityQuoteParam = {
liquidity: new BN(100000),
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1).subn(1),
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 1000),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
};
const quote =
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage(params);
const { lowerBound, upperBound } = PriceMath.getSlippageBoundForSqrtPrice(
params.sqrtPrice,
params.slippageTolerance,
);
const quoteAtPlusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: upperBound[0],
tickCurrentIndex: upperBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const quoteAtMinusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: lowerBound[0],
tickCurrentIndex: lowerBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const expectedTokenMinA = BN.min(
BN.min(quote.tokenEstA, quoteAtPlusSlippage.tokenEstA),
quoteAtMinusSlippage.tokenEstA,
);
const expectedTokenMinB = BN.min(
BN.min(quote.tokenEstB, quoteAtPlusSlippage.tokenEstB),
quoteAtMinusSlippage.tokenEstB,
);
assert.ok(quote.tokenMinA.eq(expectedTokenMinA));
assert.ok(quote.tokenMinB.eq(expectedTokenMinB));
});
it("at MAX_PRICE, slippage at 1.5%", () => {
const params: DecreaseLiquidityQuoteParam = {
liquidity: new BN(100000),
sqrtPrice: MAX_SQRT_PRICE_BN,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: MAX_TICK_INDEX,
slippageTolerance: Percentage.fromFraction(15, 1000), //1.5%
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
};
const quote =
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage(params);
const { lowerBound, upperBound } = PriceMath.getSlippageBoundForSqrtPrice(
params.sqrtPrice,
params.slippageTolerance,
);
const quoteAtPlusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: upperBound[0],
tickCurrentIndex: upperBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const quoteAtMinusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: lowerBound[0],
tickCurrentIndex: lowerBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const expectedTokenMinA = BN.min(
BN.min(quote.tokenEstA, quoteAtPlusSlippage.tokenEstA),
quoteAtMinusSlippage.tokenEstA,
);
const expectedTokenMinB = BN.min(
BN.min(quote.tokenEstB, quoteAtPlusSlippage.tokenEstB),
quoteAtMinusSlippage.tokenEstB,
);
assert.ok(quote.tokenMinA.eq(expectedTokenMinA));
assert.ok(quote.tokenMinB.eq(expectedTokenMinB));
});
it("at MIN_PRICE, slippage at 1.5%", () => {
const params: DecreaseLiquidityQuoteParam = {
liquidity: new BN(100000),
sqrtPrice: MIN_SQRT_PRICE_BN,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: MIN_TICK_INDEX,
slippageTolerance: Percentage.fromFraction(15, 1000), //1.5%
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
};
const quote =
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage(params);
const { lowerBound, upperBound } = PriceMath.getSlippageBoundForSqrtPrice(
params.sqrtPrice,
params.slippageTolerance,
);
const quoteAtPlusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: upperBound[0],
tickCurrentIndex: upperBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const quoteAtMinusSlippage = decreaseLiquidityQuoteByLiquidityWithParams({
...params,
sqrtPrice: lowerBound[0],
tickCurrentIndex: lowerBound[1],
slippageTolerance: Percentage.fromFraction(0, 1000),
});
const expectedTokenMinA = BN.min(
BN.min(quoteAtMinusSlippage.tokenEstA, quoteAtPlusSlippage.tokenEstA),
quoteAtMinusSlippage.tokenEstA,
);
const expectedTokenMinB = BN.min(
BN.min(quoteAtMinusSlippage.tokenEstB, quoteAtPlusSlippage.tokenEstB),
quoteAtMinusSlippage.tokenEstB,
);
assert.ok(quote.tokenMinA.eq(expectedTokenMinA));
assert.ok(quote.tokenMinB.eq(expectedTokenMinB));
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/quote/increase-liquidity-quote-by-input-token.test.ts
|
import { Percentage, ZERO } from "@orca-so/common-sdk";
import { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import {
PriceMath,
increaseLiquidityQuoteByInputTokenWithParams,
increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage,
increaseLiquidityQuoteByLiquidityWithParams,
} from "../../../../src";
import {
getLiquidityFromTokenA,
getLiquidityFromTokenB,
} from "../../../../src/utils/position-util";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../../src/utils/public/token-extension-util";
function getTestSlippageRange(currIndex: number, slippage: Percentage) {
const sqrtPrice = PriceMath.tickIndexToSqrtPriceX64(currIndex);
const {
lowerBound: [_sLowerSqrtPrice, sLowerIndex],
upperBound: [_sUpperSqrtPrice, sUpperIndex],
} = PriceMath.getSlippageBoundForSqrtPrice(sqrtPrice, slippage);
return {
tickLowerIndex: sLowerIndex === sUpperIndex ? sLowerIndex - 1 : sLowerIndex,
tickUpperIndex: sUpperIndex,
tickCurrentIndex: currIndex,
};
}
const variations = [
[0, true, Percentage.fromFraction(1, 1000)] as const,
[0, false, Percentage.fromFraction(1, 1000)] as const,
[0, true, Percentage.fromFraction(1, 100)] as const,
[0, false, Percentage.fromFraction(1, 100)] as const,
[234653, true, Percentage.fromFraction(1, 1000)] as const,
[234653, false, Percentage.fromFraction(1, 1000)] as const,
[234653, true, Percentage.fromFraction(1, 100)] as const,
[234653, false, Percentage.fromFraction(1, 100)] as const,
[-234653, true, Percentage.fromFraction(1, 1000)] as const,
[-234653, false, Percentage.fromFraction(1, 1000)] as const,
[-234653, true, Percentage.fromFraction(1, 100)] as const,
[-234653, false, Percentage.fromFraction(1, 100)] as const,
];
// NOTE: Slippage range for current price (tick = 0) is [-101, 99]
// [---P---] = P is the current price & [] is the slippage boundary
// |-------| = Position Boundary
variations.forEach(([currentTickIndex, isTokenA, slippage]) => {
describe("increaseLiquidityQuoteByInputTokenUsingPriceSlippage", () => {
const tokenMintA = new PublicKey(
"orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE",
);
const tokenMintB = new PublicKey(
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
);
it(`|[--------P--------]| @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex,
pTickUpperIndex: slippageRange.tickCurrentIndex,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`|----------------| [---P---] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickLowerIndex - 100,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`|--------------[--|--P----] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickLowerIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[|---|---P------] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex,
pTickUpperIndex: slippageRange.tickCurrentIndex - 1,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[--|---|--P-------] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickCurrentIndex - 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`|-----[---P---]-----| @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickUpperIndex + 200,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[--|----P----]-----| @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`|--[---P---|-----] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 125,
pTickUpperIndex: slippageRange.tickCurrentIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[---|---P---|----] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickCurrentIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[---P---] |---------| @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickUpperIndex + 100,
pTickUpperIndex: slippageRange.tickUpperIndex + 200,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[---P--|---]------| @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex + 100,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[-----P--|---|] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
it(`[-------P--|---|--] @ isTokenA - ${isTokenA} tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlippageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 2,
pTickUpperIndex: slippageRange.tickUpperIndex - 2,
tickCurrentIndex: slippageRange.tickCurrentIndex,
inputTokenAmount: new BN(100000),
isTokenA,
slippageTolerance: slippage,
});
});
function testVariation(params: {
pTickLowerIndex: number;
pTickUpperIndex: number;
tickCurrentIndex: number;
inputTokenAmount: BN;
isTokenA: boolean;
slippageTolerance: Percentage;
}) {
const {
pTickLowerIndex,
pTickUpperIndex,
tickCurrentIndex,
inputTokenAmount,
isTokenA,
} = params;
const sqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickCurrentIndex);
const inputTokenMint = isTokenA ? tokenMintA : tokenMintB;
const quote =
increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage({
inputTokenAmount,
inputTokenMint,
sqrtPrice,
tokenMintA,
tokenMintB,
tickLowerIndex: pTickLowerIndex,
tickUpperIndex: pTickUpperIndex,
tickCurrentIndex,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
slippageTolerance: slippage,
});
// Expectations
const liquidity = getLiquidityFromInputToken({
inputTokenAmount,
isInputTokenA: isTokenA,
sqrtPrice,
currentTickIndex: tickCurrentIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const expectedQuote = increaseLiquidityQuoteByLiquidityWithParams({
tickLowerIndex: pTickLowerIndex,
tickUpperIndex: pTickUpperIndex,
tickCurrentIndex,
liquidity,
sqrtPrice: sqrtPrice,
slippageTolerance: slippage,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
const {
tokenEstA: expectedTokenEstA,
tokenEstB: expectedTokenEstB,
tokenMaxA: expectedTokenMaxA,
tokenMaxB: expectedTokenMaxB,
} = expectedQuote;
assert.ok(
quote.tokenEstA.eq(expectedTokenEstA),
`tokenEstA: ${quote.tokenEstA.toString()} !== ${expectedTokenEstA.toString()}`,
);
assert.ok(
quote.tokenEstB.eq(expectedTokenEstB),
`tokenEstB: ${quote.tokenEstB.toString()} !== ${expectedTokenEstB.toString()}`,
);
assert.ok(
quote.tokenMaxA.eq(expectedTokenMaxA),
`tokenMaxA: ${quote.tokenMaxA.toString()} !== ${expectedTokenMaxA.toString()}`,
);
assert.ok(
quote.tokenMaxB.eq(expectedTokenMaxB),
`tokenMaxB: ${quote.tokenMaxB.toString()} !== ${expectedTokenMaxB.toString()}`,
);
}
});
});
describe("edge cases for old slippage", () => {
const tokenMintA = new PublicKey(
"orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE",
);
const tokenMintB = new PublicKey(
"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
);
it("sqrtPrice on lower bound, tokenB input", async () => {
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintB,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.isZero());
assert.ok(quote.tokenEstA.isZero());
assert.ok(quote.tokenEstB.isZero());
assert.ok(quote.tokenMaxA.isZero());
assert.ok(quote.tokenMaxB.isZero());
});
it("sqrtPrice on lower bound, tokenA input", async () => {
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintA,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(0),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.gtn(0));
assert.ok(quote.tokenEstA.gtn(0));
assert.ok(quote.tokenEstB.isZero());
assert.ok(quote.tokenMaxA.gtn(0));
assert.ok(quote.tokenMaxB.isZero());
});
it("tickCurrentIndex on lower bound but sqrtPrice not on lower bound, tokenA input", async () => {
assert.ok(
PriceMath.tickIndexToSqrtPriceX64(1)
.subn(1)
.gt(PriceMath.tickIndexToSqrtPriceX64(0)),
);
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintA,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1).subn(1),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.gtn(0));
assert.ok(quote.tokenEstA.gtn(0));
assert.ok(quote.tokenEstB.gtn(0));
assert.ok(quote.tokenMaxA.gtn(0));
assert.ok(quote.tokenMaxB.gtn(0));
});
it("tickCurrentIndex on lower bound but sqrtPrice not on lower bound, tokenB input", async () => {
assert.ok(
PriceMath.tickIndexToSqrtPriceX64(1)
.subn(1)
.gt(PriceMath.tickIndexToSqrtPriceX64(0)),
);
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintB,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(1).subn(1),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 0,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.gtn(0));
assert.ok(quote.tokenEstA.gtn(0));
assert.ok(quote.tokenEstB.gtn(0));
assert.ok(quote.tokenMaxA.gtn(0));
assert.ok(quote.tokenMaxB.gtn(0));
});
it("sqrtPrice on upper bound, tokenA input", async () => {
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintA,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(64),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 64,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.isZero());
assert.ok(quote.tokenEstA.isZero());
assert.ok(quote.tokenEstB.isZero());
assert.ok(quote.tokenMaxA.isZero());
assert.ok(quote.tokenMaxB.isZero());
});
it("sqrtPrice on upper bound, tokenB input", async () => {
const quote = increaseLiquidityQuoteByInputTokenWithParams({
inputTokenAmount: new BN(1000),
inputTokenMint: tokenMintB,
sqrtPrice: PriceMath.tickIndexToSqrtPriceX64(64),
tokenMintA,
tokenMintB,
tickLowerIndex: 0,
tickUpperIndex: 64,
tickCurrentIndex: 64,
slippageTolerance: Percentage.fromFraction(0, 100),
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
assert.ok(quote.liquidityAmount.gtn(0));
assert.ok(quote.tokenEstA.isZero());
assert.ok(quote.tokenEstB.gtn(0));
assert.ok(quote.tokenMaxA.isZero());
assert.ok(quote.tokenMaxB.gtn(0));
});
});
function getLiquidityFromInputToken(params: {
inputTokenAmount: BN;
isInputTokenA: boolean;
currentTickIndex: number;
sqrtPrice: BN;
lowerTickIndex: number;
upperTickIndex: number;
}) {
const {
inputTokenAmount,
isInputTokenA,
sqrtPrice,
currentTickIndex,
lowerTickIndex,
upperTickIndex,
} = params;
const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(lowerTickIndex);
const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(upperTickIndex);
if (currentTickIndex >= upperTickIndex) {
return isInputTokenA
? ZERO
: getLiquidityFromTokenB(
inputTokenAmount,
lowerSqrtPrice,
upperSqrtPrice,
false,
);
}
if (currentTickIndex < lowerTickIndex) {
return isInputTokenA
? getLiquidityFromTokenA(
inputTokenAmount,
lowerSqrtPrice,
upperSqrtPrice,
false,
)
: ZERO;
}
return isInputTokenA
? getLiquidityFromTokenA(inputTokenAmount, sqrtPrice, upperSqrtPrice, false)
: getLiquidityFromTokenB(
inputTokenAmount,
lowerSqrtPrice,
sqrtPrice,
false,
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/quote/increase-liquidity-quote-by-liq.test.ts
|
import { Percentage, ZERO } from "@orca-so/common-sdk";
import assert from "assert";
import BN from "bn.js";
import {
PriceMath,
increaseLiquidityQuoteByLiquidityWithParams,
} from "../../../../src";
import {
getTokenAFromLiquidity,
getTokenBFromLiquidity,
} from "../../../../src/utils/position-util";
import { NO_TOKEN_EXTENSION_CONTEXT } from "../../../../src/utils/public/token-extension-util";
const variations = [
[0, Percentage.fromFraction(1, 1000), new BN(17733543)] as const,
[0, Percentage.fromFraction(1, 100), new BN(17733543)] as const,
[0, Percentage.fromFraction(5, 100), new BN(17733543)] as const,
[234653, Percentage.fromFraction(1, 1000), new BN(17733543)] as const,
[234653, Percentage.fromFraction(1, 100), new BN(17733543)] as const,
[234653, Percentage.fromFraction(5, 100), new BN(17733543)] as const,
[-234653, Percentage.fromFraction(1, 1000), new BN(17733543)] as const,
[-234653, Percentage.fromFraction(1, 100), new BN(17733543)] as const,
[-234653, Percentage.fromFraction(5, 100), new BN(17733543)] as const,
];
function getTestSlipageRange(currIndex: number, slippage: Percentage) {
const sqrtPrice = PriceMath.tickIndexToSqrtPriceX64(currIndex);
const {
lowerBound: [_sLowerSqrtPrice, sLowerIndex],
upperBound: [_sUpperSqrtPrice, sUpperIndex],
} = PriceMath.getSlippageBoundForSqrtPrice(sqrtPrice, slippage);
return {
tickLowerIndex: sLowerIndex === sUpperIndex ? sLowerIndex - 1 : sLowerIndex,
tickUpperIndex: sUpperIndex,
tickCurrentIndex: currIndex,
};
}
// [---P---] = P is the current price & [] is the slippage boundary
// |-------| = Position Boundary
variations.forEach(([currentTickIndex, slippage, liquidity]) => {
describe("increaseLiquidityQuoteByLiquidity", () => {
it(`|[--------P--------]| @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex,
pTickUpperIndex: slippageRange.tickCurrentIndex,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`|----------------| [---P---] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickLowerIndex - 100,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`|--------------[--|--P----] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickLowerIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[|---|---P------] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex,
pTickUpperIndex: slippageRange.tickCurrentIndex - 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[--|---|--P-------] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickCurrentIndex - 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`|-----[---P---]-----| @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 200,
pTickUpperIndex: slippageRange.tickUpperIndex + 200,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[--|----P----]-----| @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`|--[---P---|-----] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex - 125,
pTickUpperIndex: slippageRange.tickCurrentIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[---|---P---|----] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickLowerIndex + 5,
pTickUpperIndex: slippageRange.tickCurrentIndex + 5,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[---P---] |---------| @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickUpperIndex + 100,
pTickUpperIndex: slippageRange.tickUpperIndex + 200,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[---P--|---]------| @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex + 100,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[-----P--|---|] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 5,
pTickUpperIndex: slippageRange.tickUpperIndex,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
it(`[-------P--|---|--] @ tickCurrentIndex - ${currentTickIndex}, slippage - ${slippage.toDecimal()}%`, async () => {
const slippageRange = getTestSlipageRange(currentTickIndex, slippage);
testVariation({
pTickLowerIndex: slippageRange.tickCurrentIndex + 2,
pTickUpperIndex: slippageRange.tickUpperIndex - 2,
tickCurrentIndex: slippageRange.tickCurrentIndex,
liquidity,
slippageTolerance: slippage,
});
});
async function testVariation(params: {
pTickLowerIndex: number;
pTickUpperIndex: number;
tickCurrentIndex: number;
liquidity: BN;
slippageTolerance: Percentage;
}) {
const { pTickLowerIndex, pTickUpperIndex, tickCurrentIndex, liquidity } =
params;
const sqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickCurrentIndex);
const quote = increaseLiquidityQuoteByLiquidityWithParams({
liquidity,
sqrtPrice,
tickLowerIndex: pTickLowerIndex,
tickUpperIndex: pTickUpperIndex,
tickCurrentIndex,
slippageTolerance: params.slippageTolerance,
tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, // TokenExtension is not related to this test
});
const {
lowerBound: [sLowerSqrtPrice, sLowerIndex],
upperBound: [sUpperSqrtPrice, sUpperIndex],
} = PriceMath.getSlippageBoundForSqrtPrice(sqrtPrice, slippage);
const upperTokenEstA = getTokenEstA({
liquidity,
sqrtPrice: sUpperSqrtPrice,
currentTickIndex: sUpperIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const upperTokenEstB = getTokenEstB({
liquidity,
sqrtPrice: sUpperSqrtPrice,
currentTickIndex: sUpperIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const lowerTokenEstA = getTokenEstA({
liquidity,
sqrtPrice: sLowerSqrtPrice,
currentTickIndex: sLowerIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const lowerTokenEstB = getTokenEstB({
liquidity,
sqrtPrice: sLowerSqrtPrice,
currentTickIndex: sLowerIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const expectedTokenMaxA = BN.max(
BN.max(quote.tokenEstA, upperTokenEstA),
lowerTokenEstA,
);
const expectedTokenMaxB = BN.max(
BN.max(quote.tokenEstB, upperTokenEstB),
lowerTokenEstB,
);
// Generate expectations for TokenEstA and TokenEstB
const expectedTokenEstA = getTokenEstA({
liquidity,
sqrtPrice,
currentTickIndex: tickCurrentIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
const expectedTokenEstB = getTokenEstB({
liquidity,
sqrtPrice,
currentTickIndex: tickCurrentIndex,
lowerTickIndex: pTickLowerIndex,
upperTickIndex: pTickUpperIndex,
});
assert.ok(
quote.tokenEstA.eq(expectedTokenEstA),
`tokenEstA: ${quote.tokenEstA.toString()} !== ${expectedTokenEstA.toString()}`,
);
assert.ok(
quote.tokenEstB.eq(expectedTokenEstB),
`tokenEstB: ${quote.tokenEstB.toString()} !== ${expectedTokenEstB.toString()}`,
);
assert.ok(
quote.tokenMaxA.eq(expectedTokenMaxA),
`tokenMaxA: ${quote.tokenMaxA.toString()} !== ${expectedTokenMaxA.toString()}`,
);
assert.ok(
quote.tokenMaxB.eq(expectedTokenMaxB),
`tokenMaxB: ${quote.tokenMaxB.toString()} !== ${expectedTokenMaxB.toString()}`,
);
}
});
});
function getTokenEstA(params: {
liquidity: BN;
sqrtPrice: BN;
currentTickIndex: number;
lowerTickIndex: number;
upperTickIndex: number;
}) {
const {
liquidity,
sqrtPrice,
currentTickIndex,
lowerTickIndex,
upperTickIndex,
} = params;
const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(lowerTickIndex);
const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(upperTickIndex);
if (currentTickIndex >= upperTickIndex) {
return ZERO;
}
if (currentTickIndex < lowerTickIndex) {
return getTokenAFromLiquidity(
liquidity,
lowerSqrtPrice,
upperSqrtPrice,
true,
);
}
return getTokenAFromLiquidity(liquidity, sqrtPrice, upperSqrtPrice, true);
}
function getTokenEstB(params: {
liquidity: BN;
sqrtPrice: BN;
currentTickIndex: number;
lowerTickIndex: number;
upperTickIndex: number;
}) {
const {
liquidity,
sqrtPrice,
currentTickIndex,
lowerTickIndex,
upperTickIndex,
} = params;
const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(lowerTickIndex);
const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(upperTickIndex);
if (currentTickIndex < lowerTickIndex) {
return ZERO;
}
if (currentTickIndex >= upperTickIndex) {
return getTokenBFromLiquidity(
liquidity,
lowerSqrtPrice,
upperSqrtPrice,
true,
);
}
return getTokenBFromLiquidity(liquidity, lowerSqrtPrice, sqrtPrice, true);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/swap-array.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { AddressUtil, Percentage, ZERO } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import {
PriceMath,
SwapUtils,
TICK_ARRAY_SIZE,
WhirlpoolContext,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteWithParams,
} from "../../../../src";
import type { WhirlpoolsError } from "../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../src/errors/errors";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { adjustForSlippage } from "../../../../src/utils/position-util";
import { TickSpacing } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
setupSwapTest,
} from "../../../utils/swap-test-utils";
import { getTickArrays } from "../../../utils/testDataTypes";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("swap arrays test", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
/**
* |--------------------|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("3 sequential arrays, 2nd array not initialized, use tickArray0 only, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 8446 (arrayIndex: 1)
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |--------------------|xxxxxxxxxxxxxc2xx|------c1-----------|
*/
it("3 sequential arrays, 2nd array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(40_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 4091 (arrayIndex: 0 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 4091);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc2xx|xxxxxxxxxxxxxxxxx|------c1-----------|
*/
it("3 sequential arrays, 2nd and 3rd array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -4522 (arrayIndex: -1 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, -4522);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc2xx|xxxxxxxxxxxxxxxxx|xxxxxxc1xxxxxxxxxxx|
*/
it("3 sequential arrays, all array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -4522 (arrayIndex: -1 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, -4522);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|-------------------|
*/
it("3 sequential arrays, 2nd array not initialized, use tickArray0 only, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -2816 (arrayIndex: -1)
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |-------------c1-----|xxc2xxxxxxxxxxxxx|-------------------|
*/
it("3 sequential arrays, 2nd array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(40_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 556 (arrayIndex: 0 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 556);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |-------------c1-----|xxxxxxxxxxxxxxxxx|xxc2xxxxxxxxxxxxx|
*/
it("3 sequential arrays, 2nd and 3rd array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 7662 (arrayIndex: 1 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 7662);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc1xxxxx|xxxxxxxxxxxxxxxxx|xxc2xxxxxxxxxxxxx|
*/
it("3 sequential arrays, all array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 7662 (arrayIndex: 1 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 7662);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("3 sequential arrays, 2nd array and 3rd array not initialized, use tickArray0 only, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 8446 (arrayIndex: 1)
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxxxx|
*/
it("3 sequential arrays, 2nd array and 3rd array not initialized, use tickArray0 only, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -2816 (arrayIndex: -1)
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* c1|------------------|-----------------|-------------------|
*/
it("3 sequential arrays does not contain curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|-----------------|-------------------|c1
*/
it("3 sequential arrays does not contain curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.getData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|------c1---------|-------------------|
*/
it("3 sequential arrays, 2nd array contains curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|------c1---------|-------------------|
*/
it("3 sequential arrays, 2nd array contains curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264, 16896],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |---a-c2--(5632)-----|------(0)--------|---c1--(11264)--a-|
*/
it("on first array, 2nd array is not sequential, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await getTickArrays(
[11264, 0, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorCodeMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
const messageMatch =
whirlErr.message.indexOf("TickArray at index 1 is unexpected") >= 0;
return errorCodeMatch && messageMatch;
},
);
});
/**
* |-a--(-11264)---c1---|--------(0)------|----(-5632)---c2--a-|
*/
it("on first array, 2nd array is not sequential, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: -1, offsetIndex: TICK_ARRAY_SIZE - 2 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await getTickArrays(
[-11264, 0, -5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorCodeMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
const messageMatch =
whirlErr.message.indexOf("TickArray at index 1 is unexpected") >= 0;
return errorCodeMatch && messageMatch;
},
);
});
/**
* |-------(5632)------|-------(5632)------|---c2--(5632)-c1---|
*/
it("3 identical arrays, 1st contains curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [5632],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await getTickArrays(
[5632, 5632, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
const tradeAmount = new BN("33588");
const quote = swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: tradeAmount,
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
);
// Verify with an actual swap.
assert.equal(quote.aToB, aToB);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(aToB).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |---c1--(5632)-c2---|-------(5632)------|-------(5632)------|
*/
it("3 identical arrays, 1st contains curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 4 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [5632],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await getTickArrays(
[5632, 5632, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
const tradeAmount = new BN("33588");
const quote = swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: tradeAmount,
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
);
// Verify with an actual swap.
assert.equal(quote.aToB, aToB);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(aToB).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |xxxxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("Whirlpool.swap with uninitialized TickArrays, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const aToB = true;
const tickArrays = SwapUtils.getTickArrayPublicKeys(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
);
// SparseSwap makes it possible to execute this swap.
await assert.doesNotReject(
whirlpool.swap({
amount: tradeAmount,
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArray0: tickArrays[0],
tickArray1: tickArrays[1], // uninitialized TickArray is acceptable
tickArray2: tickArrays[2], // uninitialized TickArray is acceptable
}),
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxxxx|
*/
it("Whirlpool.swap with uninitialized TickArrays, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const aToB = false;
const tickArrays = SwapUtils.getTickArrayPublicKeys(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
);
// SparseSwap makes it possible to execute this swap.
await assert.doesNotReject(
whirlpool.swap({
amount: tradeAmount,
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArray0: tickArrays[0],
tickArray1: tickArrays[1], // uninitialized TickArray is acceptable
tickArray2: tickArrays[2], // uninitialized TickArray is acceptable
}),
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/swap-traverse.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import {
buildWhirlpoolClient,
MAX_SQRT_PRICE,
MAX_TICK_INDEX,
MIN_SQRT_PRICE,
MIN_TICK_INDEX,
PriceMath,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
SwapUtils,
TICK_ARRAY_SIZE,
WhirlpoolContext,
} from "../../../../src";
import type { WhirlpoolsError } from "../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../src/errors/errors";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import {
assertInputOutputQuoteEqual,
assertQuoteAndResults,
TickSpacing,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
setupSwapTest,
} from "../../../utils/swap-test-utils";
import { getVaultAmounts } from "../../../utils/whirlpools-test-utils";
import { TokenExtensionUtil } from "../../../../src/utils/public/token-extension-util";
describe("swap traversal tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
/**
* |--------------------|b-----x2----a-------b-|x1-a------------------|
*/
it("curr_index on the last initializable tick, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 15 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 44 },
{ arrayIndex: 0, offsetIndex: 30 },
tickSpacing,
new BN(250_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 0 },
{ arrayIndex: -1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(150000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------------------x1,a|-b--------a----x2---b-|-------------------|
*/
it("curr_index on the last initializable tick, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(190000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* b|-----x2---------|a---------------|a,x1-------------b|
*/
it("curr_index on the first initializable tick, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* b|a,x1--------------|a---------------|---------x2--------b|
*/
it("curr_index on the first initializable tick, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 0 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(450000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------b-----x1-a|------a---x2---b--|-------------------|
*/
it("curr_index on the 2nd last initialized tick, with the next tick initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 2 }, // 5504
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(150000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----------b--x2--|-------a-----b-----|a-x1-------------|
*/
it("curr_index on the 2nd initialized tick, with the first tick initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 1 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(75000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------b-----a-x1|a---------x2---b--|-------------------|
*/
it("curr_index btw end of last offset and next array, with the next tick initialized, b->a", async () => {
const currIndex = 5629;
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 1 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(15000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----------b--x2--|-------a-----b-----|x1,a-------------|
*/
it("curr_index btw end of last offset and next array, with the next tick initialized, a->b", async () => {
const currIndex = 11264 + 30;
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(7500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |----------------|-----a----x2-----b|--------x1----a---b----|
*/
it("on some tick, traverse to the 1st initialized tick in the next tick-array, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 2, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(45000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |----a--b---x1------|a---x2-----b-------|------------------|
*/
it("on some tick, traverse to the 1st initialized tick in the next tick-array, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 64 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 0, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 22 },
{ arrayIndex: 0, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(49500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-------a----x2------|-----------------|----x1-----a-------|
*/
it("on some tick, traverse to the next tick in the n+2 tick-array, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-------a------x1----|-----------------|-----x2--------a---|
*/
it("on some tick, traverse to the next tick in the n+2 tick-array, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* a|----------------|-----------------|-------x1--------|a
*/
it("3 arrays, on some initialized tick, no other initialized tick in the sequence, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----x1-------------|-----------------|-------------------|
*/
it("3 arrays, on some initialized tick, no other initialized tick in the sequence, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* [1, 0, -1]
* e|---c--x2----a---d----b|f-----a--b----d----|f-----c---x1-------|e
*/
it("3 arrays, on some uninitialized tick, traverse lots of ticks, a->b", async () => {
const currIndex =
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 25 },
tickSpacing,
) - 30;
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// e
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000),
),
buildPosition(
// c
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 15 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 30 },
{ arrayIndex: 0, offsetIndex: 20 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// d
{ arrayIndex: -1, offsetIndex: 60 },
{ arrayIndex: 0, offsetIndex: 60 },
tickSpacing,
new BN(50_000_000),
),
buildPosition(
// f
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(25_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(102195000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* e|---c--x1----a---d--b---|f-----a--b----d----|f------c---x2--------|e
*/
it("3 arrays, on some uninitialized tick, traverse lots of ticks, b->a", async () => {
const currIndex =
arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 15 },
tickSpacing,
) - 30;
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// e
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000),
),
buildPosition(
// c
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 15 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 30 },
{ arrayIndex: 0, offsetIndex: 20 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// d
{ arrayIndex: -1, offsetIndex: 60 },
{ arrayIndex: 0, offsetIndex: 60 },
tickSpacing,
new BN(50_000_000),
),
buildPosition(
// f
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(25_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(99900000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* trade amount > liquidity
* |----------x1----------|-----------------|-------------------|
*/
it("3 arrays, trade amount exceeds liquidity available in array sequence, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
await assert.rejects(
async () =>
await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(9159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
// Message contains failure on finding beyond tickIndex
const messageMatch = whirlErr.message.indexOf("11264") >= 0;
assert.ok(messageMatch, "Error Message must match condition.");
assert.ok(errorMatch, "Error Code must match condition.");
return true;
},
);
});
/**
* trade amount > liquidity
* |--------------------|-----------------|---------x1----------|
*/
it("3 arrays, trade amount exceeds liquidity available in array sequence, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
await assert.rejects(
async () =>
await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(9159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
// Message contains failure on finding beyond tickIndex
const messageMatch = whirlErr.message.indexOf("-5696") >= 0;
assert.ok(messageMatch, "Error Message must match condition.");
assert.ok(errorMatch, "Error Code must match condition.");
return true;
},
);
});
/**
* |a--------x1----------a| Max
*/
it("on the last tick-array, traverse to the MAX_TICK_INDEX tick", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 78, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [MAX_TICK_INDEX],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 78, offsetIndex: 0 }, // 439,296
{ arrayIndex: 78, offsetIndex: 67 }, // 443,584
tickSpacing,
new BN(250),
),
],
tokenMintAmount: new BN("95000000000000000"),
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN("12595000000000"),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await (await whirlpool.swap(quote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
quote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* Min |a--------x2--------a----|-----------------|-------------------|
*/
it("on the first tick-array, traverse to the MIN_TICK_INDEX tick", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -79, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [MIN_TICK_INDEX],
fundedPositions: [
buildPosition(
// a -444,928
{ arrayIndex: -79, offsetIndex: 21 },
{ arrayIndex: -79, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250),
),
],
tokenMintAmount: new BN("95000000000000000"),
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN("12595000000000"),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await (await whirlpool.swap(quote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
quote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|-------x1-|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -tickSpacing, shifted", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 87 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|--------x1|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -1, shifted", async () => {
const currIndex = -1;
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|XXXXXXXXx1|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -1, tickCurrentIndex on uninitialized TickArray, shifted", async () => {
const currIndex = -1;
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* sqrtPriceLimit < MIN_SQRT_PRICE
* |--------------------|-----------------|---------x1----------|
*/
it("3 arrays, sqrtPriceLimit is out of bounds (< MIN_SQRT_PRICE), a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
currIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: new BN(MIN_SQRT_PRICE).subn(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.SqrtPriceOutOfBounds,
);
});
/**
* sqrtPriceLimit > MAX_SQRT_PRICE
* |-----x1-------------|-----------------|---------------------|
*/
it("3 arrays, sqrtPriceLimit is out of bounds (> MAX_SQRT_PRICE), b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
currIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: new BN(MAX_SQRT_PRICE).addn(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.SqrtPriceOutOfBounds,
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/swap-dev-fee.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { Address } from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import type { Whirlpool } from "../../../../src";
import {
buildWhirlpoolClient,
PriceMath,
swapQuoteByInputToken,
WhirlpoolContext,
} from "../../../../src";
import type { WhirlpoolsError } from "../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../src/errors/errors";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { swapQuoteByInputTokenWithDevFees } from "../../../../src/quotes/public/dev-fee-swap-quote";
import {
assertDevFeeQuotes,
assertDevTokenAmount,
assertQuoteAndResults,
TickSpacing,
} from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
setupSwapTest,
} from "../../../utils/swap-test-utils";
import { getVaultAmounts } from "../../../utils/whirlpools-test-utils";
describe("whirlpool-dev-fee-swap", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
it("swap with dev-fee 0% equals swap", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const devWallet = Keypair.generate();
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(0, 1000); // 0%
const inputTokenAmount = new BN(119500000);
const postFeeTokenAmount = inputTokenAmount.sub(
inputTokenAmount
.mul(devFeePercentage.numerator)
.div(devFeePercentage.denominator),
);
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
const postFeeInputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
postFeeTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
const inputTokenQuoteWithDevFees = await swapQuoteByInputTokenWithDevFees(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
devFeePercentage,
IGNORE_CACHE,
);
assertDevFeeQuotes(
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
);
await (
await whirlpool.swapWithDevFees(
inputTokenQuoteWithDevFees,
devWallet.publicKey,
)
).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
it("swap with dev-fee 0.1%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const devWallet = Keypair.generate();
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(1, 1000); // 0.1%
const inputTokenAmount = new BN(1195000);
const postFeeTokenAmount = inputTokenAmount.sub(
inputTokenAmount
.mul(devFeePercentage.numerator)
.div(devFeePercentage.denominator),
);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = aToB
? whirlpoolData.tokenMintA
: whirlpoolData.tokenMintB;
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const {
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
} = await getQuotes(
ctx,
whirlpool,
swapToken,
inputTokenAmount,
postFeeTokenAmount,
slippageTolerance,
devFeePercentage,
);
assertDevFeeQuotes(
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
);
await (
await whirlpool.swapWithDevFees(
inputTokenQuoteWithDevFees,
devWallet.publicKey,
)
).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
postFeeInputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
await assertDevTokenAmount(
ctx,
inputTokenQuoteWithDevFees,
swapToken,
devWallet.publicKey,
);
});
it("swap with dev-fee 1%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const devWallet = Keypair.generate();
const aToB = true;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(1, 100); // 1%
const inputTokenAmount = new BN(119500000);
const postFeeTokenAmount = inputTokenAmount.sub(
inputTokenAmount
.mul(devFeePercentage.numerator)
.div(devFeePercentage.denominator),
);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = aToB
? whirlpoolData.tokenMintA
: whirlpoolData.tokenMintB;
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const {
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
} = await getQuotes(
ctx,
whirlpool,
swapToken,
inputTokenAmount,
postFeeTokenAmount,
slippageTolerance,
devFeePercentage,
);
assertDevFeeQuotes(
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
);
await (
await whirlpool.swapWithDevFees(
inputTokenQuoteWithDevFees,
devWallet.publicKey,
)
).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
postFeeInputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
await assertDevTokenAmount(
ctx,
inputTokenQuoteWithDevFees,
swapToken,
devWallet.publicKey,
);
});
it("swap with input-token as NATIVE_MINT & dev-fee 1%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 1 },
tickSpacing,
);
const aToB = true;
const tokenAIsNative = true;
const whirlpool = await setupSwapTest(
{
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-16896, -11264, -5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(990_000_000),
),
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 0, offsetIndex: 23 },
tickSpacing,
new anchor.BN(990_000_000),
),
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 22 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(1_990_000_000),
),
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 23 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(990_000_000),
),
],
},
tokenAIsNative,
);
const { devWallet, balance: preDevWalletBalance } = await setupDevWallet(
ctx,
10_000_000,
);
const devFeePercentage = Percentage.fromFraction(1, 10000); // 0.01%
const inputTokenAmount = new BN(1_000_000_000); // Swap 1SOL
const postFeeTokenAmount = inputTokenAmount.sub(
inputTokenAmount
.mul(devFeePercentage.numerator)
.div(devFeePercentage.denominator),
);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = aToB
? whirlpoolData.tokenMintA
: whirlpoolData.tokenMintB;
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const {
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
} = await getQuotes(
ctx,
whirlpool,
swapToken,
inputTokenAmount,
postFeeTokenAmount,
slippageTolerance,
devFeePercentage,
);
assertDevFeeQuotes(
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
);
await (
await whirlpool.swapWithDevFees(
inputTokenQuoteWithDevFees,
devWallet.publicKey,
)
).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
postFeeInputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
await assertDevTokenAmount(
ctx,
inputTokenQuoteWithDevFees,
swapToken,
devWallet.publicKey,
preDevWalletBalance,
);
});
it("swap with dev-fee 50%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const devWallet = Keypair.generate();
const aToB = false;
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(500000, 1000000); // 50%
const inputTokenAmount = new BN(119500000);
const postFeeTokenAmount = inputTokenAmount.sub(
inputTokenAmount
.mul(devFeePercentage.numerator)
.div(devFeePercentage.denominator),
);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = aToB
? whirlpoolData.tokenMintA
: whirlpoolData.tokenMintB;
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const {
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
} = await getQuotes(
ctx,
whirlpool,
swapToken,
inputTokenAmount,
postFeeTokenAmount,
slippageTolerance,
devFeePercentage,
);
assertDevFeeQuotes(
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
);
await (
await whirlpool.swapWithDevFees(
inputTokenQuoteWithDevFees,
devWallet.publicKey,
)
).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
postFeeInputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
await assertDevTokenAmount(
ctx,
inputTokenQuoteWithDevFees,
swapToken,
devWallet.publicKey,
);
});
it("swap with dev-fee of 100%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(100, 100); // 100%
const inputTokenAmount = new BN(119500000);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = whirlpoolData.tokenMintB;
assert.rejects(
() =>
swapQuoteByInputTokenWithDevFees(
whirlpool,
swapToken,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
devFeePercentage,
IGNORE_CACHE,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.InvalidDevFeePercentage,
);
});
it("swap with dev-fee of 200%", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new anchor.BN(250_000_000),
),
],
});
const devFeePercentage = Percentage.fromFraction(200, 100); // 200%
const inputTokenAmount = new BN(119500000);
const whirlpoolData = await whirlpool.refreshData();
const swapToken = whirlpoolData.tokenMintB;
assert.rejects(
() =>
swapQuoteByInputTokenWithDevFees(
whirlpool,
swapToken,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
devFeePercentage,
IGNORE_CACHE,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.InvalidDevFeePercentage,
);
});
});
async function getQuotes(
ctx: WhirlpoolContext,
whirlpool: Whirlpool,
swapToken: Address,
inputTokenAmount: BN,
postFeeTokenAmount: BN,
slippageTolerance: Percentage,
devFeePercentage: Percentage,
) {
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
swapToken,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
const postFeeInputTokenQuote = await swapQuoteByInputToken(
whirlpool,
swapToken,
postFeeTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
const inputTokenQuoteWithDevFees = await swapQuoteByInputTokenWithDevFees(
whirlpool,
swapToken,
inputTokenAmount,
slippageTolerance,
ctx.program.programId,
ctx.fetcher,
devFeePercentage,
IGNORE_CACHE,
);
return {
inputTokenQuote,
postFeeInputTokenQuote,
inputTokenQuoteWithDevFees,
};
}
async function setupDevWallet(ctx: WhirlpoolContext, airdrop: number) {
// Setup dev-wallet. Airdrop some tokens in or it'll be difficult to account for
// rent-tokens when we do assertion
const devWallet = Keypair.generate();
const txn = await ctx.provider.connection.requestAirdrop(
devWallet.publicKey,
airdrop,
);
await ctx.provider.connection.confirmTransaction(txn);
const balance = await ctx.provider.connection.getBalance(devWallet.publicKey);
return { devWallet, balance };
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/swap-with-fallback.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import type { TwoHopSwapV2Params } from "../../../../src";
import {
ORCA_WHIRLPOOL_PROGRAM_ID,
PDAUtil,
PriceMath,
UseFallbackTickArray,
WhirlpoolContext,
WhirlpoolIx,
buildWhirlpoolClient,
swapQuoteByInputToken,
toTx,
twoHopSwapQuoteFromSwapQuotes,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { TickSpacing } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
setupSwapTest,
} from "../../../utils/swap-test-utils";
import {
buildTestAquariums,
getDefaultAquarium,
} from "../../../utils/init-utils";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
describe("swap with fallback test", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
const SWAP_V1_DISCRIMINATOR = Buffer.from([
0xf8, 0xc6, 0x9e, 0x91, 0xe1, 0x75, 0x87, 0xc8,
]);
const SWAP_V2_DISCRIMINATOR = Buffer.from([
0x2b, 0x04, 0xed, 0x0b, 0x1a, 0xc9, 0x1e, 0x62,
]);
/**
* |-5632-----------|0------------c2-|5632---------c1-|11264-----------|
*/
it("a->b, on rightmost quoter, ta1 = ta2", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 77 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 0, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const _taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(50_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = 4734; // arrayIndex: 0
assert.equal(quoteNever.aToB, true);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta5632));
assert.ok(quoteNever.tickArray1.equals(ta0));
assert.ok(quoteNever.tickArray2.equals(ta0)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, true);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta5632));
assert.ok(quoteAlways.tickArray1.equals(ta0));
assert.ok(quoteAlways.tickArray2.equals(ta11264)); // fallback
assert.ok(quoteAlways.supplementalTickArrays === undefined);
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
assert.equal(quoteSituational.aToB, true);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta5632));
assert.ok(quoteSituational.tickArray1.equals(ta0));
assert.ok(quoteSituational.tickArray2.equals(ta11264)); // fallback
assert.ok(quoteSituational.supplementalTickArrays === undefined);
// V1 instruction will be used because we can use tickArray2 as fallback
const tx = await whirlpool.swap(quoteAlways);
assert.ok(
tx
.compressIx(true)
.instructions.some(
(ix) =>
ix.programId.equals(ORCA_WHIRLPOOL_PROGRAM_ID) &&
ix.data.subarray(0, 8).equals(SWAP_V1_DISCRIMINATOR),
),
);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quoteAlways)).buildAndExecute(),
);
});
/**
* |-5632--------c2-|0---------------|5632---------c1-|11264-----------|
*/
it("a->b, on rightmost quoter, ta1 != ta2 (no room for fallback)", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 77 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 0, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(120_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = -1323; // arrayIndex: -1
assert.equal(quoteNever.aToB, true);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta5632));
assert.ok(quoteNever.tickArray1.equals(ta0));
assert.ok(quoteNever.tickArray2.equals(taNeg5632)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, true);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta5632));
assert.ok(quoteAlways.tickArray1.equals(ta0));
assert.ok(quoteAlways.tickArray2.equals(taNeg5632)); // no fallback tick array
assert.ok(quoteAlways.supplementalTickArrays?.length === 1);
assert.ok(quoteAlways.supplementalTickArrays[0].equals(ta11264)); // fallback in supplemental
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
assert.equal(quoteSituational.aToB, true);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta5632));
assert.ok(quoteSituational.tickArray1.equals(ta0));
assert.ok(quoteSituational.tickArray2.equals(taNeg5632)); // no fallback tick array
assert.ok(quoteSituational.supplementalTickArrays?.length === 1);
assert.ok(quoteSituational.supplementalTickArrays[0].equals(ta11264)); // fallback in supplemental
// V2 instruction will be used to use supplemental tick arrays
const tx = await whirlpool.swap(quoteAlways);
assert.ok(
tx
.compressIx(true)
.instructions.some(
(ix) =>
ix.programId.equals(ORCA_WHIRLPOOL_PROGRAM_ID) &&
ix.data.subarray(0, 8).equals(SWAP_V2_DISCRIMINATOR),
),
);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quoteAlways)).buildAndExecute(),
);
});
/**
* |-5632-----------|0------------c2-|5632-c1---------|11264-----------|
*/
it("a->b, not on rightmost quoter, ta1 = ta2", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 0, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const _taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(50_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = 3135; // arrayIndex: 0
assert.equal(quoteNever.aToB, true);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta5632));
assert.ok(quoteNever.tickArray1.equals(ta0));
assert.ok(quoteNever.tickArray2.equals(ta0)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, true);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta5632));
assert.ok(quoteAlways.tickArray1.equals(ta0));
assert.ok(quoteAlways.tickArray2.equals(ta11264)); // fallback
assert.ok(quoteAlways.supplementalTickArrays === undefined);
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
// no fallback because it is not on the rightmost quoter
assert.equal(quoteSituational.aToB, true);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta5632));
assert.ok(quoteSituational.tickArray1.equals(ta0));
assert.ok(quoteSituational.tickArray2.equals(ta0)); // no fallback tick array
assert.ok(quoteSituational.supplementalTickArrays === undefined);
});
/**
* |-5632-----------|0-c1------------|5632---------c2-|11264-----------|
*/
it("b->a, on leftmost quoter, ta1 = ta2", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 11 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const _ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(100_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = 7218; // arrayIndex: 1
assert.equal(quoteNever.aToB, false);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta0));
assert.ok(quoteNever.tickArray1.equals(ta5632));
assert.ok(quoteNever.tickArray2.equals(ta5632)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, false);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta0));
assert.ok(quoteAlways.tickArray1.equals(ta5632));
assert.ok(quoteAlways.tickArray2.equals(taNeg5632)); // fallback
assert.ok(quoteAlways.supplementalTickArrays === undefined);
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
assert.equal(quoteSituational.aToB, false);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta0));
assert.ok(quoteSituational.tickArray1.equals(ta5632));
assert.ok(quoteSituational.tickArray2.equals(taNeg5632)); // fallback
assert.ok(quoteSituational.supplementalTickArrays === undefined);
// V1 instruction will be used because we can use tickArray2 as fallback
const tx = await whirlpool.swap(quoteAlways);
assert.ok(
tx
.compressIx(true)
.instructions.some(
(ix) =>
ix.programId.equals(ORCA_WHIRLPOOL_PROGRAM_ID) &&
ix.data.subarray(0, 8).equals(SWAP_V1_DISCRIMINATOR),
),
);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quoteAlways)).buildAndExecute(),
);
});
/**
* |-5632-----------|0-c1------------|5632------------|11264---c2------|
*/
it("b->a, on leftmost quoter, ta1 != ta2 (no room for fallback)", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 11 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(200_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = 12124; // arrayIndex: 2
assert.equal(quoteNever.aToB, false);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta0));
assert.ok(quoteNever.tickArray1.equals(ta5632));
assert.ok(quoteNever.tickArray2.equals(ta11264)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, false);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta0));
assert.ok(quoteAlways.tickArray1.equals(ta5632));
assert.ok(quoteAlways.tickArray2.equals(ta11264)); // no fallback tick array
assert.ok(quoteAlways.supplementalTickArrays?.length === 1);
assert.ok(quoteAlways.supplementalTickArrays[0].equals(taNeg5632)); // fallback in supplemental
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
assert.equal(quoteSituational.aToB, false);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta0));
assert.ok(quoteSituational.tickArray1.equals(ta5632));
assert.ok(quoteSituational.tickArray2.equals(ta11264)); // no fallback tick array
assert.ok(quoteSituational.supplementalTickArrays?.length === 1);
assert.ok(quoteSituational.supplementalTickArrays[0].equals(taNeg5632)); // fallback in supplemental
// V2 instruction will be used to use supplemental tick arrays
const tx = await whirlpool.swap(quoteAlways);
assert.ok(
tx
.compressIx(true)
.instructions.some(
(ix) =>
ix.programId.equals(ORCA_WHIRLPOOL_PROGRAM_ID) &&
ix.data.subarray(0, 8).equals(SWAP_V2_DISCRIMINATOR),
),
);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quoteAlways)).buildAndExecute(),
);
});
/**
* |-5632-----------|0-------c1------|5632---------c2-|11264-----------|
*/
it("b->a, not on leftmost quoter, ta1 = ta2", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTest({
ctx,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
// b
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 87 },
tickSpacing,
new BN(1),
),
],
});
const _taNeg11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-11264,
).publicKey;
const taNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
-5632,
).publicKey;
const ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
0,
).publicKey;
const ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
5632,
).publicKey;
const _ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpool.getAddress(),
11264,
).publicKey;
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(100_000_000);
const quoteNever = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Never,
);
const estimatedEndTickIndex = 8765; // arrayIndex: 1
assert.equal(quoteNever.aToB, false);
assert.equal(quoteNever.amountSpecifiedIsInput, true);
assert.equal(quoteNever.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteNever.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteNever.tickArray0.equals(ta0));
assert.ok(quoteNever.tickArray1.equals(ta5632));
assert.ok(quoteNever.tickArray2.equals(ta5632)); // no fallback tick array
assert.ok(quoteNever.supplementalTickArrays === undefined);
const quoteAlways = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
assert.equal(quoteAlways.aToB, false);
assert.equal(quoteAlways.amountSpecifiedIsInput, true);
assert.equal(quoteAlways.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteAlways.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteAlways.tickArray0.equals(ta0));
assert.ok(quoteAlways.tickArray1.equals(ta5632));
assert.ok(quoteAlways.tickArray2.equals(taNeg5632)); // fallback
assert.ok(quoteAlways.supplementalTickArrays === undefined);
const quoteSituational = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Situational,
);
// no fallback because it is not on the leftmost quoter
assert.equal(quoteSituational.aToB, false);
assert.equal(quoteSituational.amountSpecifiedIsInput, true);
assert.equal(quoteSituational.estimatedEndTickIndex, estimatedEndTickIndex);
assert.equal(quoteSituational.estimatedAmountIn.toString(), tradeAmount);
assert.ok(quoteSituational.tickArray0.equals(ta0));
assert.ok(quoteSituational.tickArray1.equals(ta5632));
assert.ok(quoteSituational.tickArray2.equals(ta5632)); // no fallback tick array
assert.ok(quoteSituational.supplementalTickArrays === undefined);
});
it("twoHopSwapQuoteFromSwapQuotes", async () => {
const tickSpacing64 = 64;
const aToB = false;
const aqConfig = getDefaultAquarium();
// Add a third token and account and a second pool
aqConfig.initFeeTierParams = [{ tickSpacing: tickSpacing64 }];
aqConfig.initMintParams.push({});
aqConfig.initTokenAccParams.push({ mintIndex: 2 });
aqConfig.initPoolParams = [
{
mintIndices: [0, 1],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
{
mintIndices: [1, 2],
tickSpacing: tickSpacing64,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(2816),
},
];
// Add tick arrays and positions
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 0,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: -444928,
arrayCount: 1,
aToB,
});
aqConfig.initTickArrayRangeParams.push({
poolIndex: 1,
startTickIndex: 439296,
arrayCount: 1,
aToB,
});
// pool1(b(2) -> a(1)) --> pool0(b(1) -> a(0)) (so pool0 has smaller liquidity)
aqConfig.initPositionParams.push({
poolIndex: 0,
fundParams: [
{
liquidityAmount: new anchor.BN(4_100_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
aqConfig.initPositionParams.push({
poolIndex: 1,
fundParams: [
{
liquidityAmount: new anchor.BN(10_000_000),
tickLowerIndex: -443584,
tickUpperIndex: 443584,
},
],
});
const aquarium = (await buildTestAquariums(ctx, [aqConfig]))[0];
const poolInit0 = aquarium.pools[0];
const poolInit1 = aquarium.pools[1];
const pool0 = await client.getPool(
poolInit0.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
const pool1 = await client.getPool(
poolInit1.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
// quote1: in 8731861 out 3740488 end tick 14080
// quote0: in 3740488 out 1571989 end tick 14462
const quote1 = await swapQuoteByInputToken(
pool1,
pool1.getData().tokenMintB,
new BN(8731861),
Percentage.fromFraction(0, 100),
ORCA_WHIRLPOOL_PROGRAM_ID,
ctx.fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
const quote0 = await swapQuoteByInputToken(
pool0,
pool0.getData().tokenMintB,
quote1.estimatedAmountOut,
Percentage.fromFraction(0, 100),
ORCA_WHIRLPOOL_PROGRAM_ID,
ctx.fetcher,
IGNORE_CACHE,
UseFallbackTickArray.Always,
);
const pool0TaNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool0.getAddress(),
-5632,
).publicKey;
const pool0Ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool0.getAddress(),
0,
).publicKey;
const pool0Ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool0.getAddress(),
5632,
).publicKey;
const pool0Ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool0.getAddress(),
11264,
).publicKey;
const pool1TaNeg5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool1.getAddress(),
-5632,
).publicKey;
const pool1Ta0 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool1.getAddress(),
0,
).publicKey;
const pool1Ta5632 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool1.getAddress(),
5632,
).publicKey;
const pool1Ta11264 = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
pool1.getAddress(),
11264,
).publicKey;
assert.ok(quote1.tickArray0.equals(pool1Ta0));
assert.ok(quote1.tickArray1.equals(pool1Ta5632));
assert.ok(quote1.tickArray2.equals(pool1Ta11264)); // no room for fallback
assert.ok(quote1.supplementalTickArrays?.length === 1);
assert.ok(quote1.supplementalTickArrays[0].equals(pool1TaNeg5632)); // fallback in supplemental
assert.ok(quote0.tickArray0.equals(pool0Ta0));
assert.ok(quote0.tickArray1.equals(pool0Ta5632));
assert.ok(quote0.tickArray2.equals(pool0Ta11264)); // no room for fallback
assert.ok(quote0.supplementalTickArrays?.length === 1);
assert.ok(quote0.supplementalTickArrays[0].equals(pool0TaNeg5632)); // fallback in supplemental
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quote1, quote0);
// verify if the twoHopQuote has supplemental tick arrays
assert.ok(twoHopQuote.supplementalTickArraysOne?.length === 1);
assert.ok(twoHopQuote.supplementalTickArraysOne[0].equals(pool1TaNeg5632));
assert.ok(twoHopQuote.supplementalTickArraysTwo?.length === 1);
assert.ok(twoHopQuote.supplementalTickArraysTwo[0].equals(pool0TaNeg5632));
const params: TwoHopSwapV2Params = {
...twoHopQuote,
tokenAuthority: ctx.wallet.publicKey,
whirlpoolOne: pool1.getAddress(),
whirlpoolTwo: pool0.getAddress(),
oracleOne: PDAUtil.getOracle(ctx.program.programId, pool1.getAddress())
.publicKey,
oracleTwo: PDAUtil.getOracle(ctx.program.programId, pool0.getAddress())
.publicKey,
tokenProgramInput: TOKEN_PROGRAM_ID,
tokenProgramIntermediate: TOKEN_PROGRAM_ID,
tokenProgramOutput: TOKEN_PROGRAM_ID,
tokenMintInput: pool1.getData().tokenMintB,
tokenMintIntermediate: pool1.getData().tokenMintA,
tokenMintOutput: pool0.getData().tokenMintA,
tokenVaultOneInput: pool1.getData().tokenVaultB,
tokenVaultOneIntermediate: pool1.getData().tokenVaultA,
tokenVaultTwoIntermediate: pool0.getData().tokenVaultB,
tokenVaultTwoOutput: pool0.getData().tokenVaultA,
tokenOwnerAccountInput: aquarium.tokenAccounts[2].account,
tokenOwnerAccountOutput: aquarium.tokenAccounts[0].account,
};
// verify if the params has supplemental tick arrays
assert.ok(params.supplementalTickArraysOne?.length === 1);
assert.ok(params.supplementalTickArraysOne[0].equals(pool1TaNeg5632));
assert.ok(params.supplementalTickArraysTwo?.length === 1);
assert.ok(params.supplementalTickArraysTwo[0].equals(pool0TaNeg5632));
// execute twoHopSwapV2 with supplemental tick arrays
assert.ok(
(await pool1.refreshData()).tickCurrentIndex !==
quote1.estimatedEndTickIndex,
);
assert.ok(
(await pool0.refreshData()).tickCurrentIndex !==
quote0.estimatedEndTickIndex,
);
const tx = toTx(ctx, WhirlpoolIx.twoHopSwapV2Ix(ctx.program, params));
await assert.doesNotReject(async () => await tx.buildAndExecute());
assert.ok(
(await pool1.refreshData()).tickCurrentIndex ===
quote1.estimatedEndTickIndex,
);
assert.ok(
(await pool0.refreshData()).tickCurrentIndex ===
quote0.estimatedEndTickIndex,
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/swap-edge-case.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import {
PriceMath,
WhirlpoolContext,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteByOutputToken,
} from "../../../../src";
import { IGNORE_CACHE } from "../../../../src/network/public/fetcher";
import { defaultConfirmOptions } from "../../../utils/const";
import { NATIVE_MINT } from "@solana/spl-token";
import { WhirlpoolTestFixture } from "../../../utils/fixture";
import { SystemInstruction } from "@solana/web3.js";
import { SwapUtils } from "../../../../dist/utils/public/swap-utils";
describe("swap edge case test", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
describe("SOL Wrapping", () => {
async function buildTestFixture() {
const tickSpacing = 64;
const tickInitialIndex = -1988;
const tickUpperIndex = -64;
const tickLowerIndex = -3904;
const liquidityAmount = new BN(100000000000);
return new WhirlpoolTestFixture(ctx).init({
tokenAIsNative: true, // build pool which is similar to SOL/mSOL
initialSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(tickInitialIndex),
tickSpacing,
positions: [
{ tickLowerIndex, tickUpperIndex, liquidityAmount }, // In range position
],
});
}
it("ExactIn, SOL is input token", async () => {
const fixture = await buildTestFixture();
const poolInitInfo = fixture.getInfos().poolInitInfo;
const pool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(pool.getData().tokenMintA.equals(NATIVE_MINT));
const quote = await swapQuoteByInputToken(
pool,
pool.getData().tokenMintA, // SOL(tokenMintA) will be input
new BN(1_000_000_000), // 1 SOL (required input is obvilously 1 SOL + rent)
Percentage.fromFraction(0, 1000),
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
// ExactIn
assert.ok(quote.amountSpecifiedIsInput === true);
assert.ok(quote.aToB);
// The value of mSOL > The value of SOL
assert.ok(quote.amount.eq(new BN(1_000_000_000))); // 1 SOL
assert.ok(quote.otherAmountThreshold.lt(new BN(900_000_000))); // < 0.9 mSOL
const tx = await pool.swap(quote);
// check wrapping instruction
const createAccountIx = tx.compressIx(true).instructions[0];
const decoded = SystemInstruction.decodeCreateAccount(createAccountIx);
const tokenAccountRent = await fetcher.getAccountRentExempt(true);
const lamportsExpected = quote.amount.addn(tokenAccountRent);
assert.ok(lamportsExpected.eq(new BN(decoded.lamports)));
await tx.buildAndExecute();
});
it("ExactOut, SOL is input token", async () => {
const fixture = await buildTestFixture();
const poolInitInfo = fixture.getInfos().poolInitInfo;
const pool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(pool.getData().tokenMintA.equals(NATIVE_MINT));
const quote = await swapQuoteByOutputToken(
pool,
pool.getData().tokenMintB, // SOL(tokenMintA) will be input
new BN(1_000_000_000), // 1 mSOL (required input is obvilously larger than 1 SOL)
Percentage.fromFraction(0, 1000),
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
// ExactOut
assert.ok(quote.amountSpecifiedIsInput === false);
assert.ok(quote.aToB);
// If WSOL amount is 1 WSOL, swap should be failed
assert.ok(quote.amount.eq(new BN(1_000_000_000))); // 1 mSOL
assert.ok(quote.otherAmountThreshold.gt(new BN(1_100_000_000))); // > 1.1 SOL
const tx = await pool.swap(quote);
// check wrapping instruction
const createAccountIx = tx.compressIx(true).instructions[0];
const decoded = SystemInstruction.decodeCreateAccount(createAccountIx);
const tokenAccountRent = await fetcher.getAccountRentExempt(true);
const lamportsExpected =
quote.otherAmountThreshold.addn(tokenAccountRent);
assert.ok(lamportsExpected.eq(new BN(decoded.lamports)));
await tx.buildAndExecute();
});
it("[Fail] ExactOut, SOL is input token, otherAmountThreshold is default value (U64_MAX)", async () => {
const fixture = await buildTestFixture();
const poolInitInfo = fixture.getInfos().poolInitInfo;
const pool = await client.getPool(
poolInitInfo.whirlpoolPda.publicKey,
IGNORE_CACHE,
);
assert.ok(pool.getData().tokenMintA.equals(NATIVE_MINT));
const quote = await swapQuoteByOutputToken(
pool,
pool.getData().tokenMintB, // SOL(tokenMintA) will be input
new BN(1_000_000_000), // 1 mSOL (required input is obvilously larger than 1 SOL)
Percentage.fromFraction(0, 1000),
ctx.program.programId,
ctx.fetcher,
IGNORE_CACHE,
);
// ExactOut
assert.ok(quote.amountSpecifiedIsInput === false);
assert.ok(quote.aToB);
// If WSOL amount is 1 WSOL, swap should be failed
assert.ok(quote.amount.eq(new BN(1_000_000_000))); // 1 mSOL
assert.ok(quote.otherAmountThreshold.gt(new BN(1_100_000_000))); // > 1.1 SOL
await assert.rejects(
pool.swap({
...quote,
// use default otherAmountThreshold (U64_MAX)
otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(
quote.amountSpecifiedIsInput,
),
}),
/Wrapping U64_MAX amount of SOL is not possible/,
);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/v2/swap-array.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { AddressUtil, Percentage, ZERO } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import {
PriceMath,
SwapUtils,
TICK_ARRAY_SIZE,
WhirlpoolContext,
buildWhirlpoolClient,
swapQuoteByInputToken,
swapQuoteWithParams,
} from "../../../../../src";
import type { WhirlpoolsError } from "../../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../../src/errors/errors";
import { IGNORE_CACHE } from "../../../../../src/network/public/fetcher";
import { adjustForSlippage } from "../../../../../src/utils/position-util";
import { TickSpacing } from "../../../../utils";
import { defaultConfirmOptions } from "../../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
} from "../../../../utils/swap-test-utils";
import { setupSwapTestV2 } from "../../../../utils/v2/swap-test-utils-v2";
import { getTickArrays } from "../../../../utils/testDataTypes";
import { TokenExtensionUtil } from "../../../../../src/utils/public/token-extension-util";
import type { TokenTrait } from "../../../../utils/v2/init-utils-v2";
describe("swap arrays test (v2)", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}`, () => {
/**
* |--------------------|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("3 sequential arrays, 2nd array not initialized, use tickArray0 only, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 8446 (arrayIndex: 1)
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |--------------------|xxxxxxxxxxxxxc2xx|------c1-----------|
*/
it("3 sequential arrays, 2nd array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(40_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 4091 (arrayIndex: 0 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 4091);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc2xx|xxxxxxxxxxxxxxxxx|------c1-----------|
*/
it("3 sequential arrays, 2nd and 3rd array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -4522 (arrayIndex: -1 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, -4522);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc2xx|xxxxxxxxxxxxxxxxx|xxxxxxc1xxxxxxxxxxx|
*/
it("3 sequential arrays, all array not initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -4522 (arrayIndex: -1 (not initialized))
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(quote.estimatedEndTickIndex, -4522);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|-------------------|
*/
it("3 sequential arrays, 2nd array not initialized, use tickArray0 only, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -2816 (arrayIndex: -1)
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |-------------c1-----|xxc2xxxxxxxxxxxxx|-------------------|
*/
it("3 sequential arrays, 2nd array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(40_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 556 (arrayIndex: 0 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 556);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |-------------c1-----|xxxxxxxxxxxxxxxxx|xxc2xxxxxxxxxxxxx|
*/
it("3 sequential arrays, 2nd and 3rd array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 7662 (arrayIndex: 1 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 7662);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxc1xxxxx|xxxxxxxxxxxxxxxxx|xxc2xxxxxxxxxxxxx|
*/
it("3 sequential arrays, all array not initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
// SparseSwap makes it possible to execute this swap.
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(150_000_000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 7662 (arrayIndex: 1 (not initialized))
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(quote.estimatedEndTickIndex, 7662);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
await assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
const updatedWhirlpoolData = await whirlpool.refreshData();
assert.equal(
updatedWhirlpoolData.tickCurrentIndex,
quote.estimatedEndTickIndex,
);
});
/**
* |xxxxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("3 sequential arrays, 2nd array and 3rd array not initialized, use tickArray0 only, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is 8446 (arrayIndex: 1)
assert.equal(quote.aToB, true);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(true).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxxxx|
*/
it("3 sequential arrays, 2nd array and 3rd array not initialized, use tickArray0 only, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
tradeAmount,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
// Verify with an actual swap.
// estimatedEndTickIndex is -2816 (arrayIndex: -1)
assert.equal(quote.aToB, false);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(false).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* c1|------------------|-----------------|-------------------|
*/
it("3 sequential arrays does not contain curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|-----------------|-------------------|c1
*/
it("3 sequential arrays does not contain curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.getData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|------c1---------|-------------------|
*/
it("3 sequential arrays, 2nd array contains curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |--------------------|------c1---------|-------------------|
*/
it("3 sequential arrays, 2nd array contains curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264, 16896],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 10 },
tickSpacing,
),
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.TickArraySequenceInvalid,
);
});
/**
* |---a-c2--(5632)-----|------(0)--------|---c1--(11264)--a-|
*/
it("on first array, 2nd array is not sequential, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await getTickArrays(
[11264, 0, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorCodeMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
const messageMatch =
whirlErr.message.indexOf("TickArray at index 1 is unexpected") >=
0;
return errorCodeMatch && messageMatch;
},
);
});
/**
* |-a--(-11264)---c1---|--------(0)------|----(-5632)---c2--a-|
*/
it("on first array, 2nd array is not sequential, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -2, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: -1, offsetIndex: TICK_ARRAY_SIZE - 2 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await getTickArrays(
[-11264, 0, -5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorCodeMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
const messageMatch =
whirlErr.message.indexOf("TickArray at index 1 is unexpected") >=
0;
return errorCodeMatch && messageMatch;
},
);
});
/**
* |-------(5632)------|-------(5632)------|---c2--(5632)-c1---|
*/
it("3 identical arrays, 1st contains curr_tick_index, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [5632],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await getTickArrays(
[5632, 5632, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
const tradeAmount = new BN("33588");
const quote = swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: tradeAmount,
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
);
// Verify with an actual swap.
assert.equal(quote.aToB, aToB);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(aToB).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |---c1--(5632)-c2---|-------(5632)------|-------(5632)------|
*/
it("3 identical arrays, 1st contains curr_tick_index, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 4 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [5632],
fundedPositions: [
buildPosition(
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await getTickArrays(
[5632, 5632, 5632],
ctx,
AddressUtil.toPubKey(whirlpool.getAddress()),
fetcher,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
const tradeAmount = new BN("33588");
const quote = swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: tradeAmount,
whirlpoolData,
tickArrays,
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
otherAmountThreshold: ZERO,
tokenExtensionCtx,
},
slippageTolerance,
);
// Verify with an actual swap.
assert.equal(quote.aToB, aToB);
assert.equal(quote.amountSpecifiedIsInput, true);
assert.equal(
quote.sqrtPriceLimit.toString(),
SwapUtils.getDefaultSqrtPriceLimit(aToB).toString(),
);
assert.equal(
quote.otherAmountThreshold.toString(),
adjustForSlippage(
quote.estimatedAmountOut,
slippageTolerance,
false,
).toString(),
);
assert.equal(quote.estimatedAmountIn.toString(), tradeAmount);
assert.doesNotReject(
async () => await (await whirlpool.swap(quote)).buildAndExecute(),
);
});
/**
* |xxxxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxx|-c2---c1-----------|
*/
it("Whirlpool.swap with uninitialized TickArrays, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const aToB = true;
const tickArrays = SwapUtils.getTickArrayPublicKeys(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
);
// SparseSwap makes it possible to execute this swap.
await assert.doesNotReject(
whirlpool.swap({
amount: tradeAmount,
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArray0: tickArrays[0],
tickArray1: tickArrays[1], // uninitialized TickArray is acceptable
tickArray2: tickArrays[2], // uninitialized TickArray is acceptable
}),
);
});
/**
* |-------------c1--c2-|xxxxxxxxxxxxxxxxx|xxxxxxxxxxxxxxxxxxx|
*/
it("Whirlpool.swap with uninitialized TickArrays, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 44 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const tradeAmount = new BN(10000);
const aToB = false;
const tickArrays = SwapUtils.getTickArrayPublicKeys(
whirlpoolData.tickCurrentIndex,
whirlpoolData.tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
);
// SparseSwap makes it possible to execute this swap.
await assert.doesNotReject(
whirlpool.swap({
amount: tradeAmount,
amountSpecifiedIsInput: true,
aToB,
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),
tickArray0: tickArrays[0],
tickArray1: tickArrays[1], // uninitialized TickArray is acceptable
tickArray2: tickArrays[2], // uninitialized TickArray is acceptable
}),
);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/swap/v2/swap-traverse.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Percentage } from "@orca-so/common-sdk";
import * as assert from "assert";
import BN from "bn.js";
import {
buildWhirlpoolClient,
MAX_SQRT_PRICE,
MAX_TICK_INDEX,
MIN_SQRT_PRICE,
MIN_TICK_INDEX,
PriceMath,
swapQuoteByInputToken,
swapQuoteByOutputToken,
swapQuoteWithParams,
SwapUtils,
TICK_ARRAY_SIZE,
WhirlpoolContext,
} from "../../../../../src";
import type { WhirlpoolsError } from "../../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../../src/errors/errors";
import { IGNORE_CACHE } from "../../../../../src/network/public/fetcher";
import {
assertInputOutputQuoteEqual,
assertQuoteAndResults,
TickSpacing,
} from "../../../../utils";
import { defaultConfirmOptions } from "../../../../utils/const";
import {
arrayTickIndexToTickIndex,
buildPosition,
} from "../../../../utils/swap-test-utils";
import { setupSwapTestV2 } from "../../../../utils/v2/swap-test-utils-v2";
import { getVaultAmounts } from "../../../../utils/whirlpools-test-utils";
import { TokenExtensionUtil } from "../../../../../src/utils/public/token-extension-util";
import type { TokenTrait } from "../../../../utils/v2/init-utils-v2";
describe("swap traversal tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
const client = buildWhirlpoolClient(ctx);
const tickSpacing = TickSpacing.SixtyFour;
const slippageTolerance = Percentage.fromFraction(0, 100);
const tokenTraitVariations: {
tokenTraitA: TokenTrait;
tokenTraitB: TokenTrait;
}[] = [
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
},
{
tokenTraitA: { isToken2022: false },
tokenTraitB: { isToken2022: true },
},
{
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: true },
},
];
tokenTraitVariations.forEach((tokenTraits) => {
describe(`tokenTraitA: ${
tokenTraits.tokenTraitA.isToken2022 ? "Token2022" : "Token"
}, tokenTraitB: ${
tokenTraits.tokenTraitB.isToken2022 ? "Token2022" : "Token"
}`, () => {
/**
* |--------------------|b-----x2----a-------b-|x1-a------------------|
*/
it("curr_index on the last initializable tick, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 15 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 44 },
{ arrayIndex: 0, offsetIndex: 30 },
tickSpacing,
new BN(250_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 0 },
{ arrayIndex: -1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(150000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------------------x1,a|-b--------a----x2---b-|-------------------|
*/
it("curr_index on the last initializable tick, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 1, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(190000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* b|-----x2---------|a---------------|a,x1-------------b|
*/
it("curr_index on the first initializable tick, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -2, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* b|a,x1--------------|a---------------|---------x2--------b|
*/
it("curr_index on the first initializable tick, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: 0 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(450000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------b-----x1-a|------a---x2---b--|-------------------|
*/
it("curr_index on the 2nd last initialized tick, with the next tick initialized, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 2 }, // 5504
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(150000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----------b--x2--|-------a-----b-----|a-x1-------------|
*/
it("curr_index on the 2nd initialized tick, with the first tick initialized, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 1 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(75000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |--------b-----a-x1|a---------x2---b--|-------------------|
*/
it("curr_index btw end of last offset and next array, with the next tick initialized, b->a", async () => {
const currIndex = 5629;
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 0, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 1, offsetIndex: 1 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 4 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(15000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----------b--x2--|-------a-----b-----|x1,a-------------|
*/
it("curr_index btw end of last offset and next array, with the next tick initialized, a->b", async () => {
const currIndex = 11264 + 30;
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 0, offsetIndex: 44 },
{ arrayIndex: 1, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(7500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |----------------|-----a----x2-----b|--------x1----a---b----|
*/
it("on some tick, traverse to the 1st initialized tick in the next tick-array, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 2, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 1, offsetIndex: 44 },
{ arrayIndex: 2, offsetIndex: 44 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: 1, offsetIndex: TICK_ARRAY_SIZE - 1 },
{ arrayIndex: 2, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(45000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |----a--b---x1------|a---x2-----b-------|------------------|
*/
it("on some tick, traverse to the 1st initialized tick in the next tick-array, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 64 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 0, offsetIndex: 0 },
tickSpacing,
new BN(250_000_000),
),
buildPosition(
//b
{ arrayIndex: -1, offsetIndex: 22 },
{ arrayIndex: 0, offsetIndex: 64 },
tickSpacing,
new BN(350_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(49500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-------a----x2------|-----------------|----x1-----a-------|
*/
it("on some tick, traverse to the next tick in the n+2 tick-array, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-------a------x1----|-----------------|-----x2--------a---|
*/
it("on some tick, traverse to the next tick in the n+2 tick-array, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-5632, 0, 5632],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* a|----------------|-----------------|-------x1--------|a
*/
it("3 arrays, on some initialized tick, no other initialized tick in the sequence, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(119500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* |-----x1-------------|-----------------|-------------------|
*/
it("3 arrays, on some initialized tick, no other initialized tick in the sequence, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* [1, 0, -1]
* e|---c--x2----a---d----b|f-----a--b----d----|f-----c---x1-------|e
*/
it("3 arrays, on some uninitialized tick, traverse lots of ticks, a->b", async () => {
const currIndex =
arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 25 },
tickSpacing,
) - 30;
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// e
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000),
),
buildPosition(
// c
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 15 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 30 },
{ arrayIndex: 0, offsetIndex: 20 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// d
{ arrayIndex: -1, offsetIndex: 60 },
{ arrayIndex: 0, offsetIndex: 60 },
tickSpacing,
new BN(50_000_000),
),
buildPosition(
// f
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(25_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(102195000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintB,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* e|---c--x1----a---d--b---|f-----a--b----d----|f------c---x2--------|e
*/
it("3 arrays, on some uninitialized tick, traverse lots of ticks, b->a", async () => {
const currIndex =
arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 15 },
tickSpacing,
) - 30;
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// e
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000),
),
buildPosition(
// c
{ arrayIndex: -1, offsetIndex: 10 },
{ arrayIndex: 1, offsetIndex: 15 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// a
{ arrayIndex: -1, offsetIndex: 30 },
{ arrayIndex: 0, offsetIndex: 20 },
tickSpacing,
new BN(100_000_000),
),
buildPosition(
// d
{ arrayIndex: -1, offsetIndex: 60 },
{ arrayIndex: 0, offsetIndex: 60 },
tickSpacing,
new BN(50_000_000),
),
buildPosition(
// f
{ arrayIndex: 0, offsetIndex: 0 },
{ arrayIndex: 1, offsetIndex: 0 },
tickSpacing,
new BN(25_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(99900000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* trade amount > liquidity
* |----------x1----------|-----------------|-------------------|
*/
it("3 arrays, trade amount exceeds liquidity available in array sequence, b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
await assert.rejects(
async () =>
await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(9159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
// Message contains failure on finding beyond tickIndex
const messageMatch = whirlErr.message.indexOf("11264") >= 0;
assert.ok(messageMatch, "Error Message must match condition.");
assert.ok(errorMatch, "Error Code must match condition.");
return true;
},
);
});
/**
* trade amount > liquidity
* |--------------------|-----------------|---------x1----------|
*/
it("3 arrays, trade amount exceeds liquidity available in array sequence, a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
await assert.rejects(
async () =>
await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN(9159500000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
),
(err) => {
const whirlErr = err as WhirlpoolsError;
const errorMatch =
whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
// Message contains failure on finding beyond tickIndex
const messageMatch = whirlErr.message.indexOf("-5696") >= 0;
assert.ok(messageMatch, "Error Message must match condition.");
assert.ok(errorMatch, "Error Code must match condition.");
return true;
},
);
});
/**
* |a--------x1----------a| Max
*/
it("on the last tick-array, traverse to the MAX_TICK_INDEX tick", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 78, offsetIndex: 22 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [MAX_TICK_INDEX],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: 78, offsetIndex: 0 }, // 439,296
{ arrayIndex: 78, offsetIndex: 67 }, // 443,584
tickSpacing,
new BN(250),
),
],
tokenMintAmount: new BN("95000000000000000"),
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN("12595000000000"),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await (await whirlpool.swap(quote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
quote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* Min |a--------x2--------a----|-----------------|-------------------|
*/
it("on the first tick-array, traverse to the MIN_TICK_INDEX tick", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -79, offsetIndex: 22 },
tickSpacing,
);
const aToB = true;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [MIN_TICK_INDEX],
fundedPositions: [
buildPosition(
// a -444,928
{ arrayIndex: -79, offsetIndex: 21 },
{ arrayIndex: -79, offsetIndex: TICK_ARRAY_SIZE - 1 },
tickSpacing,
new BN(250),
),
],
tokenMintAmount: new BN("95000000000000000"),
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const quote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintA,
new BN("12595000000000"),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
await (await whirlpool.swap(quote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
quote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|-------x1-|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -tickSpacing, shifted", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 87 },
tickSpacing,
);
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|--------x1|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -1, shifted", async () => {
const currIndex = -1;
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* -5632 0 5632 11264
* |-a--------|XXXXXXXXx1|----------|----------|-x2-----a-|
* ta0 ta1 ta2
*/
it("b->a, tickCurrentIndex = -1, tickCurrentIndex on uninitialized TickArray, shifted", async () => {
const currIndex = -1;
const aToB = false;
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 80 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const beforeVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
const inputTokenQuote = await swapQuoteByInputToken(
whirlpool,
whirlpoolData.tokenMintB,
new BN(200000000),
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
const ta2StartTickIndex = 11264;
assert.ok(inputTokenQuote.estimatedEndTickIndex > ta2StartTickIndex); // traverse ta0, ta1, and ta2
const outputTokenQuote = await swapQuoteByOutputToken(
whirlpool,
whirlpoolData.tokenMintA,
inputTokenQuote.estimatedAmountOut,
slippageTolerance,
ctx.program.programId,
fetcher,
IGNORE_CACHE,
);
assertInputOutputQuoteEqual(inputTokenQuote, outputTokenQuote);
await (await whirlpool.swap(inputTokenQuote)).buildAndExecute();
const newData = await whirlpool.refreshData();
const afterVaultAmounts = await getVaultAmounts(ctx, whirlpoolData);
assertQuoteAndResults(
aToB,
inputTokenQuote,
newData,
beforeVaultAmounts,
afterVaultAmounts,
);
});
/**
* sqrtPriceLimit < MIN_SQRT_PRICE
* |--------------------|-----------------|---------x1----------|
*/
it("3 arrays, sqrtPriceLimit is out of bounds (< MIN_SQRT_PRICE), a->b", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: 1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = true;
const tickArrays = await SwapUtils.getTickArrays(
currIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: new BN(MIN_SQRT_PRICE).subn(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.SqrtPriceOutOfBounds,
);
});
/**
* sqrtPriceLimit > MAX_SQRT_PRICE
* |-----x1-------------|-----------------|---------------------|
*/
it("3 arrays, sqrtPriceLimit is out of bounds (> MAX_SQRT_PRICE), b->a", async () => {
const currIndex = arrayTickIndexToTickIndex(
{ arrayIndex: -1, offsetIndex: 22 },
tickSpacing,
);
const whirlpool = await setupSwapTestV2({
ctx,
...tokenTraits,
client,
tickSpacing,
initSqrtPrice: PriceMath.tickIndexToSqrtPriceX64(currIndex),
initArrayStartTicks: [-11264, -5632, 0, 5632, 11264],
fundedPositions: [
buildPosition(
// a
{ arrayIndex: -2, offsetIndex: 10 },
{ arrayIndex: 2, offsetIndex: 23 },
tickSpacing,
new BN(250_000_000),
),
],
});
const whirlpoolData = await whirlpool.refreshData();
const aToB = false;
const tickArrays = await SwapUtils.getTickArrays(
currIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpool.getAddress(),
fetcher,
IGNORE_CACHE,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData,
IGNORE_CACHE,
);
assert.throws(
() =>
swapQuoteWithParams(
{
aToB,
amountSpecifiedIsInput: true,
tokenAmount: new BN("10000"),
whirlpoolData,
tickArrays,
sqrtPriceLimit: new BN(MAX_SQRT_PRICE).addn(1),
otherAmountThreshold:
SwapUtils.getDefaultOtherAmountThreshold(true),
tokenExtensionCtx,
},
slippageTolerance,
),
(err) =>
(err as WhirlpoolsError).errorCode ===
SwapErrorCode.SqrtPriceOutOfBounds,
);
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/position-util.test.ts
|
import * as assert from "assert";
import { PriceMath } from "../../../../src";
import {
PositionStatus,
PositionUtil,
} from "../../../../src/utils/position-util";
describe("PositionUtil tests", () => {
const tickLowerIndex = 64;
const tickUpperIndex = 128;
describe("getPositionStatus", () => {
it("tickCurrentIndex < tickLowerIndex, BelowRange", async () => {
const tickCurrentIndex = 0;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.BelowRange);
});
it("tickCurrentIndex + 1 == tickLowerIndex, BelowRange", async () => {
const tickCurrentIndex = tickLowerIndex - 1;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.BelowRange);
});
it("tickCurrentIndex == tickLowerIndex, InRange", async () => {
const tickCurrentIndex = tickLowerIndex;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.InRange);
});
it("tickCurrentIndex + 1 == tickUpperIndex, InRange", async () => {
const tickCurrentIndex = tickUpperIndex - 1;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.InRange);
});
it("tickCurrentIndex == tickUpperIndex, AboveRange", async () => {
const tickCurrentIndex = tickUpperIndex;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.AboveRange);
});
it("tickCurrentIndex > tickUpperIndex, AboveRange", async () => {
const tickCurrentIndex = 192;
const result = PositionUtil.getPositionStatus(
tickCurrentIndex,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.AboveRange);
});
});
describe("getStrictPositionStatus", async () => {
it("sqrtPrice < toSqrtPrice(tickLowerIndex), BelowRange", async () => {
const sqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(0);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.BelowRange);
});
it("sqrtPrice + 1 == toSqrtPrice(tickLowerIndex), BelowRange", async () => {
const sqrtPriceX64 =
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex).subn(1);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.BelowRange);
});
it("sqrtPrice == toSqrtPrice(tickLowerIndex), BelowRange", async () => {
const sqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.BelowRange);
});
it("sqrtPrice - 1 == toSqrtPrice(tickLowerIndex), InRange", async () => {
const sqrtPriceX64 =
PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex).addn(1);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.InRange);
});
it("sqrtPrice + 1 == toSqrtPrice(tickUpperIndex), InRange", async () => {
const sqrtPriceX64 =
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex).subn(1);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.InRange);
});
it("sqrtPrice == toSqrtPrice(tickUpperIndex), AboveRange", async () => {
const sqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.AboveRange);
});
it("sqrtPrice - 1 == toSqrtPrice(tickUpperIndex), AboveRange", async () => {
const sqrtPriceX64 =
PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex).addn(1);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.AboveRange);
});
it("sqrtPrice > toSqrtPrice(tickUpperIndex), AboveRange", async () => {
const sqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(192);
const result = PositionUtil.getStrictPositionStatus(
sqrtPriceX64,
tickLowerIndex,
tickUpperIndex,
);
assert.equal(result, PositionStatus.AboveRange);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/position-bundle-util.test.ts
|
import * as assert from "assert";
import { PositionBundleUtil, POSITION_BUNDLE_SIZE } from "../../../../src";
import { buildPositionBundleData } from "../../../utils/testDataTypes";
describe("PositionBundleUtil tests", () => {
const occupiedEmpty: number[] = [];
const occupiedPartial: number[] = [0, 1, 5, 49, 128, 193, 255];
const occupiedFull: number[] = new Array(POSITION_BUNDLE_SIZE)
.fill(0)
.map((a, i) => i);
describe("checkBundleIndexInBounds", () => {
it("valid bundle indexes", async () => {
for (
let bundleIndex = 0;
bundleIndex < POSITION_BUNDLE_SIZE;
bundleIndex++
) {
assert.ok(PositionBundleUtil.checkBundleIndexInBounds(bundleIndex));
}
});
it("less than zero", async () => {
assert.ok(!PositionBundleUtil.checkBundleIndexInBounds(-1));
});
it("greater than or equal to POSITION_BUNDLE_SIZE", async () => {
assert.ok(
!PositionBundleUtil.checkBundleIndexInBounds(POSITION_BUNDLE_SIZE),
);
assert.ok(
!PositionBundleUtil.checkBundleIndexInBounds(POSITION_BUNDLE_SIZE + 1),
);
});
});
it("isOccupied / isUnoccupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
for (
let bundleIndex = 0;
bundleIndex < POSITION_BUNDLE_SIZE;
bundleIndex++
) {
if (occupiedPartial.includes(bundleIndex)) {
assert.ok(PositionBundleUtil.isOccupied(positionBundle, bundleIndex));
assert.ok(
!PositionBundleUtil.isUnoccupied(positionBundle, bundleIndex),
);
} else {
assert.ok(PositionBundleUtil.isUnoccupied(positionBundle, bundleIndex));
assert.ok(!PositionBundleUtil.isOccupied(positionBundle, bundleIndex));
}
}
});
describe("isFull / isEmpty", () => {
it("empty", async () => {
const positionBundle = buildPositionBundleData(occupiedEmpty);
assert.ok(PositionBundleUtil.isEmpty(positionBundle));
assert.ok(!PositionBundleUtil.isFull(positionBundle));
});
it("some bundle indexes are occupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
assert.ok(!PositionBundleUtil.isEmpty(positionBundle));
assert.ok(!PositionBundleUtil.isFull(positionBundle));
});
it("full", async () => {
const positionBundle = buildPositionBundleData(occupiedFull);
assert.ok(!PositionBundleUtil.isEmpty(positionBundle));
assert.ok(PositionBundleUtil.isFull(positionBundle));
});
});
describe("getOccupiedBundleIndexes", () => {
it("empty", async () => {
const positionBundle = buildPositionBundleData(occupiedEmpty);
const result =
PositionBundleUtil.getOccupiedBundleIndexes(positionBundle);
assert.equal(result.length, 0);
});
it("some bundle indexes are occupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
const result =
PositionBundleUtil.getOccupiedBundleIndexes(positionBundle);
assert.equal(result.length, occupiedPartial.length);
assert.ok(occupiedPartial.every((index) => result.includes(index)));
});
it("full", async () => {
const positionBundle = buildPositionBundleData(occupiedFull);
const result =
PositionBundleUtil.getOccupiedBundleIndexes(positionBundle);
assert.equal(result.length, POSITION_BUNDLE_SIZE);
assert.ok(occupiedFull.every((index) => result.includes(index)));
});
});
describe("getUnoccupiedBundleIndexes", () => {
it("empty", async () => {
const positionBundle = buildPositionBundleData(occupiedEmpty);
const result =
PositionBundleUtil.getUnoccupiedBundleIndexes(positionBundle);
assert.equal(result.length, POSITION_BUNDLE_SIZE);
assert.ok(occupiedFull.every((index) => result.includes(index)));
});
it("some bundle indexes are occupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
const result =
PositionBundleUtil.getUnoccupiedBundleIndexes(positionBundle);
assert.equal(
result.length,
POSITION_BUNDLE_SIZE - occupiedPartial.length,
);
assert.ok(occupiedPartial.every((index) => !result.includes(index)));
});
it("full", async () => {
const positionBundle = buildPositionBundleData(occupiedFull);
const result =
PositionBundleUtil.getUnoccupiedBundleIndexes(positionBundle);
assert.equal(result.length, 0);
});
});
describe("findUnoccupiedBundleIndex", () => {
it("empty", async () => {
const positionBundle = buildPositionBundleData(occupiedEmpty);
const result =
PositionBundleUtil.findUnoccupiedBundleIndex(positionBundle);
assert.equal(result, 0);
});
it("some bundle indexes are occupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
const result =
PositionBundleUtil.findUnoccupiedBundleIndex(positionBundle);
assert.equal(result, 2);
});
it("full", async () => {
const positionBundle = buildPositionBundleData(occupiedFull);
const result =
PositionBundleUtil.findUnoccupiedBundleIndex(positionBundle);
assert.ok(result === null);
});
});
describe("convertBitmapToArray", () => {
it("empty", async () => {
const positionBundle = buildPositionBundleData(occupiedEmpty);
const result = PositionBundleUtil.convertBitmapToArray(positionBundle);
assert.equal(result.length, POSITION_BUNDLE_SIZE);
assert.ok(result.every((occupied) => !occupied));
});
it("some bundle indexes are occupied", async () => {
const positionBundle = buildPositionBundleData(occupiedPartial);
const result = PositionBundleUtil.convertBitmapToArray(positionBundle);
assert.equal(result.length, POSITION_BUNDLE_SIZE);
assert.ok(
result.every((occupied, i) => occupied === occupiedPartial.includes(i)),
);
});
it("full", async () => {
const positionBundle = buildPositionBundleData(occupiedFull);
const result = PositionBundleUtil.convertBitmapToArray(positionBundle);
assert.equal(result.length, POSITION_BUNDLE_SIZE);
assert.ok(result.every((occupied) => occupied));
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/price-math.test.ts
|
import { MathUtil, Percentage } from "@orca-so/common-sdk";
import assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import {
MAX_SQRT_PRICE_BN,
MAX_TICK_INDEX,
MIN_SQRT_PRICE_BN,
MIN_TICK_INDEX,
PriceMath,
} from "../../../../src";
function toSqrtPrice(n: number) {
return PriceMath.priceToSqrtPriceX64(new Decimal(n), 6, 6);
}
const EVAL_PRECISION = 16;
const variations = [
[MAX_SQRT_PRICE_BN, Percentage.fromFraction(0, 100), true] as const,
[MAX_SQRT_PRICE_BN, Percentage.fromFraction(1, 1000), true] as const,
[MAX_SQRT_PRICE_BN, Percentage.fromFraction(1, 100), true] as const,
[MIN_SQRT_PRICE_BN, Percentage.fromFraction(0, 1000), true] as const,
[MIN_SQRT_PRICE_BN, Percentage.fromFraction(1, 1000), true] as const,
[MIN_SQRT_PRICE_BN, Percentage.fromFraction(1, 100), true] as const,
[MIN_SQRT_PRICE_BN, Percentage.fromFraction(1, 100), true] as const,
[toSqrtPrice(5), Percentage.fromFraction(0, 1000), false] as const,
[toSqrtPrice(5), Percentage.fromFraction(1, 1000), false] as const,
[toSqrtPrice(5), Percentage.fromFraction(10, 1000), false] as const,
[toSqrtPrice(1000000), Percentage.fromFraction(0, 1000), false] as const,
[toSqrtPrice(1000000), Percentage.fromFraction(5, 1000), false] as const,
[toSqrtPrice(1000000), Percentage.fromFraction(20, 1000), false] as const,
[toSqrtPrice(61235.33), Percentage.fromFraction(0, 1000), false] as const,
[toSqrtPrice(61235.33), Percentage.fromFraction(5, 1000), false] as const,
[toSqrtPrice(61235.33), Percentage.fromFraction(20, 1000), false] as const,
];
function toPrecisionLevel(decimal: Decimal) {
return decimal.toSignificantDigits(EVAL_PRECISION);
}
variations.forEach(([sqrtPrice, slippage, ignorePrecisionVerification]) => {
describe("PriceMath - getSlippageBoundForSqrtPrice tests", () => {
it(`slippage boundary for sqrt price - ${sqrtPrice.toString()}, slippage - ${slippage
.toDecimal()
.mul(100)}%`, () => {
const { lowerBound, upperBound } = PriceMath.getSlippageBoundForSqrtPrice(
sqrtPrice,
slippage,
);
const price = PriceMath.sqrtPriceX64ToPrice(sqrtPrice, 6, 6);
const slippageDecimal = slippage.toDecimal();
const expectedUpperSlippagePrice = toPrecisionLevel(
price.mul(slippageDecimal.add(1)),
);
const expectedLowerSlippagePrice = toPrecisionLevel(
price.mul(new Decimal(1).sub(slippageDecimal)),
);
const expectedUpperSqrtPrice = BN.min(
BN.max(
MathUtil.toX64(expectedUpperSlippagePrice.sqrt()),
MIN_SQRT_PRICE_BN,
),
MAX_SQRT_PRICE_BN,
);
const expectedLowerSqrtPrice = BN.min(
BN.max(
MathUtil.toX64(expectedLowerSlippagePrice.sqrt()),
MIN_SQRT_PRICE_BN,
),
MAX_SQRT_PRICE_BN,
);
const expectedUpperTickIndex = PriceMath.sqrtPriceX64ToTickIndex(
expectedUpperSqrtPrice,
);
const expectedLowerTickIndex = PriceMath.sqrtPriceX64ToTickIndex(
expectedLowerSqrtPrice,
);
const lowerBoundSqrtPrice = lowerBound[0];
const lowerBoundTickIndex = lowerBound[1];
const lowerBoundPrice = toPrecisionLevel(
PriceMath.sqrtPriceX64ToPrice(lowerBoundSqrtPrice, 6, 6),
);
const upperBoundSqrtPrice = upperBound[0];
const upperBoundTickIndex = upperBound[1];
const upperBoundPrice = toPrecisionLevel(
PriceMath.sqrtPriceX64ToPrice(upperBoundSqrtPrice, 6, 6),
);
// For larger sqrt-price boundary values, it's difficult to verify exactly due to the precision loss.
// We will only verify that it won't crash and the upper and lower bounds are within the expected range by
// testing that the function won't crash.
if (!ignorePrecisionVerification) {
assert.ok(
lowerBoundPrice.eq(expectedLowerSlippagePrice),
`lower slippage price ${lowerBoundPrice.toString()} should equal ${expectedLowerSlippagePrice.toString()}`,
);
assert.ok(
upperBoundPrice.eq(expectedUpperSlippagePrice),
`upper slippage price ${upperBoundPrice.toString()} should equal ${expectedUpperSlippagePrice.toString()}`,
);
assert.ok(
expectedUpperTickIndex === upperBoundTickIndex,
`upper tick index ${upperBoundTickIndex} should equal ${expectedUpperTickIndex}`,
);
assert.ok(
expectedLowerTickIndex === lowerBoundTickIndex,
`lower tick index ${lowerBoundTickIndex} should equal ${expectedLowerTickIndex}`,
);
} else {
// Verify generally the conditions hold between sqrtPrices and tick indicies
assert.ok(
lowerBoundSqrtPrice.gte(MIN_SQRT_PRICE_BN) &&
lowerBoundSqrtPrice.lte(MAX_SQRT_PRICE_BN),
`lower bound sqrt price ${lowerBoundSqrtPrice.toString()} should be within bounds of MIN_SQRT_PRICE_BN & MAX_SQRT_PRICE_BN`,
);
assert.ok(
upperBoundSqrtPrice.gte(MIN_SQRT_PRICE_BN) &&
upperBoundSqrtPrice.lte(MAX_SQRT_PRICE_BN),
`lower bound sqrt price ${upperBoundSqrtPrice.toString()} should be within bounds of MIN_SQRT_PRICE_BN & MAX_SQRT_PRICE_BN`,
);
assert.ok(
lowerBoundTickIndex >= MIN_TICK_INDEX &&
lowerBoundTickIndex <= MAX_TICK_INDEX,
`lower bound tick index ${lowerBoundTickIndex} should be within bounds of MIN_TICK_INDEX & MAX_TICK_INDEX`,
);
assert.ok(
upperBoundTickIndex >= MIN_TICK_INDEX &&
upperBoundTickIndex <= MAX_TICK_INDEX,
`upper bound tick index ${upperBoundTickIndex} should be within bounds of MIN_TICK_INDEX & MAX_TICK_INDEX`,
);
}
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/pool-graph.test.ts
|
import type { Address } from "@coral-xyz/anchor";
import { AddressUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import type { Path, PathSearchEntries, PoolTokenPair } from "../../../../src";
import { PoolGraphBuilder, PoolGraphUtils } from "../../../../src";
import {
feeTierPoolsGraphData,
solConnectedPools,
uniqueTokenMintsGraphData,
uniqueTokenMintsGraphTokenUnsortedData,
usdcConnectedPools,
} from "../../../utils/graph-test-data";
const uniqueTokenPair = uniqueTokenMintsGraphData[0];
const uniqueTokenPairSorted = uniqueTokenMintsGraphData[0];
const rlbSolPool = solConnectedPools[0];
const mSolSolPool = solConnectedPools[1];
const dustSolPool = solConnectedPools[2];
const stSolSolPool = solConnectedPools[3];
const usdcSolPool = solConnectedPools[4];
const rlbUsdcPool = usdcConnectedPools[0];
const msolUsdcPool = usdcConnectedPools[1];
const dustUsdcPool = usdcConnectedPools[2];
const usdcMint: Address = feeTierPoolsGraphData[0].tokenMintB;
describe("PoolGraph tests", () => {
describe("getPathsForPairs", () => {
it("Path does not exist", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const uniqueTokenPair = uniqueTokenMintsGraphTokenUnsortedData[0];
const results = graph.getPathsForPairs([
[uniqueTokenPair.tokenMintA, uniqueTokenPair.tokenMintB],
]);
assert.equal(results.length, 1);
const searchId = PoolGraphUtils.getSearchPathId(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
assertGetPathsForPairsResult(results, [[searchId, []]]);
});
it("Path between the same token mint", async () => {
const testData = [...solConnectedPools, ...feeTierPoolsGraphData];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [[usdcMint, usdcMint]];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const searchId = PoolGraphUtils.getSearchPathId(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintA,
);
assertGetPathsForPairsResult(results, [[searchId, []]]);
});
it("1 path exist", async () => {
const testData = [...solConnectedPools, ...uniqueTokenMintsGraphData];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[uniqueTokenPair.tokenMintA, uniqueTokenPair.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[uniqueTokenPair]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("1 path exist - token ordering reversed", async () => {
const testData = [
...solConnectedPools,
...uniqueTokenMintsGraphTokenUnsortedData,
];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[uniqueTokenPair.tokenMintA, uniqueTokenPair.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[uniqueTokenPairSorted]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("1 path with 2 edges exist - verify edge ordering correct", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[rlbSolPool, mSolSolPool]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("1 path with 2 edges exist - verify edge ordering correct (reverse)", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[mSolSolPool.tokenMintB, rlbSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[mSolSolPool, rlbSolPool]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("1 tokenPair input to multiple paths exist - verify token order, edge ordering", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("duplicated token-pairs will still be executed and ordered in results", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 2);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
],
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[1][0],
searchTokenPairs[1][1],
),
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("same token-pairs but with reversed order has unique search ids", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
[mSolSolPool.tokenMintB, rlbSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 2);
// TODO: Directionality of the edges is not being considered
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
],
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[1][0],
searchTokenPairs[1][1],
),
[
[mSolSolPool, rlbSolPool],
[msolUsdcPool, rlbUsdcPool],
],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("only allow 2-edge paths that go through tokens from the intermediate token list ", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbUsdcPool.tokenMintB, msolUsdcPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs, {
intermediateTokens: [rlbUsdcPool.tokenMintA],
});
// Assert that the SOL paths are filtered out
assert.equal(results.length, 1);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[rlbUsdcPool, msolUsdcPool]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
it("multiple tokenPair input to multiple paths exist - verify token order, edge ordering", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[rlbSolPool.tokenMintB, mSolSolPool.tokenMintB],
[dustSolPool.tokenMintB, mSolSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 2);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
],
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[1][0],
searchTokenPairs[1][1],
),
[
[dustSolPool, mSolSolPool],
[dustUsdcPool, msolUsdcPool],
],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
});
describe("getPath", async () => {
it("Path does not exist", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
assert.equal(result.length, 0);
});
it("1 path exist", async () => {
const testData = [...solConnectedPools, ...uniqueTokenMintsGraphData];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
assertGetPathResult(
result,
[[uniqueTokenPair]],
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
});
it("1 path exist - token ordering reversed", async () => {
const testData = [
...solConnectedPools,
...uniqueTokenMintsGraphTokenUnsortedData,
];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
assertGetPathResult(
result,
[[uniqueTokenPairSorted]],
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
});
it("Path between the same token mint", async () => {
const testData = [...solConnectedPools, ...feeTierPoolsGraphData];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const results = graph.getPath(usdcMint, usdcMint);
assertGetPathResult(results, [], usdcMint, usdcMint);
});
it("1 path with 2 edges exist - verify edge ordering correct", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
rlbSolPool.tokenMintB,
mSolSolPool.tokenMintB,
);
assertGetPathResult(
result,
[[rlbSolPool, mSolSolPool]],
rlbSolPool.tokenMintB,
mSolSolPool.tokenMintB,
);
});
it("1 path with 2 edges exist - verify edge ordering correct (reverse)", async () => {
const testData = [...solConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
mSolSolPool.tokenMintB,
rlbSolPool.tokenMintB,
);
assertGetPathResult(
result,
[[mSolSolPool, rlbSolPool]],
mSolSolPool.tokenMintB,
rlbSolPool.tokenMintB,
);
});
it("1 tokenPair input to multiple paths exist - verify token order, edge ordering", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
rlbSolPool.tokenMintB,
mSolSolPool.tokenMintB,
);
assertGetPathResult(
result,
[
[rlbSolPool, mSolSolPool],
[rlbUsdcPool, msolUsdcPool],
],
rlbSolPool.tokenMintB,
mSolSolPool.tokenMintB,
);
});
it("only allow 2-edge paths that go through tokens from the intermediate token list ", async () => {
const testData = [...solConnectedPools, ...usdcConnectedPools];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const result = graph.getPath(
rlbUsdcPool.tokenMintB,
msolUsdcPool.tokenMintB,
{
intermediateTokens: [rlbUsdcPool.tokenMintA],
},
);
assertGetPathResult(
result,
[[rlbUsdcPool, msolUsdcPool]],
rlbUsdcPool.tokenMintB,
msolUsdcPool.tokenMintB,
);
});
});
describe("Pool graph edge cases", () => {
it("Zero pools in graph should not return any results", async () => {
const graph = PoolGraphBuilder.buildPoolGraph([]);
const uniqueTokenPair = uniqueTokenMintsGraphTokenUnsortedData[0];
const results = graph.getPathsForPairs([
[uniqueTokenPair.tokenMintA, uniqueTokenPair.tokenMintB],
]);
assert.equal(results.length, 1);
const searchId = PoolGraphUtils.getSearchPathId(
uniqueTokenPair.tokenMintA,
uniqueTokenPair.tokenMintB,
);
assertGetPathsForPairsResult(results, [[searchId, []]]);
});
it("Duplicate pool data in input should not affect output", async () => {
const testData = [
...solConnectedPools,
...solConnectedPools,
...uniqueTokenMintsGraphData,
];
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const searchTokenPairs: [Address, Address][] = [
[uniqueTokenPair.tokenMintA, uniqueTokenPair.tokenMintB],
[rlbSolPool.tokenMintA, rlbSolPool.tokenMintB],
];
const results = graph.getPathsForPairs(searchTokenPairs);
assert.equal(results.length, 2);
const expectedPathsForTokenPairQueries: [string, PoolTokenPair[][]][] = [
[
PoolGraphUtils.getSearchPathId(
searchTokenPairs[0][0],
searchTokenPairs[0][1],
),
[[uniqueTokenPair]],
],
[
PoolGraphUtils.getSearchPathId(
rlbSolPool.tokenMintA,
rlbSolPool.tokenMintB,
),
[[rlbSolPool]],
],
];
assertGetPathsForPairsResult(results, expectedPathsForTokenPairQueries);
});
});
describe("getAllPaths", () => {
it("Zero pools", async () => {
const graph = PoolGraphBuilder.buildPoolGraph([]);
const results = graph.getAllPaths();
assert.equal(results.length, 0);
});
it("solConnectedPools", () => {
const testData = solConnectedPools;
const graph = PoolGraphBuilder.buildPoolGraph(testData);
const results = graph.getAllPaths();
const sol = rlbSolPool.tokenMintA;
const rlb = rlbSolPool.tokenMintB;
const msol = mSolSolPool.tokenMintB;
const dust = dustSolPool.tokenMintB;
const stSol = stSolSolPool.tokenMintB;
const usdc = usdcSolPool.tokenMintB;
const expectedPaths = new Map<string, PoolTokenPair[][]>();
// combinations
expectedPaths.set(PoolGraphUtils.getSearchPathId(sol, rlb), [
[rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(sol, msol), [
[mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(sol, dust), [
[dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(sol, stSol), [
[stSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(sol, usdc), [
[usdcSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(rlb, msol), [
[rlbSolPool, mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(rlb, dust), [
[rlbSolPool, dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(rlb, stSol), [
[rlbSolPool, stSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(rlb, usdc), [
[rlbSolPool, usdcSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(msol, dust), [
[mSolSolPool, dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(msol, stSol), [
[mSolSolPool, stSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(msol, usdc), [
[mSolSolPool, usdcSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(dust, stSol), [
[dustSolPool, stSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(dust, usdc), [
[dustSolPool, usdcSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(stSol, usdc), [
[stSolSolPool, usdcSolPool],
]);
// reverse
expectedPaths.set(PoolGraphUtils.getSearchPathId(rlb, sol), [
[rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(msol, sol), [
[mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(dust, sol), [
[dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(stSol, sol), [
[stSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(usdc, sol), [
[usdcSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(msol, rlb), [
[mSolSolPool, rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(dust, rlb), [
[dustSolPool, rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(stSol, rlb), [
[stSolSolPool, rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(usdc, rlb), [
[usdcSolPool, rlbSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(dust, msol), [
[dustSolPool, mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(stSol, msol), [
[stSolSolPool, mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(usdc, msol), [
[usdcSolPool, mSolSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(stSol, dust), [
[stSolSolPool, dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(usdc, dust), [
[usdcSolPool, dustSolPool],
]);
expectedPaths.set(PoolGraphUtils.getSearchPathId(usdc, stSol), [
[usdcSolPool, stSolSolPool],
]);
assert.equal(
results.length,
expectedPaths.size,
"Number of paths should match expected paths",
);
results.forEach((searchEntry) => {
const [pathId, paths] = searchEntry;
const [startMint, endMint] = PoolGraphUtils.deconstructPathId(pathId);
const expected = expectedPaths.get(pathId);
assert.ok(!!expected, `Expected path for ${pathId} to exist`);
assertGetPathResult(paths, expected, startMint, endMint);
});
});
});
});
function assertGetPathsForPairsResult(
searchResultEntires: PathSearchEntries,
expectedPaths: [string, PoolTokenPair[][]][],
) {
assert.equal(
searchResultEntires.length,
expectedPaths.length,
`Number of paths should match expected paths`,
);
searchResultEntires.forEach((searchEntry, entryIndex) => {
const [pathId, paths] = searchEntry;
const [startMint, endMint] = PoolGraphUtils.deconstructPathId(pathId);
// Assert path is correct
const expectedPathsForEntry = expectedPaths[entryIndex];
assert.equal(
paths.length,
expectedPathsForEntry[1].length,
"Expected number of paths to match expected pools",
);
assertGetPathResult(paths, expectedPathsForEntry[1], startMint, endMint);
});
}
function assertGetPathResult(
paths: Path[],
expectedPaths: PoolTokenPair[][],
expectedStartMint: Address,
expectedEndMint: Address,
) {
assert.equal(paths.length, expectedPaths.length);
paths.forEach((path, pathIndex) => {
assertPath(
path,
pathIndex,
expectedStartMint,
expectedEndMint,
expectedPaths,
);
});
}
function assertPath(
path: Path,
pathIndex: number,
expectedStartMint: Address,
expectedEndMint: Address,
expectedPaths: PoolTokenPair[][],
) {
assert.equal(path.startTokenMint, AddressUtil.toString(expectedStartMint));
assert.equal(path.endTokenMint, AddressUtil.toString(expectedEndMint));
const expectedPath = expectedPaths[pathIndex];
assert.equal(
path.edges.length,
expectedPath.length,
`Expected number of edges to match expected pools at index ${pathIndex}`,
);
path.edges.forEach((edge, edgeIndex) => {
assert.equal(
AddressUtil.toString(edge.poolAddress),
AddressUtil.toString(expectedPaths[pathIndex][edgeIndex].address),
`Expected edge pool address to match expected pool addr at edge index ${edgeIndex}`,
);
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/token-extension-util.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import type { MintWithTokenProgram } from "@orca-so/common-sdk";
import { MathUtil } from "@orca-so/common-sdk";
import * as assert from "assert";
import Decimal from "decimal.js";
import {
IGNORE_CACHE,
TokenExtensionUtil,
WhirlpoolContext,
} from "../../../../src";
import { TickSpacing } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixtureV2 } from "../../../utils/v2/fixture-v2";
describe("TokenExtensionUtil tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
const fetcher = ctx.fetcher;
let fixture: WhirlpoolTestFixtureV2;
function partialEqualsTokenMintWithPrograml(
a: MintWithTokenProgram,
b: MintWithTokenProgram,
): boolean {
if (!a.address.equals(b.address)) return false;
if (!a.tokenProgram.equals(b.tokenProgram)) return false;
if (a.decimals !== b.decimals) return false;
if (!a.tlvData.equals(b.tlvData)) return false;
return true;
}
beforeAll(async () => {
const vaultStartBalance = 1_000_000;
const lowerTickIndex = -1280,
upperTickIndex = 1280,
tickSpacing = TickSpacing.Standard;
fixture = await new WhirlpoolTestFixtureV2(ctx).init({
tokenTraitA: { isToken2022: true },
tokenTraitB: { isToken2022: false },
tickSpacing: tickSpacing,
initialSqrtPrice: MathUtil.toX64(new Decimal(1)),
positions: [
{
tickLowerIndex: lowerTickIndex,
tickUpperIndex: upperTickIndex,
liquidityAmount: new anchor.BN(1_000_000),
},
],
rewards: [
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
{
rewardTokenTrait: {
isToken2022: true,
hasConfidentialTransferExtension: true,
},
emissionsPerSecondX64: MathUtil.toX64(new Decimal(10)),
vaultAmount: new BN(vaultStartBalance),
},
],
});
});
it("buildTokenExtensionContextForPool", async () => {
const poolInitInfo = fixture.getInfos().poolInitInfo;
const { tokenMintA, tokenMintB } = poolInitInfo;
const whirlpoolData = await fetcher.getPool(
poolInitInfo.whirlpoolPda.publicKey,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
fetcher,
whirlpoolData!,
IGNORE_CACHE,
);
const tokenExtensionCtxForPool =
await TokenExtensionUtil.buildTokenExtensionContextForPool(
fetcher,
tokenMintA,
tokenMintB,
IGNORE_CACHE,
);
assert.ok(
partialEqualsTokenMintWithPrograml(
tokenExtensionCtx.tokenMintWithProgramA,
tokenExtensionCtxForPool.tokenMintWithProgramA,
),
);
assert.ok(
partialEqualsTokenMintWithPrograml(
tokenExtensionCtx.tokenMintWithProgramB,
tokenExtensionCtxForPool.tokenMintWithProgramB,
),
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/fetcher-util.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import * as assert from "assert";
import {
getAllPositionAccountsByOwner,
IGNORE_CACHE,
toTx,
WhirlpoolContext,
} from "../../../../src";
import { systemTransferTx, TickSpacing } from "../../../utils";
import { defaultConfirmOptions } from "../../../utils/const";
import { WhirlpoolTestFixture } from "../../../utils/fixture";
import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import type { PublicKey } from "@solana/web3.js";
import { PDAUtil } from "../../../../dist/utils/public/pda-utils";
import { WhirlpoolIx } from "../../../../dist/ix";
import {
getAssociatedTokenAddressSync,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import { PositionBundleUtil } from "../../../../dist/utils/public/position-bundle-util";
import NodeWallet from "@coral-xyz/anchor/dist/cjs/nodewallet";
describe("fetcher util tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const globalCtx = WhirlpoolContext.fromWorkspace(provider, program);
// create isolated wallet because the wallet for globalCtx has many positions created by other test cases.
const isolatedOwnerKeypair = Keypair.generate();
const isolatedWallet = new NodeWallet(isolatedOwnerKeypair);
const ctx = WhirlpoolContext.from(
globalCtx.connection,
isolatedWallet,
globalCtx.program.programId,
);
const fetcher = ctx.fetcher;
beforeAll(async () => {
await systemTransferTx(
provider,
isolatedOwnerKeypair.publicKey,
10 * LAMPORTS_PER_SOL,
).buildAndExecute();
});
const tickLowerIndex = 29440;
const tickUpperIndex = 33536;
const tickSpacing = TickSpacing.Standard;
const liquidityAmount = new BN(10_000_000);
async function initializePositionBundleWithPositions(
whirlpool: PublicKey,
bundleIndexes: number[],
): Promise<PublicKey> {
const positionBundleMintKeypair = Keypair.generate();
const positionBundlePda = PDAUtil.getPositionBundle(
ctx.program.programId,
positionBundleMintKeypair.publicKey,
);
const positionBundleTokenAccount = getAssociatedTokenAddressSync(
positionBundleMintKeypair.publicKey,
ctx.wallet.publicKey,
undefined,
TOKEN_PROGRAM_ID,
);
await toTx(
ctx,
WhirlpoolIx.initializePositionBundleIx(ctx.program, {
funder: ctx.wallet.publicKey,
owner: ctx.wallet.publicKey,
positionBundleMintKeypair,
positionBundlePda,
positionBundleTokenAccount,
}),
).buildAndExecute();
for (const bundleIndex of bundleIndexes) {
const bundledPositionPda = PDAUtil.getBundledPosition(
ctx.program.programId,
positionBundleMintKeypair.publicKey,
bundleIndex,
);
await toTx(
ctx,
WhirlpoolIx.openBundledPositionIx(ctx.program, {
bundledPositionPda,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
positionBundle: positionBundlePda.publicKey,
positionBundleAuthority: ctx.wallet.publicKey,
positionBundleTokenAccount,
funder: ctx.wallet.publicKey,
whirlpool,
}),
).buildAndExecute();
}
const positionBundleData = await fetcher.getPositionBundle(
positionBundlePda.publicKey,
IGNORE_CACHE,
);
assert.ok(!!positionBundleData);
const occupied =
PositionBundleUtil.getOccupiedBundleIndexes(positionBundleData);
assert.deepEqual(occupied, bundleIndexes);
return positionBundlePda.publicKey;
}
it("getAllPositionAccountsByOwner", async () => {
const fixture = await new WhirlpoolTestFixture(ctx).init({
tickSpacing,
positions: [
// 5 TokenProgram based positions
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: false,
},
// 5 TokenExtensions based positions
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: true,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: true,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: true,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: true,
},
{
tickLowerIndex,
tickUpperIndex,
liquidityAmount,
isTokenExtensionsBasedPosition: true,
},
],
});
const positionAddresses = new Set(
fixture
.getInfos()
.positions.slice(0, 5)
.map((p) => p.publicKey.toBase58()),
);
assert.ok(positionAddresses.size === 5);
const positionWithTokenExtensionsAddresses = new Set(
fixture
.getInfos()
.positions.slice(5)
.map((p) => p.publicKey.toBase58()),
);
assert.ok(positionWithTokenExtensionsAddresses.size === 5);
// initialize 2 position bundles
const whirlpool = fixture.getInfos().poolInitInfo.whirlpoolPda.publicKey;
const positionBundle1BundleIndexes = [0, 128, 250];
const positionBundle1Pubkey = await initializePositionBundleWithPositions(
whirlpool,
positionBundle1BundleIndexes,
);
const positionBundle2BundleIndexes = [5, 30, 64, 135, 192, 255];
const positionBundle2Pubkey = await initializePositionBundleWithPositions(
whirlpool,
positionBundle2BundleIndexes,
);
const result = await getAllPositionAccountsByOwner({
ctx,
owner: ctx.wallet.publicKey,
includesPositions: true,
includesBundledPositions: true,
includesPositionsWithTokenExtensions: true,
});
assert.ok(result.positions.size === 5);
assert.ok(
Array.from(result.positions.keys()).every((p) =>
positionAddresses.has(p),
),
);
assert.ok(
Array.from(result.positions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
assert.ok(result.positionsWithTokenExtensions.size === 5);
assert.ok(
Array.from(result.positionsWithTokenExtensions.keys()).every((p) =>
positionWithTokenExtensionsAddresses.has(p),
),
);
assert.ok(
Array.from(result.positionsWithTokenExtensions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
assert.ok(result.positionBundles.length === 2);
const pb0 = result.positionBundles[0];
const pb1 = result.positionBundles[1];
const occupied0 = PositionBundleUtil.getOccupiedBundleIndexes(
pb0.positionBundleData,
);
const occupied1 = PositionBundleUtil.getOccupiedBundleIndexes(
pb1.positionBundleData,
);
if (
pb0.positionBundleAddress.toString() === positionBundle1Pubkey.toString()
) {
assert.ok(
pb0.positionBundleAddress.toString() ===
positionBundle1Pubkey.toString(),
);
assert.deepEqual(occupied0, positionBundle1BundleIndexes);
assert.ok(
pb0.bundledPositions.size === positionBundle1BundleIndexes.length,
);
assert.deepEqual(
Array.from(pb0.bundledPositions.keys()),
positionBundle1BundleIndexes,
);
assert.ok(
Array.from(pb0.bundledPositions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
assert.ok(
pb1.positionBundleAddress.toString() ===
positionBundle2Pubkey.toString(),
);
assert.deepEqual(occupied1, positionBundle2BundleIndexes);
assert.ok(
pb1.bundledPositions.size === positionBundle2BundleIndexes.length,
);
assert.deepEqual(
Array.from(pb1.bundledPositions.keys()),
positionBundle2BundleIndexes,
);
assert.ok(
Array.from(pb1.bundledPositions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
} else {
assert.ok(
pb0.positionBundleAddress.toString() ===
positionBundle2Pubkey.toString(),
);
assert.deepEqual(occupied0, positionBundle2BundleIndexes);
assert.ok(
pb0.bundledPositions.size === positionBundle2BundleIndexes.length,
);
assert.deepEqual(
Array.from(pb0.bundledPositions.keys()),
positionBundle2BundleIndexes,
);
assert.ok(
Array.from(pb0.bundledPositions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
assert.ok(
pb1.positionBundleAddress.toString() ===
positionBundle1Pubkey.toString(),
);
assert.deepEqual(occupied1, positionBundle1BundleIndexes);
assert.ok(
pb1.bundledPositions.size === positionBundle1BundleIndexes.length,
);
assert.deepEqual(
Array.from(pb1.bundledPositions.keys()),
positionBundle1BundleIndexes,
);
assert.ok(
Array.from(pb1.bundledPositions.values()).every(
(p) =>
p.tickLowerIndex === tickLowerIndex &&
p.tickUpperIndex === tickUpperIndex,
),
);
}
const resultDefault = await getAllPositionAccountsByOwner({
ctx,
owner: ctx.wallet.publicKey,
});
assert.ok(resultDefault.positions.size === 5);
assert.ok(resultDefault.positionsWithTokenExtensions.size === 5);
// no bundled positions
assert.ok(resultDefault.positionBundles.length === 0);
const resultAllFalse = await getAllPositionAccountsByOwner({
ctx,
owner: ctx.wallet.publicKey,
includesPositions: false,
includesBundledPositions: false,
includesPositionsWithTokenExtensions: false,
});
assert.ok(resultAllFalse.positions.size === 0);
assert.ok(resultAllFalse.positionsWithTokenExtensions.size === 0);
assert.ok(resultAllFalse.positionBundles.length === 0);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/tick-utils.test.ts
|
import * as assert from "assert";
import { TickUtil, MIN_TICK_INDEX, MAX_TICK_INDEX } from "../../../../src";
describe("TickUtil tests", () => {
describe("getFullRangeTickIndex", () => {
function checkGetFullRangeTickIndex(
tickSpacing: number,
minMaxAbs: number,
) {
const [min, max] = TickUtil.getFullRangeTickIndex(tickSpacing);
assert.equal(min, -minMaxAbs);
assert.equal(max, +minMaxAbs);
assert.ok(-minMaxAbs - tickSpacing < MIN_TICK_INDEX);
assert.ok(+minMaxAbs + tickSpacing > MAX_TICK_INDEX);
}
it("tickSpacing = 1", async () => {
const [min, max] = TickUtil.getFullRangeTickIndex(1);
assert.equal(min, MIN_TICK_INDEX);
assert.equal(max, MAX_TICK_INDEX);
});
it("tickSpacing = 8", async () => {
checkGetFullRangeTickIndex(8, 443632);
});
it("tickSpacing = 64", async () => {
checkGetFullRangeTickIndex(64, 443584);
});
it("tickSpacing = 128", async () => {
checkGetFullRangeTickIndex(128, 443520);
});
});
describe("isFullRange", () => {
function checkIsFullRange(tickSpacing: number) {
const [min, max] = TickUtil.getFullRangeTickIndex(tickSpacing);
assert.ok(TickUtil.isFullRange(tickSpacing, min, max));
for (let minShift = -1; minShift <= 1; minShift++) {
for (let maxShift = -1; maxShift <= 1; maxShift++) {
const isFullRange = minShift === 0 && maxShift === 0;
assert.equal(
TickUtil.isFullRange(
tickSpacing,
min + minShift * tickSpacing,
max + maxShift * tickSpacing,
),
isFullRange,
);
}
}
}
it("tickSpacing = [1, 2, 4, 8, ...., 128, 256]", async () => {
for (let tickSpacing = 1; tickSpacing <= 256; tickSpacing *= 2) {
checkIsFullRange(tickSpacing);
}
});
});
describe("isFullRangeOnly", () => {
it("returns true for tickSpacing = 32768", async () => {
assert.strictEqual(TickUtil.isFullRangeOnly(32768), true);
});
it("returns true for tickSpacing > 32768", async () => {
assert.strictEqual(TickUtil.isFullRangeOnly(32769), true);
});
it("returns false for tickSpacing < 32768", async () => {
assert.strictEqual(TickUtil.isFullRangeOnly(32767), false);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/pool-utils.test.ts
|
import * as assert from "assert";
import { TokenType, PoolUtil } from "../../../../src";
import { testWhirlpoolData } from "../../../utils/testDataTypes";
import { Keypair } from "@solana/web3.js";
describe("PoolUtils tests", () => {
describe("getTokenType", () => {
it("Token is tokenA", async () => {
const whirlpoolData = testWhirlpoolData;
const result = PoolUtil.getTokenType(
whirlpoolData,
whirlpoolData.tokenMintA,
);
assert.equal(result, TokenType.TokenA);
});
it("Token is tokenB", async () => {
const whirlpoolData = testWhirlpoolData;
const result = PoolUtil.getTokenType(
whirlpoolData,
whirlpoolData.tokenMintB,
);
assert.equal(result, TokenType.TokenB);
});
it("Token is some other token", async () => {
const whirlpoolData = testWhirlpoolData;
const result = PoolUtil.getTokenType(
whirlpoolData,
Keypair.generate().publicKey,
);
assert.ok(result === undefined);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/tick-array-sequence.test.ts
|
import { TICK_ARRAY_SIZE } from "../../../../src";
import * as assert from "assert";
import { TickArraySequence } from "../../../../src/quotes/swap/tick-array-sequence";
import { buildTickArrayData } from "../../../utils/testDataTypes";
import { TickArrayIndex } from "../../../../src/quotes/swap/tick-array-index";
import type { WhirlpoolsError } from "../../../../src/errors/errors";
import { SwapErrorCode } from "../../../../src/errors/errors";
describe("TickArray Sequence tests", () => {
const ts64 = 64;
const ts128 = 128;
describe("isValidTickArray0 tests", () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -1, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -2, [25, 50]);
it("a->b, |--------ta2--------|--------ta1------i-|--------ta0--------|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(!seq.isValidTickArray0(-1 * ts64));
});
it("a->b, |--------ta2--------|--------ta1-------i|--------ta0--------|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(!seq.isValidTickArray0(-1));
});
it("a->b, |--------ta2--------|--------ta1--------|i-------ta0--------|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(seq.isValidTickArray0(0));
});
it("a->b, |--------ta2--------|--------ta1--------|-i------ta0--------|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(seq.isValidTickArray0(ts64));
});
it("a->b, |--------ta2--------|--------ta1--------|--------ta0-----i--|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(seq.isValidTickArray0(ts64 * TICK_ARRAY_SIZE - ts64 - 1));
});
it("a->b, |--------ta2--------|--------ta1--------|--------ta0------i-|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(seq.isValidTickArray0(ts64 * TICK_ARRAY_SIZE - ts64));
});
it("a->b, |--------ta2--------|--------ta1--------|--------ta0-------i|", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(seq.isValidTickArray0(ts64 * TICK_ARRAY_SIZE - 1));
});
it("a->b, |--------ta2--------|--------ta1--------|--------ta0--------|i", () => {
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
assert.ok(!seq.isValidTickArray0(ts64 * TICK_ARRAY_SIZE));
});
it("b->a, i--|--------ta2--------|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta2StartTickIndex = ts64 * TICK_ARRAY_SIZE * -2;
assert.ok(!seq.isValidTickArray0(ta2StartTickIndex - ts64 - 1));
});
it("b->a, -i-|--------ta2--------|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta2StartTickIndex = ts64 * TICK_ARRAY_SIZE * -2;
assert.ok(seq.isValidTickArray0(ta2StartTickIndex - ts64));
});
it("b->a, --i|--------ta2--------|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta2StartTickIndex = ts64 * TICK_ARRAY_SIZE * -2;
assert.ok(seq.isValidTickArray0(ta2StartTickIndex - 1));
});
it("b->a, ---|i-------ta2--------|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta2StartTickIndex = ts64 * TICK_ARRAY_SIZE * -2;
assert.ok(seq.isValidTickArray0(ta2StartTickIndex));
});
it("b->a, ---|-i------ta2--------|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta2StartTickIndex = ts64 * TICK_ARRAY_SIZE * -2;
assert.ok(seq.isValidTickArray0(ta2StartTickIndex + ts64));
});
it("b->a, ---|--------ta2-----i--|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta1StartTickIndex = ts64 * TICK_ARRAY_SIZE * -1;
assert.ok(seq.isValidTickArray0(ta1StartTickIndex - ts64 - 1));
});
it("b->a, ---|--------ta2------i-|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta1StartTickIndex = ts64 * TICK_ARRAY_SIZE * -1;
assert.ok(!seq.isValidTickArray0(ta1StartTickIndex - ts64));
});
it("b->a, ---|--------ta2-------i|--------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta1StartTickIndex = ts64 * TICK_ARRAY_SIZE * -1;
assert.ok(!seq.isValidTickArray0(ta1StartTickIndex - 1));
});
it("b->a, ---|--------ta2--------|i-------ta1--------|--------ta0--------|", () => {
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
const ta1StartTickIndex = ts64 * TICK_ARRAY_SIZE * -1;
assert.ok(!seq.isValidTickArray0(ta1StartTickIndex));
});
});
describe("findNextInitializedTickIndex tests", () => {
it("a->b, search reaches left bounds", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -1, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
let searchIndex = new TickArrayIndex(-2, 12, ts64).toTickIndex();
// First traversal brings swap to the left most edge
const { nextIndex } = seq.findNextInitializedTickIndex(searchIndex);
assert.equal(nextIndex, ta2.data!.startTickIndex);
// The next one will throw an error
assert.throws(
() => seq.findNextInitializedTickIndex(nextIndex - 1),
(err) => {
const whirlErr = err as WhirlpoolsError;
return whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
},
);
});
it("b->a, search reaches right bounds", async () => {
const ta0 = buildTickArrayData(0, [0, 32]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -1, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -2, [25, 50]);
const seq = new TickArraySequence([ta2, ta1, ta0], ts64, false);
let searchIndex = new TickArrayIndex(0, 33, ts64).toTickIndex();
// First traversal brings swap to the right most edge
const { nextIndex } = seq.findNextInitializedTickIndex(searchIndex);
assert.equal(
nextIndex,
ta0.data!.startTickIndex + TICK_ARRAY_SIZE * ts64 - 1,
);
// The next one will throw an error
assert.throws(
() => seq.findNextInitializedTickIndex(nextIndex),
(err) => {
const whirlErr = err as WhirlpoolsError;
return whirlErr.errorCode === SwapErrorCode.TickArraySequenceInvalid;
},
);
});
it("a->b, on initializable index, ts = 64", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -1, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
let searchIndex = new TickArrayIndex(0, 32, ts64).toTickIndex();
const expectedIndicies = [
new TickArrayIndex(0, 32, ts64).toTickIndex(),
new TickArrayIndex(0, 0, ts64).toTickIndex(),
new TickArrayIndex(-1, 50, ts64).toTickIndex(),
new TickArrayIndex(-1, 0, ts64).toTickIndex(),
new TickArrayIndex(-2, 50, ts64).toTickIndex(),
new TickArrayIndex(-2, 25, ts64).toTickIndex(),
ta2.data!.startTickIndex, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex - 1;
});
});
it("a->b, on initializable index, ts = 64", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -1, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * -2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, true);
let searchIndex = new TickArrayIndex(0, 32, ts64).toTickIndex();
const expectedIndicies = [
new TickArrayIndex(0, 32, ts64).toTickIndex(),
new TickArrayIndex(0, 0, ts64).toTickIndex(),
new TickArrayIndex(-1, 50, ts64).toTickIndex(),
new TickArrayIndex(-1, 0, ts64).toTickIndex(),
new TickArrayIndex(-2, 50, ts64).toTickIndex(),
new TickArrayIndex(-2, 25, ts64).toTickIndex(),
ta2.data!.startTickIndex, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex - 1;
});
});
it("b->a, not on initializable index, ts = 128", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts128 * TICK_ARRAY_SIZE, [0, 50]);
const ta2 = buildTickArrayData(ts128 * TICK_ARRAY_SIZE * 2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts128, false);
let searchIndex = new TickArrayIndex(0, 25, ts128).toTickIndex() + 64;
const expectedIndicies = [
new TickArrayIndex(0, 32, ts128).toTickIndex(),
new TickArrayIndex(0, 63, ts128).toTickIndex(),
new TickArrayIndex(1, 0, ts128).toTickIndex(),
new TickArrayIndex(1, 50, ts128).toTickIndex(),
new TickArrayIndex(2, 25, ts128).toTickIndex(),
new TickArrayIndex(2, 50, ts128).toTickIndex(),
ta2.data!.startTickIndex + TICK_ARRAY_SIZE * ts128 - 1, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex;
});
});
it("b->a, on initializable index, ts = 64", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * 2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, false);
let searchIndex = new TickArrayIndex(0, 25, ts64).toTickIndex();
const expectedIndicies = [
new TickArrayIndex(0, 32, ts64).toTickIndex(),
new TickArrayIndex(0, 63, ts64).toTickIndex(),
new TickArrayIndex(1, 0, ts64).toTickIndex(),
new TickArrayIndex(1, 50, ts64).toTickIndex(),
new TickArrayIndex(2, 25, ts64).toTickIndex(),
new TickArrayIndex(2, 50, ts64).toTickIndex(),
ta2.data!.startTickIndex + TICK_ARRAY_SIZE * ts64 - 1, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex;
});
});
it("b->a, on initializable index, ts = 64, currentTickIndex = -64, shifted", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * 2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, false);
let searchIndex = -1 * ts64;
const expectedIndicies = [
new TickArrayIndex(0, 0, ts64).toTickIndex(),
new TickArrayIndex(0, 32, ts64).toTickIndex(),
new TickArrayIndex(0, 63, ts64).toTickIndex(),
new TickArrayIndex(1, 0, ts64).toTickIndex(),
new TickArrayIndex(1, 50, ts64).toTickIndex(),
new TickArrayIndex(2, 25, ts64).toTickIndex(),
new TickArrayIndex(2, 50, ts64).toTickIndex(),
ta2.data!.startTickIndex + TICK_ARRAY_SIZE * ts64 - 1, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex;
});
});
it("b->a, on initializable index, ts = 64, currentTickIndex = -1, shifted", async () => {
const ta0 = buildTickArrayData(0, [0, 32, 63]);
const ta1 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE, [0, 50]);
const ta2 = buildTickArrayData(ts64 * TICK_ARRAY_SIZE * 2, [25, 50]);
const seq = new TickArraySequence([ta0, ta1, ta2], ts64, false);
let searchIndex = -1;
const expectedIndicies = [
new TickArrayIndex(0, 0, ts64).toTickIndex(),
new TickArrayIndex(0, 32, ts64).toTickIndex(),
new TickArrayIndex(0, 63, ts64).toTickIndex(),
new TickArrayIndex(1, 0, ts64).toTickIndex(),
new TickArrayIndex(1, 50, ts64).toTickIndex(),
new TickArrayIndex(2, 25, ts64).toTickIndex(),
new TickArrayIndex(2, 50, ts64).toTickIndex(),
ta2.data!.startTickIndex + TICK_ARRAY_SIZE * ts64 - 1, // Last index in array 3
];
expectedIndicies.forEach((expectedIndex, expectedResultIndex) => {
const { nextIndex, nextTickData } =
seq.findNextInitializedTickIndex(searchIndex)!;
if (expectedResultIndex === expectedIndicies.length - 1) {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData === null);
} else {
assert.equal(nextIndex, expectedIndex);
assert.ok(nextTickData!.initialized);
}
searchIndex = nextIndex;
});
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/whirlpools/utils/swap-utils.test.ts
|
import * as anchor from "@coral-xyz/anchor";
import { Keypair } from "@solana/web3.js";
import * as assert from "assert";
import type { TickArray, TickArrayData, TickData } from "../../../../src";
import {
ORCA_WHIRLPOOL_PROGRAM_ID,
PDAUtil,
SwapDirection,
SwapUtils,
TICK_ARRAY_SIZE,
} from "../../../../src";
import { WhirlpoolContext } from "../../../../src/context";
import { defaultConfirmOptions } from "../../../utils/const";
import { testWhirlpoolData } from "../../../utils/testDataTypes";
import BN from "bn.js";
import { TickSpacing } from "../../../utils";
describe("SwapUtils tests", () => {
const provider = anchor.AnchorProvider.local(
undefined,
defaultConfirmOptions,
);
const program = anchor.workspace.Whirlpool;
const ctx = WhirlpoolContext.fromWorkspace(provider, program);
describe("getSwapDirection", () => {
it("SwapToken is tokenA and is an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
whirlpoolData.tokenMintA,
true,
);
assert.equal(result, SwapDirection.AtoB);
});
it("SwapToken is tokenB and is an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
whirlpoolData.tokenMintB,
true,
);
assert.equal(result, SwapDirection.BtoA);
});
it("SwapToken is tokenA and is not an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
whirlpoolData.tokenMintA,
false,
);
assert.equal(result, SwapDirection.BtoA);
});
it("SwapToken is tokenB and is not an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
whirlpoolData.tokenMintB,
false,
);
assert.equal(result, SwapDirection.AtoB);
});
it("SwapToken is a random mint and is an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
Keypair.generate().publicKey,
true,
);
assert.equal(result, undefined);
});
it("SwapToken is a random mint and is not an input", async () => {
const whirlpoolData = testWhirlpoolData;
const result = SwapUtils.getSwapDirection(
whirlpoolData,
Keypair.generate().publicKey,
false,
);
assert.equal(result, undefined);
});
});
describe("getTickArrayPublicKeys", () => {
it("a->b, ts = 64, tickCurrentIndex = 0", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = true;
const tickCurrentIndex = 0;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 0)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -2)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("a->b, ts = 64, tickCurrentIndex = 64*TICK_ARRAY_SIZE - 64", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = true;
const tickCurrentIndex = tickSpacing * TICK_ARRAY_SIZE - tickSpacing;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 0)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -2)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("a->b, ts = 64, tickCurrentIndex = 64*TICK_ARRAY_SIZE - 1", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = true;
const tickCurrentIndex = tickSpacing * TICK_ARRAY_SIZE - 1;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 0)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * -2)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("b->a, shifted, ts = 64, tickCurrentIndex = 0", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = false;
const tickCurrentIndex = 0;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 0)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 2)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("b->a, shifted, ts = 64, tickCurrentIndex = 64*TICK_ARRAY_SIZE - 64 - 1", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = false;
const tickCurrentIndex = tickSpacing * TICK_ARRAY_SIZE - tickSpacing - 1;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 0)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 2)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("b->a, shifted, ts = 64, tickCurrentIndex = 64*TICK_ARRAY_SIZE - 64", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = false;
const tickCurrentIndex = tickSpacing * TICK_ARRAY_SIZE - tickSpacing;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 2)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 3)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
it("b->a, shifted, ts = 64, tickCurrentIndex = 64*TICK_ARRAY_SIZE - 1", () => {
const programId = ctx.program.programId;
const whirlpoolPubkey = Keypair.generate().publicKey;
const tickSpacing = 64;
const ticksInArray = tickSpacing * TICK_ARRAY_SIZE;
const aToB = false;
const tickCurrentIndex = tickSpacing * TICK_ARRAY_SIZE - 1;
const result = SwapUtils.getTickArrayPublicKeys(
tickCurrentIndex,
tickSpacing,
aToB,
ctx.program.programId,
whirlpoolPubkey,
);
const expected = [
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 1)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 2)
.publicKey,
PDAUtil.getTickArray(programId, whirlpoolPubkey, ticksInArray * 3)
.publicKey,
];
result.forEach((k, i) =>
assert.equal(k.toBase58(), expected[i].toBase58()),
);
});
});
describe("interpolateUninitializedTickArrays", () => {
const whirlpoolAddress = Keypair.generate().publicKey;
const tickSpacing = TickSpacing.Standard;
const initializedTick: TickData = {
initialized: true,
liquidityNet: new BN(100),
liquidityGross: new BN(100),
feeGrowthOutsideA: new BN(100),
feeGrowthOutsideB: new BN(100),
rewardGrowthsOutside: [new BN(100), new BN(100), new BN(100)],
};
const initializedTickArrayData: TickArrayData = {
startTickIndex: 0,
ticks: Array(TICK_ARRAY_SIZE).fill(initializedTick),
whirlpool: whirlpoolAddress,
};
it("no uninitialized tick arrays", async () => {
const tickArrays: TickArray[] = [
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 0,
data: initializedTickArrayData,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 1,
data: initializedTickArrayData,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 2,
data: initializedTickArrayData,
},
];
const result = SwapUtils.interpolateUninitializedTickArrays(
whirlpoolAddress,
tickArrays,
);
// no change
assert.ok(result[0].data === initializedTickArrayData);
assert.ok(result[1].data === initializedTickArrayData);
assert.ok(result[2].data === initializedTickArrayData);
});
it("1 uninitialized tick arrays", async () => {
const tickArrays: TickArray[] = [
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 0,
data: initializedTickArrayData,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 1,
data: null,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 2,
data: initializedTickArrayData,
},
];
const result = SwapUtils.interpolateUninitializedTickArrays(
whirlpoolAddress,
tickArrays,
);
// no change
assert.ok(result[0].data === initializedTickArrayData);
assert.ok(
result[1].data !== null &&
result[1].data.startTickIndex === result[1].startTickIndex,
);
for (let i = 0; i < TICK_ARRAY_SIZE; i++) {
const tick = result[1].data.ticks[i];
assert.ok(tick.initialized === false);
assert.ok(tick.liquidityNet.eqn(0));
assert.ok(tick.liquidityGross.eqn(0));
assert.ok(tick.feeGrowthOutsideA.eqn(0));
assert.ok(tick.feeGrowthOutsideB.eqn(0));
assert.ok(tick.rewardGrowthsOutside[0].eqn(0));
assert.ok(tick.rewardGrowthsOutside[1].eqn(0));
assert.ok(tick.rewardGrowthsOutside[2].eqn(0));
}
assert.ok(result[2].data === initializedTickArrayData);
});
it("3 uninitialized tick arrays", async () => {
const tickArrays: TickArray[] = [
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 0,
data: null,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 1,
data: null,
},
{
address: whirlpoolAddress,
startTickIndex: tickSpacing * TICK_ARRAY_SIZE * 2,
data: null,
},
];
const result = SwapUtils.interpolateUninitializedTickArrays(
whirlpoolAddress,
tickArrays,
);
for (let i = 0; i < 3; i++) {
assert.ok(
result[i].data !== null &&
result[i].data!.startTickIndex === result[i].startTickIndex,
);
for (let j = 0; j < TICK_ARRAY_SIZE; j++) {
const tick = result[i].data!.ticks[j];
assert.ok(tick.initialized === false);
assert.ok(tick.liquidityNet.eqn(0));
assert.ok(tick.liquidityGross.eqn(0));
assert.ok(tick.feeGrowthOutsideA.eqn(0));
assert.ok(tick.feeGrowthOutsideB.eqn(0));
assert.ok(tick.rewardGrowthsOutside[0].eqn(0));
assert.ok(tick.rewardGrowthsOutside[1].eqn(0));
assert.ok(tick.rewardGrowthsOutside[2].eqn(0));
}
}
});
});
describe("getFallbackTickArrayPublicKey", () => {
const whirlpoolAddress = Keypair.generate().publicKey;
it("ts = 64, a --> b, normal range", async () => {
const tickSpacing = 64;
const aToB = true;
// [ta2: -11264 ][ta1: -5632 ][ta0: 0 ][fallback: 5632 ]
const tickArrays = await SwapUtils.getTickArrays(
128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, 0);
assert.equal(tickArrays[1].startTickIndex, -5632);
assert.equal(tickArrays[2].startTickIndex, -11264);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
const expected = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
5632,
);
assert.ok(result?.toBase58() === expected.publicKey.toBase58());
});
it("ts = 64, a --> b, right most", async () => {
const tickSpacing = 64;
const aToB = true;
// [ta2: 428032 ][ta1: 433664 ][ta0: 439296 ] (no fallback)
const tickArrays = await SwapUtils.getTickArrays(
439296 + 128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, 439296);
assert.equal(tickArrays[1].startTickIndex, 433664);
assert.equal(tickArrays[2].startTickIndex, 428032);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
assert.ok(result === undefined);
});
it("ts = 64, a <-- b, normal range", async () => {
const tickSpacing = 64;
const aToB = false;
// [fallback: -5632 ][ta0: 0 ][ta1: 5632 ][ta2: 11264 ]
const tickArrays = await SwapUtils.getTickArrays(
128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, 0);
assert.equal(tickArrays[1].startTickIndex, 5632);
assert.equal(tickArrays[2].startTickIndex, 11264);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
const expected = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
-5632,
);
assert.ok(result?.toBase58() === expected.publicKey.toBase58());
});
it("ts = 64, a <-- b, left most", async () => {
const tickSpacing = 64;
const aToB = false;
// (no fallback) [ta0: -444928][ta1: -439296][ta2: -433664]
const tickArrays = await SwapUtils.getTickArrays(
-439296 - 128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, -444928);
assert.equal(tickArrays[1].startTickIndex, -439296);
assert.equal(tickArrays[2].startTickIndex, -433664);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
assert.ok(result === undefined);
});
it("ts = 64, a <-- b, shifted", async () => {
const tickSpacing = 64;
const aToB = false;
// [fallback: -444928][ta0: -439296][ta1: -433664][ta2: -428032]
const tickArrays = await SwapUtils.getTickArrays(
-439296 - 32,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, -439296);
assert.equal(tickArrays[1].startTickIndex, -433664);
assert.equal(tickArrays[2].startTickIndex, -428032);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
const expected = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
-444928,
);
assert.ok(result?.toBase58() === expected.publicKey.toBase58());
});
it("ts = 32768, a --> b", async () => {
const tickSpacing = 32768;
const aToB = true;
// [ta0: -2883584][fallback: 0 ]
const tickArrays = await SwapUtils.getTickArrays(
-128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, -2883584);
assert.equal(tickArrays.length, 1);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
const expected = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
0,
);
assert.ok(result?.toBase58() === expected.publicKey.toBase58());
});
it("ts = 32768, a --> b, rightmost", async () => {
const tickSpacing = 32768;
const aToB = true;
// [ta1: -2883584][ta0: 0 ] (no fallback)
const tickArrays = await SwapUtils.getTickArrays(
128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, 0);
assert.equal(tickArrays[1].startTickIndex, -2883584);
assert.equal(tickArrays.length, 2);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
assert.ok(result === undefined);
});
it("ts = 32768, a <-- b", async () => {
const tickSpacing = 32768;
const aToB = false;
// [fallback: -2883584][ta0: 0 ]
const tickArrays = await SwapUtils.getTickArrays(
128,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, 0);
assert.equal(tickArrays.length, 1);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
const expected = PDAUtil.getTickArray(
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
-2883584,
);
assert.ok(result?.toBase58() === expected.publicKey.toBase58());
});
it("ts = 32768, a <-- b, leftmost", async () => {
const tickSpacing = 32768;
const aToB = false;
// (no fallback) [ta0: -2883584][ta1: 0 ]
const tickArrays = await SwapUtils.getTickArrays(
-65536,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
ctx.fetcher,
);
assert.equal(tickArrays[0].startTickIndex, -2883584);
assert.equal(tickArrays[1].startTickIndex, 0);
assert.equal(tickArrays.length, 2);
const result = SwapUtils.getFallbackTickArrayPublicKey(
tickArrays,
tickSpacing,
aToB,
ORCA_WHIRLPOOL_PROGRAM_ID,
whirlpoolAddress,
);
assert.ok(result === undefined);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/tests/sdk/router/router-util-priceImpact.test.ts
|
import { Percentage } from "@orca-so/common-sdk";
import { PublicKey } from "@solana/web3.js";
import * as assert from "assert";
import BN from "bn.js";
import Decimal from "decimal.js";
import { PriceMath, RouterUtils } from "../../../src";
import { U64 } from "../../../src/utils/math/constants";
const maxDecimalAccuracy = 4;
describe("RouterUtil - Price Impact tests", () => {
// Mock a Orca -> USDC ExactIn trade that has no split route and goes through a single hop (ORCA -> USDC)
it("ExactIn, a->b true, single-hop, 1 split", () => {
const params: RouteTestParam = {
amountSpecifiedIsInput: true,
totalAmountIn: new BN("1000000"),
totalAmountOut: new BN("581050"),
subRouteParams: [
{
hops: [
{
aToB: true,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("14082503933855903449"),
amountIn: new BN("1000000"),
amountOut: new BN("581050"),
},
],
},
],
};
const { trade, routes } = buildRouteTest(params);
const impact = RouterUtils.getPriceImpactForRoute(
trade,
routes,
).toDecimalPlaces(maxDecimalAccuracy);
const expect = calculateImpact(params).toDecimalPlaces(maxDecimalAccuracy);
assert.equal(impact.toString(), expect.toString());
});
// Mock a Orca -> USDC ExactOut trade that has no split route and goes through a single hop (ORCA -> USDC)
it("ExactOut, a->b false, single-hop, 1 split", () => {
const params: RouteTestParam = {
amountSpecifiedIsInput: false,
totalAmountIn: new BN("5833496"),
totalAmountOut: new BN("10000000"),
subRouteParams: [
{
hops: [
{
aToB: false,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("14067691597581169278"),
amountIn: new BN("5833496"),
amountOut: new BN("10000000"),
},
],
},
],
};
const { trade, routes } = buildRouteTest(params);
const impact = RouterUtils.getPriceImpactForRoute(
trade,
routes,
).toDecimalPlaces(maxDecimalAccuracy);
const expect = calculateImpact(params).toDecimalPlaces(maxDecimalAccuracy);
assert.equal(impact.toString(), expect.toString());
});
// Mock a ORCA -> USDC trade that has 2 split route and goes through a multi-hop (ORCA -> SOL -> USDC)
it("ExactIn, mix a->b, single & multi-hop, 2 splits", () => {
const params: RouteTestParam = {
amountSpecifiedIsInput: true,
totalAmountIn: new BN("40000000000"),
totalAmountOut: new BN("22277933969"),
subRouteParams: [
{
hops: [
{
aToB: false,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("3363616053614750676"),
amountIn: new BN("32000000000"),
amountOut: new BN("925083736236"),
},
{
aToB: true,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("2567715337494939945"),
amountIn: new BN("925083736236"),
amountOut: new BN("17871834810"),
},
],
},
{
hops: [
{
aToB: true,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("14082503933855903449"),
amountIn: new BN("8000000000"),
amountOut: new BN("4406099159"),
},
],
},
],
};
const { trade, routes } = buildRouteTest(params);
const impact = RouterUtils.getPriceImpactForRoute(
trade,
routes,
).toDecimalPlaces(maxDecimalAccuracy);
const expect = calculateImpact(params).toDecimalPlaces(maxDecimalAccuracy);
assert.equal(impact.toString(), expect.toString());
});
// Mock an ExactOut ORCA -> USDC trade that has 2 split route and goes through a multi-hop (ORCA -> SOL -> USDC)
it("ExactOut, mix a->b, single & multi-hop, 2 splits", () => {
const params: RouteTestParam = {
amountSpecifiedIsInput: false,
totalAmountIn: new BN("64800628033"),
totalAmountOut: new BN("34000000000"),
subRouteParams: [
{
hops: [
{
aToB: true,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("14067691597581169278"),
amountIn: new BN("13107594181"),
amountOut: new BN("6800000000"),
},
],
},
{
hops: [
{
aToB: false,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("3366318822902200326"),
amountIn: new BN("51693033852"),
amountOut: new BN("1403541983350"),
},
{
aToB: true,
feeRate: Percentage.fromFraction(3000, 1000000),
sqrtPrice: new BN("2572953144905521240"),
amountIn: new BN("1403541983350"),
amountOut: new BN("27200000000"),
},
],
},
],
};
const { trade, routes } = buildRouteTest(params);
const impact = RouterUtils.getPriceImpactForRoute(
trade,
routes,
).toDecimalPlaces(maxDecimalAccuracy);
const expect = calculateImpact(params).toDecimalPlaces(maxDecimalAccuracy);
assert.equal(impact.toString(), expect.toString());
});
// NOTE: The precision kept in these calculation slightly differs from the U64 calculation that we get from the RouterUtil function.
function calculateImpact(params: RouteTestParam): Decimal {
const { amountSpecifiedIsInput, totalAmountIn, totalAmountOut } = params;
const finalBaseValue = params.subRouteParams
.map((subRoute) => {
const { hops } = subRoute;
const directionalHops = amountSpecifiedIsInput
? hops
: hops.slice().reverse();
const hopResults: Decimal[] = new Array(hops.length);
directionalHops.forEach((hop, index) => {
const { aToB, feeRate, sqrtPrice, amountIn, amountOut } = hop;
const directionalSqrtPrice = aToB
? new Decimal(sqrtPrice.toString())
: new Decimal(PriceMath.invertSqrtPriceX64(sqrtPrice).toString());
const directionalPrice = directionalSqrtPrice
.pow(2)
.div(U64.toString())
.div(U64.toString());
if (amountSpecifiedIsInput) {
const amountInDec =
index === 0
? new Decimal(amountIn.toString())
: hopResults[index - 1];
const amountOutDec = amountInDec
.times(new Decimal(1).sub(feeRate.toDecimal()))
.times(directionalPrice);
hopResults[index] = amountOutDec.round();
} else {
const amountOutDec =
index === 0
? new Decimal(amountOut.toString())
: hopResults[index - 1];
const amountInDec = amountOutDec
.div(new Decimal(1).sub(feeRate.toDecimal()))
.div(directionalPrice);
hopResults[index] = amountInDec.round();
}
});
return hopResults[hops.length - 1];
})
.reduce((acc, cur) => acc.add(cur), new Decimal(0));
if (amountSpecifiedIsInput) {
const totalAmountOutDec = new Decimal(totalAmountOut.toString());
return finalBaseValue.sub(totalAmountOutDec).div(finalBaseValue).mul(100);
} else {
const totalAmountInDec = new Decimal(totalAmountIn.toString());
return totalAmountInDec
.sub(finalBaseValue)
.div(totalAmountInDec)
.mul(100);
}
}
type TradeHopTestParam = {
aToB: boolean;
feeRate: Percentage;
sqrtPrice: BN;
amountIn: BN;
amountOut: BN;
};
type SubRouteTestParam = {
hops: TradeHopTestParam[];
};
type RouteTestParam = {
amountSpecifiedIsInput: boolean;
subRouteParams: SubRouteTestParam[];
totalAmountIn: BN;
totalAmountOut: BN;
};
function buildRouteTest(params: RouteTestParam) {
return {
trade: {
tokenIn: "orcaEKTdK7LKz57vaAYr9QeNsVEPfiu6QeMU1kektZE",
tokenOut: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
tradeAmount: new BN(0),
amountSpecifiedIsInput: params.amountSpecifiedIsInput,
},
routes: {
subRoutes: params.subRouteParams.map((subRouteParam) => {
return {
hopQuotes: subRouteParam.hops.map((hopParam) => {
return {
amountIn: hopParam.amountIn,
amountOut: hopParam.amountOut,
whirlpool: PublicKey.default,
inputMint: PublicKey.default,
outputMint: PublicKey.default,
mintA: PublicKey.default,
mintB: PublicKey.default,
vaultA: PublicKey.default,
vaultB: PublicKey.default,
quote: {
amount: new BN(0),
otherAmountThreshold: new BN(0),
sqrtPriceLimit: new BN(0),
amountSpecifiedIsInput: params.amountSpecifiedIsInput,
aToB: hopParam.aToB,
tickArray0: PublicKey.default,
tickArray1: PublicKey.default,
tickArray2: PublicKey.default,
estimatedAmountIn: new BN(0),
estimatedAmountOut: new BN(0),
estimatedEndTickIndex: 0,
estimatedEndSqrtPrice: new BN(0),
estimatedFeeAmount: new BN(0),
transferFee: {
deductingFromEstimatedAmountIn: new BN(0),
deductedFromEstimatedAmountOut: new BN(0),
},
},
snapshot: {
aToB: hopParam.aToB,
feeRate: hopParam.feeRate,
sqrtPrice: hopParam.sqrtPrice,
},
};
}),
path: {
startTokenMint: "startTokenMint",
endTokenMint: "endTokenMint",
edges: [],
},
splitPercent: 30,
amountIn: new BN(0),
amountOut: new BN(0),
};
}),
totalAmountIn: params.totalAmountIn,
totalAmountOut: params.totalAmountOut,
},
};
}
});
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/context.ts
|
import type { Idl } from "@coral-xyz/anchor";
import { AnchorProvider, Program } from "@coral-xyz/anchor";
import type {
BuildOptions,
LookupTableFetcher,
TransactionBuilderOptions,
Wallet,
WrappedSolAccountCreateMethod,
} from "@orca-so/common-sdk";
import type {
Commitment,
Connection,
PublicKey,
SendOptions,
} from "@solana/web3.js";
import type { Whirlpool } from "./artifacts/whirlpool";
import WhirlpoolIDL from "./artifacts/whirlpool.json";
import type { WhirlpoolAccountFetcherInterface } from "./network/public";
import { buildDefaultAccountFetcher } from "./network/public";
import { contextOptionsToBuilderOptions } from "./utils/txn-utils";
/**
* Default settings used when interacting with transactions.
* @category Core
*/
export type WhirlpoolContextOpts = {
userDefaultBuildOptions?: Partial<BuildOptions>;
userDefaultSendOptions?: Partial<SendOptions>;
userDefaultConfirmCommitment?: Commitment;
accountResolverOptions?: AccountResolverOptions;
};
/**
* Default settings used when resolving token accounts.
* @category Core
*/
export type AccountResolverOptions = {
createWrappedSolAccountMethod: WrappedSolAccountCreateMethod;
allowPDAOwnerAddress: boolean;
};
const DEFAULT_ACCOUNT_RESOLVER_OPTS: AccountResolverOptions = {
createWrappedSolAccountMethod: "keypair",
allowPDAOwnerAddress: false,
};
/**
* Context for storing environment classes and objects for usage throughout the SDK
* @category Core
*/
export class WhirlpoolContext {
readonly connection: Connection;
readonly wallet: Wallet;
readonly program: Program<Whirlpool>;
readonly provider: AnchorProvider;
readonly fetcher: WhirlpoolAccountFetcherInterface;
readonly lookupTableFetcher: LookupTableFetcher | undefined;
readonly opts: WhirlpoolContextOpts;
readonly txBuilderOpts: TransactionBuilderOptions | undefined;
readonly accountResolverOpts: AccountResolverOptions;
public static from(
connection: Connection,
wallet: Wallet,
programId: PublicKey,
fetcher: WhirlpoolAccountFetcherInterface = buildDefaultAccountFetcher(
connection,
),
lookupTableFetcher?: LookupTableFetcher,
opts: WhirlpoolContextOpts = {},
): WhirlpoolContext {
const anchorProvider = new AnchorProvider(connection, wallet, {
commitment: opts.userDefaultConfirmCommitment || "confirmed",
preflightCommitment: opts.userDefaultConfirmCommitment || "confirmed",
});
const program = new Program(WhirlpoolIDL as Idl, programId, anchorProvider);
return new WhirlpoolContext(
anchorProvider,
anchorProvider.wallet,
program,
fetcher,
lookupTableFetcher,
opts,
);
}
public static fromWorkspace(
provider: AnchorProvider,
program: Program,
fetcher: WhirlpoolAccountFetcherInterface = buildDefaultAccountFetcher(
provider.connection,
),
lookupTableFetcher?: LookupTableFetcher,
opts: WhirlpoolContextOpts = {},
) {
return new WhirlpoolContext(
provider,
provider.wallet,
program,
fetcher,
lookupTableFetcher,
opts,
);
}
public static withProvider(
provider: AnchorProvider,
programId: PublicKey,
fetcher: WhirlpoolAccountFetcherInterface = buildDefaultAccountFetcher(
provider.connection,
),
lookupTableFetcher?: LookupTableFetcher,
opts: WhirlpoolContextOpts = {},
): WhirlpoolContext {
const program = new Program(WhirlpoolIDL as Idl, programId, provider);
return new WhirlpoolContext(
provider,
provider.wallet,
program,
fetcher,
lookupTableFetcher,
opts,
);
}
public constructor(
provider: AnchorProvider,
wallet: Wallet,
program: Program,
fetcher: WhirlpoolAccountFetcherInterface,
lookupTableFetcher?: LookupTableFetcher,
opts: WhirlpoolContextOpts = {},
) {
this.connection = provider.connection;
this.wallet = wallet;
// It's a hack but it works on Anchor workspace *shrug*
this.program = program as unknown as Program<Whirlpool>;
this.provider = provider;
this.fetcher = fetcher;
this.lookupTableFetcher = lookupTableFetcher;
this.opts = opts;
this.txBuilderOpts = contextOptionsToBuilderOptions(this.opts);
this.accountResolverOpts =
opts.accountResolverOptions ?? DEFAULT_ACCOUNT_RESOLVER_OPTS;
}
// TODO: Add another factory method to build from on-chain IDL
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/whirlpool-client.ts
|
import type { Address } from "@coral-xyz/anchor";
import type { Percentage, TransactionBuilder } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { WhirlpoolContext } from "./context";
import { WhirlpoolClientImpl } from "./impl/whirlpool-client-impl";
import type { DevFeeSwapInput, SwapInput } from "./instructions";
import type {
WhirlpoolAccountFetchOptions,
WhirlpoolAccountFetcherInterface,
} from "./network/public/fetcher";
import type { WhirlpoolRouter } from "./router/public";
import type {
DecreaseLiquidityInput,
IncreaseLiquidityInput,
PositionData,
TickData,
WhirlpoolData,
} from "./types/public";
import type {
TokenAccountInfo,
TokenInfo,
WhirlpoolRewardInfo,
} from "./types/public/client-types";
import type Decimal from "decimal.js";
/**
* Helper class to help interact with Whirlpool Accounts with a simpler interface.
*
* @category WhirlpoolClient
*/
export interface WhirlpoolClient {
/**
* Get this client's WhirlpoolContext object
* @return a WhirlpoolContext object
*/
getContext: () => WhirlpoolContext;
/**
* Get an WhirlpoolAccountCacheInterface to fetch and cache Whirlpool accounts
* @return an WhirlpoolAccountCacheInterface instance
*/
getFetcher: () => WhirlpoolAccountFetcherInterface;
/**
* Get a WhirlpoolRouter to help generate the best prices when transacting across a set of pools.
* @param poolAddresses the addresses of the Whirlpool account addresses to route through
* @returns a {@link WhirlpoolRouter} instance
* @deprecated WhirlpoolRouter will be removed in the future release. Please use endpoint which provides qoutes.
*/
getRouter: (poolAddresses: Address[]) => Promise<WhirlpoolRouter>;
/**
* Get a Whirlpool object to interact with the Whirlpool account at the given address.
* @param poolAddress the address of the Whirlpool account
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return a Whirlpool object to interact with
*/
getPool: (
poolAddress: Address,
opts?: WhirlpoolAccountFetchOptions,
) => Promise<Whirlpool>;
/**
* Get a list of Whirlpool objects matching the provided list of addresses.
* @param poolAddresses the addresses of the Whirlpool accounts
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return a list of Whirlpool objects to interact with
*/
getPools: (
poolAddresses: Address[],
opts?: WhirlpoolAccountFetchOptions,
) => Promise<Whirlpool[]>;
/**
* Get a Position object to interact with the Position account at the given address.
* @param positionAddress the address of the Position account
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return a Position object to interact with.
* @throws error when address does not return a Position account.
*/
getPosition: (
positionAddress: Address,
opts?: WhirlpoolAccountFetchOptions,
) => Promise<Position>;
/**
* Get a list of Position objects to interact with the Position account at the given addresses.
* @param positionAddress the addresses of the Position accounts
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return a Record object between account address and Position. If an address is not a Position account, it will be null.
*/
getPositions: (
positionAddresses: Address[],
opts?: WhirlpoolAccountFetchOptions,
) => Promise<Record<string, Position | null>>;
/**
* Collect all fees and rewards from a list of positions.
* @experimental
* @param positionAddress the addresses of the Position accounts to collect fee & rewards from.
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions.
*/
collectFeesAndRewardsForPositions: (
positionAddresses: Address[],
opts?: WhirlpoolAccountFetchOptions,
) => Promise<TransactionBuilder[]>;
/**
* Create a Whirlpool account for a group of token A, token B and tick spacing
* @param whirlpoolConfig the address of the whirlpool config
* @param tokenMintA the address of the token A
* @param tokenMintB the address of the token B
* @param initialPrice the initial price of the pool (as x token B per 1 token A)
* @param funder the account to debit SOL from to fund the creation of the account(s)
* @return `poolKey`: The public key of the newly created whirlpool account. `tx`: The transaction containing instructions for the on-chain operations.
* @throws error when the tokens are not in the canonical byte-based ordering. To resolve this, invert the token order and the initialTick (see `TickUtil.invertTick()`, `PriceMath.invertSqrtPriceX64()`, or `PriceMath.invertPrice()`).
*/
createSplashPool: (
whirlpoolsConfig: Address,
tokenMintA: Address,
tokenMintB: Address,
initialPrice: Decimal,
funder: Address,
) => Promise<{ poolKey: PublicKey; tx: TransactionBuilder }>;
/**
* Create a Whirlpool account for a group of token A, token B and tick spacing
* @param whirlpoolConfig the address of the whirlpool config
* @param tokenMintA the address of the token A
* @param tokenMintB the address of the token B
* @param tickSpacing the space between two ticks in the tick array
* @param initialTick the initial tick that the pool is set to (derived from initial price)
* @param funder the account to debit SOL from to fund the creation of the account(s)
* @return `poolKey`: The public key of the newly created whirlpool account. `tx`: The transaction containing instructions for the on-chain operations.
* @throws error when the tokens are not in the canonical byte-based ordering. To resolve this, invert the token order and the initialTick (see `TickUtil.invertTick()`, `PriceMath.invertSqrtPriceX64()`, or `PriceMath.invertPrice()`).
*/
createPool: (
whirlpoolsConfig: Address,
tokenMintA: Address,
tokenMintB: Address,
tickSpacing: number,
initialTick: number,
funder: Address,
) => Promise<{ poolKey: PublicKey; tx: TransactionBuilder }>;
/**
* Collect protocol fees from a list of pools
* @param poolAddresses the addresses of the Whirlpool accounts to collect protocol fees from
* @returns A transaction builder to resolve ATA for tokenA and tokenB if needed, and collect protocol fees for all pools
*/
collectProtocolFeesForPools: (
poolAddresses: Address[],
) => Promise<TransactionBuilder>;
}
/**
* Construct a WhirlpoolClient instance to help interact with Whirlpools accounts with.
*
* @category WhirlpoolClient
* @param ctx - WhirlpoolContext object
* @returns a WhirlpoolClient instance to help with interacting with Whirlpools accounts.
*/
export function buildWhirlpoolClient(ctx: WhirlpoolContext): WhirlpoolClient {
return new WhirlpoolClientImpl(ctx);
}
/**
* Helper class to interact with a Whirlpool account and build complex transactions.
* @category WhirlpoolClient
*/
export interface Whirlpool {
/**
* Return the address for this Whirlpool instance.
* @return the PublicKey for this Whirlpool instance.
*/
getAddress: () => PublicKey;
/**
* Return the most recently fetched Whirlpool account data.
* @return most recently fetched WhirlpoolData for this address.
*/
getData: () => WhirlpoolData;
/**
* Fetch and return the most recently fetched Whirlpool account data.
* @return the most up to date WhirlpoolData for this address.
*/
refreshData: () => Promise<WhirlpoolData>;
/**
* Get the TokenInfo for token A of this pool.
* @return TokenInfo for token A
*/
getTokenAInfo: () => TokenInfo;
/**
* Get the TokenInfo for token B of this pool.
* @return TokenInfo for token B
*/
getTokenBInfo: () => TokenInfo;
/**
* Get the TokenAccountInfo for token vault A of this pool.
* @return TokenAccountInfo for token vault A
*/
getTokenVaultAInfo: () => TokenAccountInfo;
/**
* Get the TokenAccountInfo for token vault B of this pool.
* @return TokenAccountInfo for token vault B
*/
getTokenVaultBInfo: () => TokenAccountInfo;
/**
* Get the WhirlpoolRewardInfos for this pool.
* @return Array of 3 WhirlpoolRewardInfos. However, not all of them may be initialized. Use the initialized field on WhirlpoolRewardInfo to check if the reward is active.
*/
getRewardInfos: () => WhirlpoolRewardInfo[];
/**
* Initialize a set of tick-arrays that encompasses the provided ticks.
*
* If `funder` is provided, the funder wallet has to sign this transaction.
*
* @param ticks - A group of ticks that define the desired tick-arrays to initialize. If the tick's array has been initialized, it will be ignored.
* @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.
* @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts
* @return a transaction that will initialize the defined tick-arrays if executed. Return null if all of the tick's arrays are initialized.
*/
initTickArrayForTicks: (
ticks: number[],
funder?: Address,
opts?: WhirlpoolAccountFetchOptions,
) => Promise<TransactionBuilder | null>;
/**
* Open and fund a position on this Whirlpool.
*
* User has to ensure the TickArray for tickLower and tickUpper has been initialized prior to calling this function.
*
* If `wallet` or `funder` is provided, those wallets have to sign this transaction.
*
* @param tickLower - the tick index for the lower bound of this position
* @param tickUpper - the tick index for the upper bound of this position
* @param liquidityInput - an InputLiquidityInput type to define the desired liquidity amount to deposit
* @param wallet - the wallet to withdraw tokens to deposit into the position and house the position token. If null, the WhirlpoolContext wallet is used.
* @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.
* @param positionMint - the mint address of the position token to be created. If null, a new mint address will be created.
* @param tokenProgramId - the token program id to use for the position token. The default is TOKEN_PROGRAM_ID.
* @return `positionMint` - the position to be created. `tx` - The transaction containing the instructions to perform the operation on chain.
*/
openPosition: (
tickLower: number,
tickUpper: number,
liquidityInput: IncreaseLiquidityInput,
wallet?: Address,
funder?: Address,
positionMint?: PublicKey,
tokenProgramId?: PublicKey,
) => Promise<{ positionMint: PublicKey; tx: TransactionBuilder }>;
/**
* Open and fund a position with meta-data on this Whirlpool.
*
* User has to ensure the TickArray for tickLower and tickUpper has been initialized prior to calling this function.
*
* If `wallet` or `funder` is provided, the wallet owners have to sign this transaction.
*
* @param tickLower - the tick index for the lower bound of this position
* @param tickUpper - the tick index for the upper bound of this position
* @param liquidityInput - input that defines the desired liquidity amount and maximum tokens willing to be to deposited.
* @param wallet - the wallet to withdraw tokens to deposit into the position and house the position token. If null, the WhirlpoolContext wallet is used.
* @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.
* @param positionMint - the mint address of the position token to be created. If null, a new mint address will be created.
* @param tokenProgramId - the token program id to use for the position token. The default is TOKEN_PROGRAM_ID.
* @return `positionMint` - the position to be created. `tx` - The transaction containing the instructions to perform the operation on chain.
*/
openPositionWithMetadata: (
tickLower: number,
tickUpper: number,
liquidityInput: IncreaseLiquidityInput,
wallet?: Address,
funder?: Address,
positionMint?: PublicKey,
tokenProgramId?: PublicKey,
) => Promise<{ positionMint: PublicKey; tx: TransactionBuilder }>;
/**
* Withdraw all tokens from a position, close the account and burn the position token.
*
* Users have to collect all fees and rewards from this position prior to closing the account.
*
* If `positionWallet`, `payer` is provided, the wallet owner has to sign this transaction.
*
* @param positionAddress - The address of the position account.
* @param slippageTolerance - The amount of slippage the caller is willing to accept when withdrawing liquidity.
* @param destinationWallet - The wallet that the tokens withdrawn and rent lamports will be sent to. If null, the WhirlpoolContext wallet is used.
* @param positionWallet - The wallet that houses the position token that corresponds to this position address. If null, the WhirlpoolContext wallet is used.
* @param payer - the wallet that will fund the cost needed to initialize the token ATA accounts. If null, the WhirlpoolContext wallet is used.
* @param usePriceSlippage - if true, use the price slippage to calculate the minimum tokens to receive. If false, use the token slippage.
* @return transactions that will close the position. The transactions must be executed serially.
*/
closePosition: (
positionAddress: Address,
slippageTolerance: Percentage,
destinationWallet?: Address,
positionWallet?: Address,
payer?: Address,
usePriceSlippage?: boolean,
) => Promise<TransactionBuilder[]>;
/**
* Perform a swap between tokenA and tokenB on this pool.
*
* @param input - A quote on the desired tokenIn and tokenOut for this swap. Use {@link swapQuoteWithParams} or other swap quote functions to generate this object.
* @param wallet - The wallet that tokens will be withdrawn and deposit into. If null, the WhirlpoolContext wallet is used.
* @return a transaction that will perform the swap once executed.
*/
swap: (input: SwapInput, wallet?: PublicKey) => Promise<TransactionBuilder>;
/**
* Collect a developer fee and perform a swap between tokenA and tokenB on this pool.
*
* @param input - A quote on the desired tokenIn and tokenOut for this swap. Use {@link swapQuoteByInputTokenWithDevFees} to generate this object.
* @param devFeeWallet - The wallet that developer fees will be deposited into.
* @param wallet - The wallet that swap tokens will be withdrawn and deposit into. If null, the WhirlpoolContext wallet is used.
* @param payer - The wallet that will fund the cost needed to initialize the dev wallet token ATA accounts. If null, the WhirlpoolContext wallet is used.
* @return a transaction that will perform the swap once executed.
*/
swapWithDevFees: (
input: DevFeeSwapInput,
devFeeWallet: PublicKey,
wallet?: PublicKey,
payer?: PublicKey,
) => Promise<TransactionBuilder>;
}
/**
* Helper class to interact with a Position account and build complex transactions.
* @category WhirlpoolClient
*/
export interface Position {
/**
* Return the address for this Whirlpool instance.
* @return the PublicKey for this Whirlpool instance.
*/
getAddress: () => PublicKey;
/**
* Return the program address owning the position token.
* @return the PublicKey for the program address owning the position token.
*/
getPositionMintTokenProgramId: () => PublicKey;
/**
* Return the most recently fetched Position account data.
* @return most recently fetched PositionData for this address.
*/
getData: () => PositionData;
/**
* Return the most recently fetched Whirlpool account data for this position.
* @return most recently fetched WhirlpoolData for this position.
*/
getWhirlpoolData: () => WhirlpoolData;
/**
* Return the most recently fetched TickData account data for this position's lower tick.
* @return most recently fetched TickData for this position's lower tick.
*/
getLowerTickData: () => TickData;
/**
* Return the most recently fetched TickData account data for this position's upper tick.
* @return most recently fetched TickData for this position's upper tick.
*/
getUpperTickData: () => TickData;
/**
* Fetch and return the most recently fetched Position account data.
* @return the most up to date PositionData for this address.
*/
refreshData: () => Promise<PositionData>;
/**
* Deposit additional tokens into this postiion.
* The wallet must contain the position token and the necessary token A & B to complete the deposit.
* If `positionWallet` and `wallet` is provided, the wallet owners have to sign this transaction.
*
* @param liquidityInput - input that defines the desired liquidity amount and maximum tokens willing to be to deposited.
* @param resolveATA - if true, add instructions to create associated token accounts for tokenA,B for the destinationWallet if necessary. (RPC call required)
* @param wallet - to withdraw tokens to deposit into the position. If null, the WhirlpoolContext wallet is used.
* @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.
* @param ataPayer - wallet that will fund the creation of the new associated token accounts
* @return the transaction that will deposit the tokens into the position when executed.
*/
increaseLiquidity: (
liquidityInput: IncreaseLiquidityInput,
resolveATA?: boolean,
wallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
) => Promise<TransactionBuilder>;
/**
* Withdraw liquidity from this position.
*
* If `positionWallet` is provided, the wallet owners have to sign this transaction.
*
* @param liquidityInput - input that defines the desired liquidity amount and minimum tokens willing to be to withdrawn from the position.
* @param resolveATA - if true, add instructions to create associated token accounts for tokenA,B for the destinationWallet if necessary. (RPC call required)
* @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.
* @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.
* @param ataPayer - wallet that will fund the creation of the new associated token accounts
* @return the transaction that will deposit the tokens into the position when executed.
*/
decreaseLiquidity: (
liquidityInput: DecreaseLiquidityInput,
resolveATA?: boolean,
destinationWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
) => Promise<TransactionBuilder>;
/**
* Collect fees from this position
*
* If `positionWallet` is provided, the wallet owners have to sign this transaction.
*
* @param updateFeesAndRewards - if true, add instructions to refresh the accumulated fees and rewards data (default to true unless you know that the collect fees quote and on-chain data match for the "feeOwedA" and "feeOwedB" fields in the Position account)
* @param ownerTokenAccountMap - A record that maps a given mint to the owner's token account for that mint (if an entry doesn't exist, it will be automatically resolved)
* @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.
* @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.
* @param ataPayer - wallet that will fund the creation of the new associated token accounts
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return the transaction that will collect fees from the position
*/
collectFees: (
updateFeesAndRewards?: boolean,
ownerTokenAccountMap?: Partial<Record<string, Address>>,
destinationWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
opts?: WhirlpoolAccountFetchOptions,
) => Promise<TransactionBuilder>;
/**
* Collect rewards from this position
*
* If `positionWallet` is provided, the wallet owners have to sign this transaction.
*
* @param rewardsToCollect - reward mints to collect (omitting this parameter means all rewards will be collected)
* @param updateFeesAndRewards - if true, add instructions to refresh the accumulated fees and rewards data (default to true unless you know that the collect fees quote and on-chain data match for the "feeOwedA" and "feeOwedB" fields in the Position account)
* @param ownerTokenAccountMap - A record that maps a given mint to the owner's token account for that mint (if an entry doesn't exist, it will be automatically resolved)
* @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.
* @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.
* @param ataPayer - wallet that will fund the creation of the new associated token accounts
* @param opts an options object to define fetch and cache options when accessing on-chain accounts
* @return the transactions that will collect rewards from the position. The transactions must be executed serially.
*/
collectRewards: (
rewardsToCollect?: Address[],
updateFeesAndRewards?: boolean,
ownerTokenAccountMap?: Partial<Record<string, Address>>,
destinationWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
opts?: WhirlpoolAccountFetchOptions,
) => Promise<TransactionBuilder[]>;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/index.ts
|
import Decimal from "decimal.js";
export * from "./context";
export * from "./impl/position-impl";
export * from "./ix";
export * from "./network/public";
export * from "./prices";
export * from "./quotes/public";
export * from "./router/public";
export * from "./types/public";
export * from "./types/public/anchor-types";
export * from "./utils/public";
export * from "./whirlpool-client";
// Global rules for Decimals
// - 40 digits of precision for the largest number
// - 20 digits of precision for the smallest number
// - Always round towards 0 to mirror smart contract rules
Decimal.set({ precision: 40, toExpPos: 40, toExpNeg: -20, rounding: 1 });
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { PDA } from "@orca-so/common-sdk";
import type { Whirlpool } from "./artifacts/whirlpool";
import * as ix from "./instructions";
/**
* Instruction builders for the Whirlpools program.
*
* @category Core
*/
export class WhirlpoolIx {
/**
* Initializes a WhirlpoolsConfig account that hosts info & authorities
* required to govern a set of Whirlpools.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitConfigParams object
* @returns - Instruction to perform the action.
*/
public static initializeConfigIx(
program: Program<Whirlpool>,
params: ix.InitConfigParams,
) {
return ix.initializeConfigIx(program, params);
}
/**
* Initializes a fee tier account usable by Whirlpools in this WhirlpoolsConfig space.
*
* Special Errors
* `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitFeeTierParams object
* @returns - Instruction to perform the action.
*/
public static initializeFeeTierIx(
program: Program<Whirlpool>,
params: ix.InitFeeTierParams,
) {
return ix.initializeFeeTierIx(program, params);
}
/**
* Initializes a tick_array account to represent a tick-range in a Whirlpool.
*
* Special Errors
* `InvalidTokenMintOrder` - The order of mints have to be ordered by
* `SqrtPriceOutOfBounds` - provided initial_sqrt_price is not between 2^-64 to 2^64
*
* @param program - program object containing services required to generate the instruction
* @param params - InitPoolParams object
* @returns - Instruction to perform the action.
*/
public static initializePoolIx(
program: Program<Whirlpool>,
params: ix.InitPoolParams,
) {
return ix.initializePoolIx(program, params);
}
/**
* Initialize reward for a Whirlpool. A pool can only support up to a set number of rewards.
* The initial emissionsPerSecond is set to 0.
*
* #### Special Errors
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS, or all reward slots for this pool has been initialized.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitializeRewardParams object
* @returns - Instruction to perform the action.
*/
public static initializeRewardIx(
program: Program<Whirlpool>,
params: ix.InitializeRewardParams,
) {
return ix.initializeRewardIx(program, params);
}
/**
* Initializes a TickArray account.
*
* #### Special Errors
* `InvalidStartTick` - if the provided start tick is out of bounds or is not a multiple of TICK_ARRAY_SIZE * tick spacing.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitTickArrayParams object
* @returns - Instruction to perform the action.
*/
public static initTickArrayIx(
program: Program<Whirlpool>,
params: ix.InitTickArrayParams,
) {
return ix.initTickArrayIx(program, params);
}
/**
* Open a position in a Whirlpool. A unique token will be minted to represent the position in the users wallet.
* The position will start off with 0 liquidity.
*
* #### Special Errors
* `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.
*
* @param program - program object containing services required to generate the instruction
* @param params - OpenPositionParams object
* @returns - Instruction to perform the action.
*/
public static openPositionIx(
program: Program<Whirlpool>,
params: ix.OpenPositionParams,
) {
return ix.openPositionIx(program, params);
}
/**
* Open a position in a Whirlpool. A unique token will be minted to represent the position
* in the users wallet. Additional Metaplex metadata is appended to identify the token.
* The position will start off with 0 liquidity.
*
* #### Special Errors
* `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.
*
* @param program - program object containing services required to generate the instruction
* @param params - OpenPositionParams object and a derived PDA that hosts the position's metadata.
* @returns - Instruction to perform the action.
*/
public static openPositionWithMetadataIx(
program: Program<Whirlpool>,
params: ix.OpenPositionParams & { metadataPda: PDA },
) {
return ix.openPositionWithMetadataIx(program, params);
}
/**
* Add liquidity to a position in the Whirlpool. This call also updates the position's accrued fees and rewards.
*
* #### Special Errors
* `LiquidityZero` - Provided liquidity amount is zero.
* `LiquidityTooHigh` - Provided liquidity exceeds u128::max.
* `TokenMaxExceeded` - The required token to perform this operation exceeds the user defined amount.
*
* @param program - program object containing services required to generate the instruction
* @param params - IncreaseLiquidityParams object
* @returns - Instruction to perform the action.
*/
public static increaseLiquidityIx(
program: Program<Whirlpool>,
params: ix.IncreaseLiquidityParams,
) {
return ix.increaseLiquidityIx(program, params);
}
/**
* Remove liquidity to a position in the Whirlpool. This call also updates the position's accrued fees and rewards.
*
* #### Special Errors
* - `LiquidityZero` - Provided liquidity amount is zero.
* - `LiquidityTooHigh` - Provided liquidity exceeds u128::max.
* - `TokenMinSubceeded` - The required token to perform this operation subceeds the user defined amount.
*
* @param program - program object containing services required to generate the instruction
* @param params - DecreaseLiquidityParams object
* @returns - Instruction to perform the action.
*/
public static decreaseLiquidityIx(
program: Program<Whirlpool>,
params: ix.DecreaseLiquidityParams,
) {
return ix.decreaseLiquidityIx(program, params);
}
/**
* Close a position in a Whirlpool. Burns the position token in the owner's wallet.
*
* @param program - program object containing services required to generate the instruction
* @param params - ClosePositionParams object
* @returns - Instruction to perform the action.
*/
public static closePositionIx(
program: Program<Whirlpool>,
params: ix.ClosePositionParams,
) {
return ix.closePositionIx(program, params);
}
/**
* Perform a swap in this Whirlpool
*
* #### Special Errors
* - `ZeroTradableAmount` - User provided parameter `amount` is 0.
* - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.
* - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.
* - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.
* - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.
* - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.
* - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.
* - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.
* - `AmountCalcOverflow` - The required token amount exceeds the u64 range.
* - `AmountRemainingOverflow` - Result does not match the specified amount.
* - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool.
* - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false.
*
* ### Parameters
* @param program - program object containing services required to generate the instruction
* @param params - {@link SwapParams}
* @returns - Instruction to perform the action.
*/
public static swapIx(program: Program<Whirlpool>, params: ix.SwapParams) {
return ix.swapIx(program, params);
}
/**
* Perform a two-hop-swap in this Whirlpool
*
* #### Special Errors
* - `ZeroTradableAmount` - User provided parameter `amount` is 0.
* - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.
* - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.
* - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.
* - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.
* - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.
* - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.
* - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.
* - `DuplicateTwoHopPool` - Swaps on the same pool are not allowed.
* - `InvalidIntermediaryMint` - The first and second leg of the hops do not share a common token.
* - `AmountCalcOverflow` - The required token amount exceeds the u64 range.
* - `AmountRemainingOverflow` - Result does not match the specified amount.
* - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool.
* - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false.
* - `IntermediateTokenAmountMismatch` - The amount of tokens received from the first hop does not match the amount sent to the second hop.
*
* ### Parameters
* @param program - program object containing services required to generate the instruction
* @param params - TwoHopSwapParams object
* @returns - Instruction to perform the action.
*/
public static twoHopSwapIx(
program: Program<Whirlpool>,
params: ix.TwoHopSwapParams,
) {
return ix.twoHopSwapIx(program, params);
}
/**
* Update the accrued fees and rewards for a position.
*
* #### Special Errors
* `TickNotFound` - Provided tick array account does not contain the tick for this position.
* `LiquidityZero` - Position has zero liquidity and therefore already has the most updated fees and reward values.
*
* @param program - program object containing services required to generate the instruction
* @param params - UpdateFeesAndRewardsParams object
* @returns - Instruction to perform the action.
*/
public static updateFeesAndRewardsIx(
program: Program<Whirlpool>,
params: ix.UpdateFeesAndRewardsParams,
) {
return ix.updateFeesAndRewardsIx(program, params);
}
/**
* Collect fees accrued for this position.
* Call updateFeesAndRewards before this to update the position to the newest accrued values.
*
* @param program - program object containing services required to generate the instruction
* @param params - CollectFeesParams object
* @returns - Instruction to perform the action.
*/
public static collectFeesIx(
program: Program<Whirlpool>,
params: ix.CollectFeesParams,
) {
return ix.collectFeesIx(program, params);
}
/**
* Collect protocol fees accrued in this Whirlpool.
*
* @param program - program object containing services required to generate the instruction
* @param params - CollectProtocolFeesParams object
* @returns - Instruction to perform the action.
*/
public static collectProtocolFeesIx(
program: Program<Whirlpool>,
params: ix.CollectProtocolFeesParams,
) {
return ix.collectProtocolFeesIx(program, params);
}
/**
* Collect rewards accrued for this reward index in a position.
* Call updateFeesAndRewards before this to update the position to the newest accrued values.
*
* @param program - program object containing services required to generate the instruction
* @param params - CollectRewardParams object
* @returns - Instruction to perform the action.
*/
public static collectRewardIx(
program: Program<Whirlpool>,
params: ix.CollectRewardParams,
) {
return ix.collectRewardIx(program, params);
}
/**
* Sets the fee authority to collect protocol fees for a WhirlpoolsConfig.
* Only the current collect protocol fee authority has permission to invoke this instruction.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetCollectProtocolFeesAuthorityParams object
* @returns - Instruction to perform the action.
*/
public static setCollectProtocolFeesAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetCollectProtocolFeesAuthorityParams,
) {
return ix.setCollectProtocolFeesAuthorityIx(program, params);
}
/**
* Updates a fee tier account with a new default fee rate. The new rate will not retroactively update
* initialized pools.
*
* #### Special Errors
* - `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetDefaultFeeRateParams object
* @returns - Instruction to perform the action.
*/
public static setDefaultFeeRateIx(
program: Program<Whirlpool>,
params: ix.SetDefaultFeeRateParams,
) {
return ix.setDefaultFeeRateIx(program, params);
}
/**
* Updates a WhirlpoolsConfig with a new default protocol fee rate. The new rate will not retroactively update
* initialized pools.
*
* #### Special Errors
* - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetDefaultFeeRateParams object
* @returns - Instruction to perform the action.
*/
public static setDefaultProtocolFeeRateIx(
program: Program<Whirlpool>,
params: ix.SetDefaultProtocolFeeRateParams,
) {
return ix.setDefaultProtocolFeeRateIx(program, params);
}
/**
* Sets the fee authority for a WhirlpoolsConfig.
* The fee authority can set the fee & protocol fee rate for individual pools or set the default fee rate for newly minted pools.
* Only the current fee authority has permission to invoke this instruction.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetFeeAuthorityParams object
* @returns - Instruction to perform the action.
*/
public static setFeeAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetFeeAuthorityParams,
) {
return ix.setFeeAuthorityIx(program, params);
}
/**
* Sets the fee rate for a Whirlpool.
* Only the current fee authority has permission to invoke this instruction.
*
* #### Special Errors
* - `FeeRateMaxExceeded` - If the provided fee_rate exceeds MAX_FEE_RATE.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetFeeRateParams object
* @returns - Instruction to perform the action.
*/
public static setFeeRateIx(
program: Program<Whirlpool>,
params: ix.SetFeeRateParams,
) {
return ix.setFeeRateIx(program, params);
}
/**
* Sets the protocol fee rate for a Whirlpool.
* Only the current fee authority has permission to invoke this instruction.
*
* #### Special Errors
* - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetFeeRateParams object
* @returns - Instruction to perform the action.
*/
public static setProtocolFeeRateIx(
program: Program<Whirlpool>,
params: ix.SetProtocolFeeRateParams,
) {
return ix.setProtocolFeeRateIx(program, params);
}
/**
* Set the whirlpool reward authority at the provided `reward_index`.
* Only the current reward super authority has permission to invoke this instruction.
*
* #### Special Errors
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetRewardAuthorityParams object
* @returns - Instruction to perform the action.
*/
public static setRewardAuthorityBySuperAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetRewardAuthorityBySuperAuthorityParams,
) {
return ix.setRewardAuthorityBySuperAuthorityIx(program, params);
}
/**
* Set the whirlpool reward authority at the provided `reward_index`.
* Only the current reward authority for this reward index has permission to invoke this instruction.
*
* #### Special Errors
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetRewardAuthorityParams object
* @returns - Instruction to perform the action.
*/
public static setRewardAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetRewardAuthorityParams,
) {
return ix.setRewardAuthorityIx(program, params);
}
/**
* Set the reward emissions for a reward in a Whirlpool.
*
* #### Special Errors
* - `RewardVaultAmountInsufficient` - The amount of rewards in the reward vault cannot emit more than a day of desired emissions.
* - `InvalidTimestamp` - Provided timestamp is not in order with the previous timestamp.
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetRewardEmissionsParams object
* @returns - Instruction to perform the action.
*/
public static setRewardEmissionsIx(
program: Program<Whirlpool>,
params: ix.SetRewardEmissionsParams,
) {
return ix.setRewardEmissionsIx(program, params);
}
/**
* Set the whirlpool reward super authority for a WhirlpoolsConfig
* Only the current reward super authority has permission to invoke this instruction.
* This instruction will not change the authority on any `WhirlpoolRewardInfo` whirlpool rewards.
*
* @param program - program object containing services required to generate the instruction
* @param params - SetRewardEmissionsSuperAuthorityParams object
* @returns - Instruction to perform the action.
*/
public static setRewardEmissionsSuperAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetRewardEmissionsSuperAuthorityParams,
) {
return ix.setRewardEmissionsSuperAuthorityIx(program, params);
}
/**
* Initializes a PositionBundle account.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitializePositionBundleParams object
* @returns - Instruction to perform the action.
*/
public static initializePositionBundleIx(
program: Program<Whirlpool>,
params: ix.InitializePositionBundleParams,
) {
return ix.initializePositionBundleIx(program, params);
}
/**
* Initializes a PositionBundle account.
* Additional Metaplex metadata is appended to identify the token.
*
* @param program - program object containing services required to generate the instruction
* @param params - InitializePositionBundleParams object
* @returns - Instruction to perform the action.
*/
public static initializePositionBundleWithMetadataIx(
program: Program<Whirlpool>,
params: ix.InitializePositionBundleParams & {
positionBundleMetadataPda: PDA;
},
) {
return ix.initializePositionBundleWithMetadataIx(program, params);
}
/**
* Deletes a PositionBundle account.
*
* #### Special Errors
* `PositionBundleNotDeletable` - The provided position bundle has open positions.
*
* @param program - program object containing services required to generate the instruction
* @param params - DeletePositionBundleParams object
* @returns - Instruction to perform the action.
*/
public static deletePositionBundleIx(
program: Program<Whirlpool>,
params: ix.DeletePositionBundleParams,
) {
return ix.deletePositionBundleIx(program, params);
}
/**
* Open a bundled position in a Whirlpool.
* No new tokens are issued because the owner of the position bundle becomes the owner of the position.
* The position will start off with 0 liquidity.
*
* #### Special Errors
* `InvalidBundleIndex` - If the provided bundle index is out of bounds.
* `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.
*
* @param program - program object containing services required to generate the instruction
* @param params - OpenBundledPositionParams object
* @returns - Instruction to perform the action.
*/
public static openBundledPositionIx(
program: Program<Whirlpool>,
params: ix.OpenBundledPositionParams,
) {
return ix.openBundledPositionIx(program, params);
}
/**
* Close a bundled position in a Whirlpool.
*
* #### Special Errors
* `InvalidBundleIndex` - If the provided bundle index is out of bounds.
* `ClosePositionNotEmpty` - The provided position account is not empty.
*
* @param program - program object containing services required to generate the instruction
* @param params - CloseBundledPositionParams object
* @returns - Instruction to perform the action.
*/
public static closeBundledPositionIx(
program: Program<Whirlpool>,
params: ix.CloseBundledPositionParams,
) {
return ix.closeBundledPositionIx(program, params);
}
/**
* Open a position in a Whirlpool. A unique token will be minted to represent the position
* in the users wallet. Additional TokenMetadata extension is initialized to identify the token if requested.
* Mint and Token account are based on Token-2022.
* The position will start off with 0 liquidity.
*
* #### Special Errors
* `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.
*
* @param context - Context object containing services required to generate the instruction
* @param params - OpenPositionWithTokenExtensionsParams object and a derived PDA that hosts the position's metadata.
* @returns - Instruction to perform the action.
*/
public static openPositionWithTokenExtensionsIx(
program: Program<Whirlpool>,
params: ix.OpenPositionWithTokenExtensionsParams,
) {
return ix.openPositionWithTokenExtensionsIx(program, params);
}
/**
* Close a position in a Whirlpool. Burns the position token in the owner's wallet.
* Mint and TokenAccount are based on Token-2022. And Mint accout will be also closed.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - ClosePositionWithTokenExtensionsParams object
* @returns - Instruction to perform the action.
*/
public static closePositionWithTokenExtensionsIx(
program: Program<Whirlpool>,
params: ix.ClosePositionWithTokenExtensionsParams,
) {
return ix.closePositionWithTokenExtensionsIx(program, params);
}
// V2 instructions
// TODO: comments
public static collectFeesV2Ix(
program: Program<Whirlpool>,
params: ix.CollectFeesV2Params,
) {
return ix.collectFeesV2Ix(program, params);
}
public static collectProtocolFeesV2Ix(
program: Program<Whirlpool>,
params: ix.CollectProtocolFeesV2Params,
) {
return ix.collectProtocolFeesV2Ix(program, params);
}
public static collectRewardV2Ix(
program: Program<Whirlpool>,
params: ix.CollectRewardV2Params,
) {
return ix.collectRewardV2Ix(program, params);
}
public static decreaseLiquidityV2Ix(
program: Program<Whirlpool>,
params: ix.DecreaseLiquidityV2Params,
) {
return ix.decreaseLiquidityV2Ix(program, params);
}
public static increaseLiquidityV2Ix(
program: Program<Whirlpool>,
params: ix.IncreaseLiquidityV2Params,
) {
return ix.increaseLiquidityV2Ix(program, params);
}
public static initializePoolV2Ix(
program: Program<Whirlpool>,
params: ix.InitPoolV2Params,
) {
return ix.initializePoolV2Ix(program, params);
}
public static initializeRewardV2Ix(
program: Program<Whirlpool>,
params: ix.InitializeRewardV2Params,
) {
return ix.initializeRewardV2Ix(program, params);
}
public static setRewardEmissionsV2Ix(
program: Program<Whirlpool>,
params: ix.SetRewardEmissionsV2Params,
) {
return ix.setRewardEmissionsV2Ix(program, params);
}
public static swapV2Ix(program: Program<Whirlpool>, params: ix.SwapV2Params) {
return ix.swapV2Ix(program, params);
}
public static twoHopSwapV2Ix(
program: Program<Whirlpool>,
params: ix.TwoHopSwapV2Params,
) {
return ix.twoHopSwapV2Ix(program, params);
}
// V2 instructions (TokenBadge related)
// TODO: comments
public static initializeConfigExtensionIx(
program: Program<Whirlpool>,
params: ix.InitConfigExtensionParams,
) {
return ix.initializeConfigExtensionIx(program, params);
}
public static setConfigExtensionAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetConfigExtensionAuthorityParams,
) {
return ix.setConfigExtensionAuthorityIx(program, params);
}
public static setTokenBadgeAuthorityIx(
program: Program<Whirlpool>,
params: ix.SetTokenBadgeAuthorityParams,
) {
return ix.setTokenBadgeAuthorityIx(program, params);
}
public static initializeTokenBadgeIx(
program: Program<Whirlpool>,
params: ix.InitializeTokenBadgeParams,
) {
return ix.initializeTokenBadgeIx(program, params);
}
public static deleteTokenBadgeIx(
program: Program<Whirlpool>,
params: ix.DeleteTokenBadgeParams,
) {
return ix.deleteTokenBadgeIx(program, params);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/impl/whirlpool-impl.ts
|
import type { Address } from "@coral-xyz/anchor";
import { BN, translateAddress } from "@coral-xyz/anchor";
import type { Percentage } from "@orca-so/common-sdk";
import {
AddressUtil,
TokenUtil,
TransactionBuilder,
ZERO,
resolveOrCreateATAs,
} from "@orca-so/common-sdk";
import {
getAssociatedTokenAddressSync,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import { Keypair } from "@solana/web3.js";
import invariant from "tiny-invariant";
import type { WhirlpoolContext } from "../context";
import type {
DevFeeSwapInput,
IncreaseLiquidityInput,
SwapInput,
} from "../instructions";
import {
closePositionIx,
closePositionWithTokenExtensionsIx,
increaseLiquidityIx,
increaseLiquidityV2Ix,
initTickArrayIx,
openPositionIx,
openPositionWithMetadataIx,
openPositionWithTokenExtensionsIx,
swapAsync,
} from "../instructions";
import { WhirlpoolIx } from "../ix";
import { IGNORE_CACHE, PREFER_CACHE } from "../network/public/fetcher";
import {
collectFeesQuote,
collectRewardsQuote,
decreaseLiquidityQuoteByLiquidityWithParams,
decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage,
} from "../quotes/public";
import type {
TokenAccountInfo,
TokenInfo,
WhirlpoolData,
WhirlpoolRewardInfo,
} from "../types/public";
import { getTickArrayDataForPosition } from "../utils/builder/position-builder-util";
import { PDAUtil, TickArrayUtil, TickUtil } from "../utils/public";
import { TokenExtensionUtil } from "../utils/public/token-extension-util";
import {
MultipleTransactionBuilderFactoryWithAccountResolver,
convertListToMap,
} from "../utils/txn-utils";
import {
TokenMintTypes,
getTokenMintsFromWhirlpools,
} from "../utils/whirlpool-ata-utils";
import type { Whirlpool } from "../whirlpool-client";
import { PositionImpl } from "./position-impl";
import { getRewardInfos, getTokenVaultAccountInfos } from "./util";
import { PoolUtil } from "../../src/utils/public/pool-utils";
export class WhirlpoolImpl implements Whirlpool {
private data: WhirlpoolData;
constructor(
readonly ctx: WhirlpoolContext,
readonly address: PublicKey,
readonly tokenAInfo: TokenInfo,
readonly tokenBInfo: TokenInfo,
private tokenVaultAInfo: TokenAccountInfo,
private tokenVaultBInfo: TokenAccountInfo,
private rewardInfos: WhirlpoolRewardInfo[],
data: WhirlpoolData,
) {
this.data = data;
}
getAddress(): PublicKey {
return this.address;
}
getData(): WhirlpoolData {
return this.data;
}
getTokenAInfo(): TokenInfo {
return this.tokenAInfo;
}
getTokenBInfo(): TokenInfo {
return this.tokenBInfo;
}
getTokenVaultAInfo(): TokenAccountInfo {
return this.tokenVaultAInfo;
}
getTokenVaultBInfo(): TokenAccountInfo {
return this.tokenVaultBInfo;
}
getRewardInfos(): WhirlpoolRewardInfo[] {
return this.rewardInfos;
}
async refreshData() {
await this.refresh();
return this.data;
}
async openPosition(
tickLower: number,
tickUpper: number,
liquidityInput: IncreaseLiquidityInput,
wallet?: Address,
funder?: Address,
positionMint?: PublicKey,
tokenProgramId?: PublicKey,
) {
await this.refresh();
return this.getOpenPositionWithOptMetadataTx(
tickLower,
tickUpper,
liquidityInput,
!!wallet ? AddressUtil.toPubKey(wallet) : this.ctx.wallet.publicKey,
!!funder ? AddressUtil.toPubKey(funder) : this.ctx.wallet.publicKey,
// TOKEN_PROGRAM_ID for v0.13.x, TOKEN_2022_PROGRAM_ID for future releases
tokenProgramId ?? TOKEN_PROGRAM_ID,
false,
positionMint,
);
}
async openPositionWithMetadata(
tickLower: number,
tickUpper: number,
liquidityInput: IncreaseLiquidityInput,
sourceWallet?: Address,
funder?: Address,
positionMint?: PublicKey,
tokenProgramId?: PublicKey,
) {
await this.refresh();
return this.getOpenPositionWithOptMetadataTx(
tickLower,
tickUpper,
liquidityInput,
!!sourceWallet
? AddressUtil.toPubKey(sourceWallet)
: this.ctx.wallet.publicKey,
!!funder ? AddressUtil.toPubKey(funder) : this.ctx.wallet.publicKey,
// TOKEN_PROGRAM_ID for v0.13.x, TOKEN_2022_PROGRAM_ID for future releases
tokenProgramId ?? TOKEN_PROGRAM_ID,
true,
positionMint,
);
}
async initTickArrayForTicks(
ticks: number[],
funder?: Address,
opts = IGNORE_CACHE,
) {
const initTickArrayStartPdas =
await TickArrayUtil.getUninitializedArraysPDAs(
ticks,
this.ctx.program.programId,
this.address,
this.data.tickSpacing,
this.ctx.fetcher,
opts,
);
if (!initTickArrayStartPdas.length) {
return null;
}
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
initTickArrayStartPdas.forEach((initTickArrayInfo) => {
txBuilder.addInstruction(
initTickArrayIx(this.ctx.program, {
startTick: initTickArrayInfo.startIndex,
tickArrayPda: initTickArrayInfo.pda,
whirlpool: this.address,
funder: !!funder
? AddressUtil.toPubKey(funder)
: this.ctx.provider.wallet.publicKey,
}),
);
});
return txBuilder;
}
async closePosition(
positionAddress: Address,
slippageTolerance: Percentage,
destinationWallet?: Address,
positionWallet?: Address,
payer?: Address,
usePriceSlippage = false,
) {
await this.refresh();
const positionWalletKey = positionWallet
? AddressUtil.toPubKey(positionWallet)
: this.ctx.wallet.publicKey;
const destinationWalletKey = destinationWallet
? AddressUtil.toPubKey(destinationWallet)
: this.ctx.wallet.publicKey;
const payerKey = payer
? AddressUtil.toPubKey(payer)
: this.ctx.wallet.publicKey;
return this.getClosePositionIx(
AddressUtil.toPubKey(positionAddress),
slippageTolerance,
destinationWalletKey,
positionWalletKey,
payerKey,
usePriceSlippage,
);
}
async swap(
quote: SwapInput,
sourceWallet?: Address,
): Promise<TransactionBuilder> {
const sourceWalletKey = sourceWallet
? AddressUtil.toPubKey(sourceWallet)
: this.ctx.wallet.publicKey;
return swapAsync(
this.ctx,
{
swapInput: quote,
whirlpool: this,
wallet: sourceWalletKey,
},
IGNORE_CACHE,
);
}
async swapWithDevFees(
quote: DevFeeSwapInput,
devFeeWallet: PublicKey,
wallet?: PublicKey | undefined,
payer?: PublicKey | undefined,
): Promise<TransactionBuilder> {
const sourceWalletKey = wallet
? AddressUtil.toPubKey(wallet)
: this.ctx.wallet.publicKey;
const payerKey = payer
? AddressUtil.toPubKey(payer)
: this.ctx.wallet.publicKey;
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
if (!quote.devFeeAmount.eq(ZERO)) {
const inputToken =
quote.aToB === quote.amountSpecifiedIsInput
? this.getTokenAInfo()
: this.getTokenBInfo();
txBuilder.addInstruction(
await TokenUtil.createSendTokensToWalletInstruction(
this.ctx.connection,
sourceWalletKey,
devFeeWallet,
inputToken.mint,
inputToken.decimals,
quote.devFeeAmount,
() => this.ctx.fetcher.getAccountRentExempt(),
payerKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
),
);
}
const swapTxBuilder = await swapAsync(
this.ctx,
{
swapInput: quote,
whirlpool: this,
wallet: sourceWalletKey,
},
IGNORE_CACHE,
);
txBuilder.addInstruction(swapTxBuilder.compressIx(true));
return txBuilder;
}
/**
* Construct a transaction for opening an new position with optional metadata
*/
async getOpenPositionWithOptMetadataTx(
tickLower: number,
tickUpper: number,
liquidityInput: IncreaseLiquidityInput,
wallet: PublicKey,
funder: PublicKey,
tokenProgramId: PublicKey,
withMetadata: boolean = false,
positionMint?: PublicKey,
): Promise<{ positionMint: PublicKey; tx: TransactionBuilder }> {
invariant(
TickUtil.checkTickInBounds(tickLower),
"tickLower is out of bounds.",
);
invariant(
TickUtil.checkTickInBounds(tickUpper),
"tickUpper is out of bounds.",
);
invariant(
tokenProgramId.equals(TOKEN_PROGRAM_ID) ||
tokenProgramId.equals(TOKEN_2022_PROGRAM_ID),
"tokenProgramId must be either TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID",
);
const { liquidityAmount: liquidity, tokenMaxA, tokenMaxB } = liquidityInput;
invariant(liquidity.gt(new BN(0)), "liquidity must be greater than zero");
const whirlpool = await this.ctx.fetcher.getPool(
this.address,
PREFER_CACHE,
);
if (!whirlpool) {
throw new Error(
`Whirlpool not found: ${translateAddress(this.address).toBase58()}`,
);
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
invariant(
TickUtil.isTickInitializable(tickLower, whirlpool.tickSpacing),
`lower tick ${tickLower} is not an initializable tick for tick-spacing ${whirlpool.tickSpacing}`,
);
invariant(
TickUtil.isTickInitializable(tickUpper, whirlpool.tickSpacing),
`upper tick ${tickUpper} is not an initializable tick for tick-spacing ${whirlpool.tickSpacing}`,
);
const positionMintKeypair = Keypair.generate();
const positionMintPubkey = positionMint ?? positionMintKeypair.publicKey;
const positionPda = PDAUtil.getPosition(
this.ctx.program.programId,
positionMintPubkey,
);
const metadataPda = PDAUtil.getPositionMetadata(positionMintPubkey);
const positionTokenAccountAddress = getAssociatedTokenAddressSync(
positionMintPubkey,
wallet,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
tokenProgramId,
);
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
const params = {
funder,
owner: wallet,
positionPda,
positionTokenAccount: positionTokenAccountAddress,
whirlpool: this.address,
tickLowerIndex: tickLower,
tickUpperIndex: tickUpper,
};
const positionIx = tokenProgramId.equals(TOKEN_2022_PROGRAM_ID)
? openPositionWithTokenExtensionsIx(this.ctx.program, {
...params,
positionMint: positionMintPubkey,
withTokenMetadataExtension: withMetadata,
})
: (withMetadata ? openPositionWithMetadataIx : openPositionIx)(
this.ctx.program,
{
...params,
positionMintAddress: positionMintPubkey,
metadataPda,
},
);
txBuilder.addInstruction(positionIx);
if (positionMint === undefined) {
txBuilder.addSigner(positionMintKeypair);
}
const [ataA, ataB] = await resolveOrCreateATAs(
this.ctx.connection,
wallet,
[
{ tokenMint: whirlpool.tokenMintA, wrappedSolAmountIn: tokenMaxA },
{ tokenMint: whirlpool.tokenMintB, wrappedSolAmountIn: tokenMaxB },
],
() => this.ctx.fetcher.getAccountRentExempt(),
funder,
undefined, // use default
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
const { address: tokenOwnerAccountA, ...tokenOwnerAccountAIx } = ataA;
const { address: tokenOwnerAccountB, ...tokenOwnerAccountBIx } = ataB;
txBuilder.addInstruction(tokenOwnerAccountAIx);
txBuilder.addInstruction(tokenOwnerAccountBIx);
const tickArrayLowerPda = PDAUtil.getTickArrayFromTickIndex(
tickLower,
this.data.tickSpacing,
this.address,
this.ctx.program.programId,
);
const tickArrayUpperPda = PDAUtil.getTickArrayFromTickIndex(
tickUpper,
this.data.tickSpacing,
this.address,
this.ctx.program.programId,
);
const baseParams = {
liquidityAmount: liquidity,
tokenMaxA,
tokenMaxB,
whirlpool: this.address,
positionAuthority: wallet,
position: positionPda.publicKey,
positionTokenAccount: positionTokenAccountAddress,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const liquidityIx = !TokenExtensionUtil.isV2IxRequiredPool(
tokenExtensionCtx,
)
? increaseLiquidityIx(this.ctx.program, baseParams)
: increaseLiquidityV2Ix(this.ctx.program, {
...baseParams,
tokenMintA: whirlpool.tokenMintA,
tokenMintB: whirlpool.tokenMintB,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
baseParams.tokenOwnerAccountA,
baseParams.tokenVaultA,
baseParams.positionAuthority,
baseParams.tokenOwnerAccountB,
baseParams.tokenVaultB,
baseParams.positionAuthority,
)),
});
txBuilder.addInstruction(liquidityIx);
return {
positionMint: positionMintPubkey,
tx: txBuilder,
};
}
async getClosePositionIx(
positionAddress: PublicKey,
slippageTolerance: Percentage,
destinationWallet: PublicKey,
positionWallet: PublicKey,
payerKey: PublicKey,
usePriceSlippage = false,
): Promise<TransactionBuilder[]> {
const positionData = await this.ctx.fetcher.getPosition(
positionAddress,
IGNORE_CACHE,
);
if (!positionData) {
throw new Error(`Position not found: ${positionAddress.toBase58()}`);
}
const positionMint = await this.ctx.fetcher.getMintInfo(
positionData.positionMint,
);
if (!positionMint) {
throw new Error(
`Position mint not found: ${positionData.positionMint.toBase58()}`,
);
}
const whirlpool = this.data;
invariant(
positionData.whirlpool.equals(this.address),
`Position ${positionAddress.toBase58()} is not a position for Whirlpool ${this.address.toBase58()}`,
);
const positionTokenAccount = getAssociatedTokenAddressSync(
positionData.positionMint,
positionWallet,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
positionMint.tokenProgram,
);
const accountExemption = await this.ctx.fetcher.getAccountRentExempt();
const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(
positionData.tickLowerIndex,
whirlpool.tickSpacing,
positionData.whirlpool,
this.ctx.program.programId,
).publicKey;
const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(
positionData.tickUpperIndex,
whirlpool.tickSpacing,
positionData.whirlpool,
this.ctx.program.programId,
).publicKey;
const [tickArrayLowerData, tickArrayUpperData] =
await getTickArrayDataForPosition(
this.ctx,
positionData,
whirlpool,
IGNORE_CACHE,
);
invariant(
!!tickArrayLowerData,
`Tick array ${tickArrayLower} expected to be initialized for whirlpool ${this.address}`,
);
invariant(
!!tickArrayUpperData,
`Tick array ${tickArrayUpper} expected to be initialized for whirlpool ${this.address}`,
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
const position = new PositionImpl(
this.ctx,
positionAddress,
positionData,
whirlpool,
tickArrayLowerData,
tickArrayUpperData,
positionMint.tokenProgram,
);
const tickLower = position.getLowerTickData();
const tickUpper = position.getUpperTickData();
const feesQuote = collectFeesQuote({
position: positionData,
whirlpool,
tickLower,
tickUpper,
tokenExtensionCtx,
});
const rewardsQuote = collectRewardsQuote({
position: positionData,
whirlpool,
tickLower,
tickUpper,
tokenExtensionCtx,
});
const shouldCollectFees =
feesQuote.feeOwedA.gtn(0) || feesQuote.feeOwedB.gtn(0);
invariant(
this.data.rewardInfos.length === rewardsQuote.rewardOwed.length,
"Rewards quote does not match reward infos length",
);
const shouldDecreaseLiquidity = positionData.liquidity.gtn(0);
const rewardsToCollect = this.data.rewardInfos
.filter((info, index) => {
if (!PoolUtil.isRewardInitialized(info)) {
return false;
}
return (
(rewardsQuote.rewardOwed[index] ?? ZERO).gtn(0) ||
(rewardsQuote.transferFee.deductedFromRewardOwed[index] ?? ZERO).gtn(
0,
)
);
})
.map((info, index) => ({ info, index }));
const shouldCollectRewards = rewardsToCollect.length > 0;
let mintType = TokenMintTypes.ALL;
if (
(shouldDecreaseLiquidity || shouldCollectFees) &&
!shouldCollectRewards
) {
mintType = TokenMintTypes.POOL_ONLY;
} else if (
!(shouldDecreaseLiquidity || shouldCollectFees) &&
shouldCollectRewards
) {
mintType = TokenMintTypes.REWARD_ONLY;
}
const allMints = getTokenMintsFromWhirlpools([whirlpool], mintType);
const resolvedAtas = convertListToMap(
await resolveOrCreateATAs(
this.ctx.connection,
destinationWallet,
allMints.mintMap.map((tokenMint) => ({ tokenMint })),
async () => accountExemption,
payerKey,
true, // CreateIdempotent
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.ctx.accountResolverOpts.createWrappedSolAccountMethod,
),
allMints.mintMap.map((mint) => mint.toBase58()),
);
const builder = new MultipleTransactionBuilderFactoryWithAccountResolver(
this.ctx,
resolvedAtas,
destinationWallet,
payerKey,
);
if (shouldDecreaseLiquidity) {
await builder.addInstructions(async (resolveTokenAccount) => {
const tokenOwnerAccountA = resolveTokenAccount(
whirlpool.tokenMintA.toBase58(),
);
const tokenOwnerAccountB = resolveTokenAccount(
whirlpool.tokenMintB.toBase58(),
);
const params = {
liquidity: positionData.liquidity,
slippageTolerance,
sqrtPrice: whirlpool.sqrtPrice,
tickCurrentIndex: whirlpool.tickCurrentIndex,
tickLowerIndex: positionData.tickLowerIndex,
tickUpperIndex: positionData.tickUpperIndex,
tokenExtensionCtx,
};
const decreaseLiqQuote = usePriceSlippage
? decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage(
params,
)
: decreaseLiquidityQuoteByLiquidityWithParams(params);
const baseParams = {
...decreaseLiqQuote,
whirlpool: positionData.whirlpool,
positionAuthority: positionWallet,
position: positionAddress,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
tickArrayLower,
tickArrayUpper,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const ix = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? WhirlpoolIx.decreaseLiquidityIx(this.ctx.program, baseParams)
: WhirlpoolIx.decreaseLiquidityV2Ix(this.ctx.program, {
...baseParams,
tokenMintA: whirlpool.tokenMintA,
tokenMintB: whirlpool.tokenMintB,
tokenProgramA:
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB:
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
baseParams.tokenVaultA,
baseParams.tokenOwnerAccountA,
baseParams.whirlpool, // vault to owner, so pool is authority
baseParams.tokenVaultB,
baseParams.tokenOwnerAccountB,
baseParams.whirlpool, // vault to owner, so pool is authority
)),
});
return [ix];
});
}
if (shouldCollectFees) {
await builder.addInstructions(async (resolveTokenAccount) => {
const tokenOwnerAccountA = resolveTokenAccount(
whirlpool.tokenMintA.toBase58(),
);
const tokenOwnerAccountB = resolveTokenAccount(
whirlpool.tokenMintB.toBase58(),
);
const collectFeesBaseParams = {
whirlpool: positionData.whirlpool,
position: positionAddress,
positionAuthority: positionWallet,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
};
const ix = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? WhirlpoolIx.collectFeesIx(this.ctx.program, collectFeesBaseParams)
: WhirlpoolIx.collectFeesV2Ix(this.ctx.program, {
...collectFeesBaseParams,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA:
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB:
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
collectFeesBaseParams.tokenVaultA,
collectFeesBaseParams.tokenOwnerAccountA,
collectFeesBaseParams.whirlpool, // vault to owner, so pool is authority
collectFeesBaseParams.tokenVaultB,
collectFeesBaseParams.tokenOwnerAccountB,
collectFeesBaseParams.whirlpool, // vault to owner, so pool is authority
)),
});
return [ix];
});
}
if (shouldCollectRewards) {
for (const { info, index: rewardIndex } of rewardsToCollect) {
await builder.addInstructions(async (resolveTokenAccount) => {
const rewardOwnerAccount = resolveTokenAccount(info.mint.toBase58());
const collectRewardBaseParams = {
whirlpool: positionData.whirlpool,
position: positionAddress,
positionAuthority: positionWallet,
positionTokenAccount,
rewardIndex,
rewardOwnerAccount,
rewardVault: whirlpool.rewardInfos[rewardIndex].vault,
};
const ix = !TokenExtensionUtil.isV2IxRequiredReward(
tokenExtensionCtx,
rewardIndex,
)
? WhirlpoolIx.collectRewardIx(
this.ctx.program,
collectRewardBaseParams,
)
: WhirlpoolIx.collectRewardV2Ix(this.ctx.program, {
...collectRewardBaseParams,
rewardMint:
tokenExtensionCtx.rewardTokenMintsWithProgram[rewardIndex]!
.address,
rewardTokenProgram:
tokenExtensionCtx.rewardTokenMintsWithProgram[rewardIndex]!
.tokenProgram,
rewardTransferHookAccounts:
await TokenExtensionUtil.getExtraAccountMetasForTransferHook(
this.ctx.connection,
tokenExtensionCtx.rewardTokenMintsWithProgram[rewardIndex]!,
collectRewardBaseParams.rewardVault,
collectRewardBaseParams.rewardOwnerAccount,
collectRewardBaseParams.whirlpool, // vault to owner, so pool is authority
),
});
return [ix];
});
}
}
/* Close position */
await builder.addInstructions(async () => {
const closePositionParams = {
positionAuthority: positionWallet,
receiver: destinationWallet,
positionTokenAccount,
position: positionAddress,
positionMint: positionData.positionMint,
};
if (positionMint.tokenProgram.equals(TOKEN_2022_PROGRAM_ID)) {
return [
closePositionWithTokenExtensionsIx(
this.ctx.program,
closePositionParams,
),
];
} else {
return [closePositionIx(this.ctx.program, closePositionParams)];
}
});
return builder.build();
}
private async refresh() {
const account = await this.ctx.fetcher.getPool(this.address, IGNORE_CACHE);
if (!!account) {
const rewardInfos = await getRewardInfos(
this.ctx.fetcher,
account,
IGNORE_CACHE,
);
const [tokenVaultAInfo, tokenVaultBInfo] =
await getTokenVaultAccountInfos(
this.ctx.fetcher,
account,
IGNORE_CACHE,
);
this.data = account;
this.tokenVaultAInfo = tokenVaultAInfo;
this.tokenVaultBInfo = tokenVaultBInfo;
this.rewardInfos = rewardInfos;
}
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/impl/position-impl.ts
|
import type { Address } from "@coral-xyz/anchor";
import type {
Instruction,
ResolvedTokenAddressInstruction,
} from "@orca-so/common-sdk";
import {
AddressUtil,
TokenUtil,
TransactionBuilder,
ZERO,
resolveOrCreateATAs,
} from "@orca-so/common-sdk";
import { NATIVE_MINT, getAssociatedTokenAddressSync } from "@solana/spl-token";
import { PublicKey } from "@solana/web3.js";
import invariant from "tiny-invariant";
import type { WhirlpoolContext } from "../context";
import type {
DecreaseLiquidityInput,
IncreaseLiquidityInput,
} from "../instructions";
import {
collectFeesIx,
collectFeesV2Ix,
collectRewardIx,
collectRewardV2Ix,
decreaseLiquidityIx,
decreaseLiquidityV2Ix,
increaseLiquidityIx,
increaseLiquidityV2Ix,
updateFeesAndRewardsIx,
} from "../instructions";
import type { WhirlpoolAccountFetchOptions } from "../network/public/fetcher";
import { IGNORE_CACHE, PREFER_CACHE } from "../network/public/fetcher";
import type {
PositionData,
TickArrayData,
TickData,
WhirlpoolData,
} from "../types/public";
import { getTickArrayDataForPosition } from "../utils/builder/position-builder-util";
import { PDAUtil, PoolUtil, TickArrayUtil, TickUtil } from "../utils/public";
import {
TokenMintTypes,
getTokenMintsFromWhirlpools,
resolveAtaForMints,
} from "../utils/whirlpool-ata-utils";
import type { Position } from "../whirlpool-client";
import { TokenExtensionUtil } from "../utils/public/token-extension-util";
import {
MultipleTransactionBuilderFactoryWithAccountResolver,
convertListToMap,
} from "../utils/txn-utils";
export class PositionImpl implements Position {
private data: PositionData;
private whirlpoolData: WhirlpoolData;
private lowerTickArrayData: TickArrayData;
private upperTickArrayData: TickArrayData;
constructor(
readonly ctx: WhirlpoolContext,
readonly address: PublicKey,
data: PositionData,
whirlpoolData: WhirlpoolData,
lowerTickArrayData: TickArrayData,
upperTickArrayData: TickArrayData,
readonly positionMintTokenProgramId: PublicKey,
) {
this.data = data;
this.whirlpoolData = whirlpoolData;
this.lowerTickArrayData = lowerTickArrayData;
this.upperTickArrayData = upperTickArrayData;
}
getAddress(): PublicKey {
return this.address;
}
getPositionMintTokenProgramId(): PublicKey {
return this.positionMintTokenProgramId;
}
getData(): PositionData {
return this.data;
}
getWhirlpoolData(): WhirlpoolData {
return this.whirlpoolData;
}
getLowerTickData(): TickData {
return TickArrayUtil.getTickFromArray(
this.lowerTickArrayData,
this.data.tickLowerIndex,
this.whirlpoolData.tickSpacing,
);
}
getUpperTickData(): TickData {
return TickArrayUtil.getTickFromArray(
this.upperTickArrayData,
this.data.tickUpperIndex,
this.whirlpoolData.tickSpacing,
);
}
async refreshData() {
await this.refresh();
return this.data;
}
async increaseLiquidity(
liquidityInput: IncreaseLiquidityInput,
resolveATA = true,
sourceWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
) {
const sourceWalletKey = sourceWallet
? AddressUtil.toPubKey(sourceWallet)
: this.ctx.wallet.publicKey;
const positionWalletKey = positionWallet
? AddressUtil.toPubKey(positionWallet)
: this.ctx.wallet.publicKey;
const ataPayerKey = ataPayer
? AddressUtil.toPubKey(ataPayer)
: this.ctx.wallet.publicKey;
const whirlpool = await this.ctx.fetcher.getPool(
this.data.whirlpool,
IGNORE_CACHE,
);
if (!whirlpool) {
throw new Error("Unable to fetch whirlpool for this position.");
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
let tokenOwnerAccountA: PublicKey;
let tokenOwnerAccountB: PublicKey;
if (resolveATA) {
const [ataA, ataB] = await resolveOrCreateATAs(
this.ctx.connection,
sourceWalletKey,
[
{
tokenMint: whirlpool.tokenMintA,
wrappedSolAmountIn: liquidityInput.tokenMaxA,
},
{
tokenMint: whirlpool.tokenMintB,
wrappedSolAmountIn: liquidityInput.tokenMaxB,
},
],
() => this.ctx.fetcher.getAccountRentExempt(),
ataPayerKey,
undefined, // use default
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
const { address: ataAddrA, ...tokenOwnerAccountAIx } = ataA!;
const { address: ataAddrB, ...tokenOwnerAccountBIx } = ataB!;
tokenOwnerAccountA = ataAddrA;
tokenOwnerAccountB = ataAddrB;
txBuilder.addInstruction(tokenOwnerAccountAIx);
txBuilder.addInstruction(tokenOwnerAccountBIx);
} else {
tokenOwnerAccountA = getAssociatedTokenAddressSync(
whirlpool.tokenMintA,
sourceWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
);
tokenOwnerAccountB = getAssociatedTokenAddressSync(
whirlpool.tokenMintB,
sourceWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
);
}
const positionTokenAccount = getAssociatedTokenAddressSync(
this.data.positionMint,
positionWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.positionMintTokenProgramId,
);
const baseParams = {
...liquidityInput,
whirlpool: this.data.whirlpool,
position: this.address,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
tickArrayLower: PDAUtil.getTickArray(
this.ctx.program.programId,
this.data.whirlpool,
TickUtil.getStartTickIndex(
this.data.tickLowerIndex,
whirlpool.tickSpacing,
),
).publicKey,
tickArrayUpper: PDAUtil.getTickArray(
this.ctx.program.programId,
this.data.whirlpool,
TickUtil.getStartTickIndex(
this.data.tickUpperIndex,
whirlpool.tickSpacing,
),
).publicKey,
positionAuthority: positionWalletKey,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const increaseIx = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? increaseLiquidityIx(this.ctx.program, baseParams)
: increaseLiquidityV2Ix(this.ctx.program, {
...baseParams,
tokenMintA: whirlpool.tokenMintA,
tokenMintB: whirlpool.tokenMintB,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
baseParams.tokenOwnerAccountA,
baseParams.tokenVaultA,
baseParams.positionAuthority,
baseParams.tokenOwnerAccountB,
baseParams.tokenVaultB,
baseParams.positionAuthority,
)),
});
txBuilder.addInstruction(increaseIx);
return txBuilder;
}
async decreaseLiquidity(
liquidityInput: DecreaseLiquidityInput,
resolveATA = true,
sourceWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
) {
const sourceWalletKey = sourceWallet
? AddressUtil.toPubKey(sourceWallet)
: this.ctx.wallet.publicKey;
const positionWalletKey = positionWallet
? AddressUtil.toPubKey(positionWallet)
: this.ctx.wallet.publicKey;
const ataPayerKey = ataPayer
? AddressUtil.toPubKey(ataPayer)
: this.ctx.wallet.publicKey;
const whirlpool = await this.ctx.fetcher.getPool(
this.data.whirlpool,
IGNORE_CACHE,
);
if (!whirlpool) {
throw new Error("Unable to fetch whirlpool for this position.");
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
let tokenOwnerAccountA: PublicKey;
let tokenOwnerAccountB: PublicKey;
if (resolveATA) {
const [ataA, ataB] = await resolveOrCreateATAs(
this.ctx.connection,
sourceWalletKey,
[
{ tokenMint: whirlpool.tokenMintA },
{ tokenMint: whirlpool.tokenMintB },
],
() => this.ctx.fetcher.getAccountRentExempt(),
ataPayerKey,
undefined, // use default
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
const { address: ataAddrA, ...tokenOwnerAccountAIx } = ataA!;
const { address: ataAddrB, ...tokenOwnerAccountBIx } = ataB!;
tokenOwnerAccountA = ataAddrA;
tokenOwnerAccountB = ataAddrB;
txBuilder.addInstruction(tokenOwnerAccountAIx);
txBuilder.addInstruction(tokenOwnerAccountBIx);
} else {
tokenOwnerAccountA = getAssociatedTokenAddressSync(
whirlpool.tokenMintA,
sourceWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
);
tokenOwnerAccountB = getAssociatedTokenAddressSync(
whirlpool.tokenMintB,
sourceWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
);
}
const baseParams = {
...liquidityInput,
whirlpool: this.data.whirlpool,
position: this.address,
positionTokenAccount: getAssociatedTokenAddressSync(
this.data.positionMint,
positionWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.positionMintTokenProgramId,
),
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
tickArrayLower: PDAUtil.getTickArray(
this.ctx.program.programId,
this.data.whirlpool,
TickUtil.getStartTickIndex(
this.data.tickLowerIndex,
whirlpool.tickSpacing,
),
).publicKey,
tickArrayUpper: PDAUtil.getTickArray(
this.ctx.program.programId,
this.data.whirlpool,
TickUtil.getStartTickIndex(
this.data.tickUpperIndex,
whirlpool.tickSpacing,
),
).publicKey,
positionAuthority: positionWalletKey,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const decreaseIx = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? decreaseLiquidityIx(this.ctx.program, baseParams)
: decreaseLiquidityV2Ix(this.ctx.program, {
...baseParams,
tokenMintA: whirlpool.tokenMintA,
tokenMintB: whirlpool.tokenMintB,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
baseParams.tokenVaultA,
baseParams.tokenOwnerAccountA,
baseParams.whirlpool, // vault to owner, so pool is authority
baseParams.tokenVaultB,
baseParams.tokenOwnerAccountB,
baseParams.whirlpool, // vault to owner, so pool is authority
)),
});
txBuilder.addInstruction(decreaseIx);
return txBuilder;
}
async collectFees(
updateFeesAndRewards: boolean = true,
ownerTokenAccountMap?: Partial<Record<string, Address>>,
destinationWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
opts: WhirlpoolAccountFetchOptions = PREFER_CACHE,
): Promise<TransactionBuilder> {
const [destinationWalletKey, positionWalletKey, ataPayerKey] =
AddressUtil.toPubKeys([
destinationWallet ?? this.ctx.wallet.publicKey,
positionWallet ?? this.ctx.wallet.publicKey,
ataPayer ?? this.ctx.wallet.publicKey,
]);
const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, opts);
if (!whirlpool) {
throw new Error(
`Unable to fetch whirlpool (${this.data.whirlpool}) for this position (${this.address}).`,
);
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
let txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
const accountExemption = await this.ctx.fetcher.getAccountRentExempt();
let ataMap = { ...ownerTokenAccountMap };
if (!ownerTokenAccountMap) {
const affliatedMints = getTokenMintsFromWhirlpools(
[whirlpool],
TokenMintTypes.POOL_ONLY,
);
const { ataTokenAddresses: affliatedTokenAtaMap, resolveAtaIxs } =
await resolveAtaForMints(this.ctx, {
mints: affliatedMints.mintMap,
accountExemption,
receiver: destinationWalletKey,
payer: ataPayerKey,
});
txBuilder.addInstructions(resolveAtaIxs);
if (affliatedMints.hasNativeMint) {
let { address: wSOLAta, ...resolveWSolIx } =
TokenUtil.createWrappedNativeAccountInstruction(
destinationWalletKey,
ZERO,
accountExemption,
ataPayerKey,
destinationWalletKey,
this.ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
affliatedTokenAtaMap[NATIVE_MINT.toBase58()] = wSOLAta;
txBuilder.addInstruction(resolveWSolIx);
}
ataMap = { ...affliatedTokenAtaMap };
}
const tokenOwnerAccountA = ataMap[whirlpool.tokenMintA.toBase58()];
invariant(
!!tokenOwnerAccountA,
`No owner token account provided for wallet ${destinationWalletKey.toBase58()} for token A ${whirlpool.tokenMintA.toBase58()} `,
);
const tokenOwnerAccountB = ataMap[whirlpool.tokenMintB.toBase58()];
invariant(
!!tokenOwnerAccountB,
`No owner token account provided for wallet ${destinationWalletKey.toBase58()} for token B ${whirlpool.tokenMintB.toBase58()} `,
);
const positionTokenAccount = getAssociatedTokenAddressSync(
this.data.positionMint,
positionWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.positionMintTokenProgramId,
);
if (updateFeesAndRewards && !this.data.liquidity.isZero()) {
const updateIx = await this.updateFeesAndRewards();
txBuilder.addInstruction(updateIx);
}
const baseParams = {
whirlpool: this.data.whirlpool,
position: this.address,
positionTokenAccount,
tokenOwnerAccountA: AddressUtil.toPubKey(tokenOwnerAccountA),
tokenOwnerAccountB: AddressUtil.toPubKey(tokenOwnerAccountB),
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
positionAuthority: positionWalletKey,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const ix = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? collectFeesIx(this.ctx.program, baseParams)
: collectFeesV2Ix(this.ctx.program, {
...baseParams,
tokenMintA: whirlpool.tokenMintA,
tokenMintB: whirlpool.tokenMintB,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
this.ctx.connection,
tokenExtensionCtx,
baseParams.tokenVaultA,
baseParams.tokenOwnerAccountA,
baseParams.whirlpool, // vault to owner, so pool is authority
baseParams.tokenVaultB,
baseParams.tokenOwnerAccountB,
baseParams.whirlpool, // vault to owner, so pool is authority
)),
});
txBuilder.addInstruction(ix);
return txBuilder;
}
async collectRewards(
rewardsToCollect?: Address[],
updateFeesAndRewards: boolean = true,
ownerTokenAccountMap?: Partial<Record<string, Address>>,
destinationWallet?: Address,
positionWallet?: Address,
ataPayer?: Address,
opts: WhirlpoolAccountFetchOptions = IGNORE_CACHE,
): Promise<TransactionBuilder[]> {
const [destinationWalletKey, positionWalletKey, ataPayerKey] =
AddressUtil.toPubKeys([
destinationWallet ?? this.ctx.wallet.publicKey,
positionWallet ?? this.ctx.wallet.publicKey,
ataPayer ?? this.ctx.wallet.publicKey,
]);
const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, opts);
if (!whirlpool) {
throw new Error(
`Unable to fetch whirlpool(${this.data.whirlpool}) for this position(${this.address}).`,
);
}
const initializedRewards = whirlpool.rewardInfos.filter((info) =>
PoolUtil.isRewardInitialized(info),
);
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
this.ctx.fetcher,
whirlpool,
IGNORE_CACHE,
);
let resolvedAtas: Record<string, ResolvedTokenAddressInstruction>;
if (ownerTokenAccountMap) {
resolvedAtas = {};
Object.entries(ownerTokenAccountMap).forEach(([mint, address]) => {
if (!address) return;
resolvedAtas[mint] = {
address: AddressUtil.toPubKey(address),
instructions: [],
cleanupInstructions: [],
signers: [],
tokenProgram: PublicKey.default, // unused (dummy)
};
});
} else {
const accountExemption = await this.ctx.fetcher.getAccountRentExempt();
const rewardMints = getTokenMintsFromWhirlpools(
[whirlpool],
TokenMintTypes.REWARD_ONLY,
);
resolvedAtas = convertListToMap(
await resolveOrCreateATAs(
this.ctx.connection,
destinationWalletKey,
rewardMints.mintMap.map((tokenMint) => ({ tokenMint })),
async () => accountExemption,
ataPayerKey,
true, // CreateIdempotent
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
),
rewardMints.mintMap.map((mint) => mint.toBase58()),
);
}
const builder = new MultipleTransactionBuilderFactoryWithAccountResolver(
this.ctx,
resolvedAtas,
destinationWalletKey,
ataPayerKey,
);
const positionTokenAccount = getAssociatedTokenAddressSync(
this.data.positionMint,
positionWalletKey,
this.ctx.accountResolverOpts.allowPDAOwnerAddress,
this.positionMintTokenProgramId,
);
if (updateFeesAndRewards && !this.data.liquidity.isZero()) {
await builder.addInstructions(async () => {
const updateIx = await this.updateFeesAndRewards();
return [updateIx];
});
}
for (let index = 0; index < initializedRewards.length; index++) {
const info = initializedRewards[index];
if (
rewardsToCollect &&
!rewardsToCollect.some((r) => r.toString() === info.mint.toBase58())
) {
// If rewardsToCollect is specified and this reward is not in it,
// don't include collectIX for that in TX
break;
}
await builder.addInstructions(async (resolve) => {
const rewardOwnerAccount = resolve(info.mint.toBase58());
invariant(
!!rewardOwnerAccount,
`No owner token account provided for wallet ${destinationWalletKey.toBase58()} for reward ${index} token ${info.mint.toBase58()} `,
);
const baseParams = {
whirlpool: this.data.whirlpool,
position: this.address,
positionTokenAccount,
rewardIndex: index,
rewardOwnerAccount: AddressUtil.toPubKey(rewardOwnerAccount),
rewardVault: info.vault,
positionAuthority: positionWalletKey,
};
// V2 can handle TokenProgram/TokenProgram pool, but it increases the size of transaction, so V1 is prefer if possible.
const ix = !TokenExtensionUtil.isV2IxRequiredReward(
tokenExtensionCtx,
index,
)
? collectRewardIx(this.ctx.program, baseParams)
: collectRewardV2Ix(this.ctx.program, {
...baseParams,
rewardMint: info.mint,
rewardTokenProgram:
tokenExtensionCtx.rewardTokenMintsWithProgram[index]!
.tokenProgram,
rewardTransferHookAccounts:
await TokenExtensionUtil.getExtraAccountMetasForTransferHook(
this.ctx.connection,
tokenExtensionCtx.rewardTokenMintsWithProgram[index]!,
baseParams.rewardVault,
baseParams.rewardOwnerAccount,
baseParams.whirlpool, // vault to owner, so pool is authority
),
});
return [ix];
});
}
return builder.build();
}
private async refresh() {
const positionAccount = await this.ctx.fetcher.getPosition(
this.address,
IGNORE_CACHE,
);
if (!!positionAccount) {
this.data = positionAccount;
}
const whirlpoolAccount = await this.ctx.fetcher.getPool(
this.data.whirlpool,
IGNORE_CACHE,
);
if (!!whirlpoolAccount) {
this.whirlpoolData = whirlpoolAccount;
}
const [lowerTickArray, upperTickArray] = await getTickArrayDataForPosition(
this.ctx,
this.data,
this.whirlpoolData,
IGNORE_CACHE,
);
if (lowerTickArray) {
this.lowerTickArrayData = lowerTickArray;
}
if (upperTickArray) {
this.upperTickArrayData = upperTickArray;
}
}
private async updateFeesAndRewards(): Promise<Instruction> {
const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool);
if (!whirlpool) {
throw new Error(
`Unable to fetch whirlpool(${this.data.whirlpool}) for this position(${this.address}).`,
);
}
const [tickArrayLowerPda, tickArrayUpperPda] = [
this.data.tickLowerIndex,
this.data.tickUpperIndex,
].map((tickIndex) =>
PDAUtil.getTickArrayFromTickIndex(
tickIndex,
whirlpool.tickSpacing,
this.data.whirlpool,
this.ctx.program.programId,
),
);
const updateIx = updateFeesAndRewardsIx(this.ctx.program, {
whirlpool: this.data.whirlpool,
position: this.address,
tickArrayLower: tickArrayLowerPda.publicKey,
tickArrayUpper: tickArrayUpperPda.publicKey,
});
return updateIx;
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/impl/util.ts
|
import BN from "bn.js";
import type { TokenInfo } from "..";
import { PoolUtil } from "..";
import type {
WhirlpoolAccountFetchOptions,
WhirlpoolAccountFetcherInterface,
} from "../network/public/fetcher";
import type {
TokenAccountInfo,
WhirlpoolData,
WhirlpoolRewardInfo,
WhirlpoolRewardInfoData,
} from "../types/public";
export async function getTokenMintInfos(
fetcher: WhirlpoolAccountFetcherInterface,
data: WhirlpoolData,
opts?: WhirlpoolAccountFetchOptions,
): Promise<TokenInfo[]> {
const mintA = data.tokenMintA;
const infoA = await fetcher.getMintInfo(mintA, opts);
if (!infoA) {
throw new Error(`Unable to fetch MintInfo for mint - ${mintA}`);
}
const mintB = data.tokenMintB;
const infoB = await fetcher.getMintInfo(mintB, opts);
if (!infoB) {
throw new Error(`Unable to fetch MintInfo for mint - ${mintB}`);
}
return [
{ mint: mintA, ...infoA },
{ mint: mintB, ...infoB },
];
}
export async function getRewardInfos(
fetcher: WhirlpoolAccountFetcherInterface,
data: WhirlpoolData,
opts?: WhirlpoolAccountFetchOptions,
): Promise<WhirlpoolRewardInfo[]> {
const rewardInfos: WhirlpoolRewardInfo[] = [];
for (const rewardInfo of data.rewardInfos) {
rewardInfos.push(await getRewardInfo(fetcher, rewardInfo, opts));
}
return rewardInfos;
}
async function getRewardInfo(
fetcher: WhirlpoolAccountFetcherInterface,
data: WhirlpoolRewardInfoData,
opts?: WhirlpoolAccountFetchOptions,
): Promise<WhirlpoolRewardInfo> {
const rewardInfo = { ...data, initialized: false, vaultAmount: new BN(0) };
if (PoolUtil.isRewardInitialized(data)) {
const vaultInfo = await fetcher.getTokenInfo(data.vault, opts);
if (!vaultInfo) {
throw new Error(
`Unable to fetch TokenAccountInfo for vault - ${data.vault}`,
);
}
rewardInfo.initialized = true;
rewardInfo.vaultAmount = new BN(vaultInfo.amount.toString());
}
return rewardInfo;
}
export async function getTokenVaultAccountInfos(
fetcher: WhirlpoolAccountFetcherInterface,
data: WhirlpoolData,
opts?: WhirlpoolAccountFetchOptions,
): Promise<TokenAccountInfo[]> {
const vaultA = data.tokenVaultA;
const vaultInfoA = await fetcher.getTokenInfo(vaultA, opts);
if (!vaultInfoA) {
throw new Error(`Unable to fetch TokenAccountInfo for vault - ${vaultA}`);
}
const vaultB = data.tokenVaultB;
const vaultInfoB = await fetcher.getTokenInfo(vaultB, opts);
if (!vaultInfoB) {
throw new Error(`Unable to fetch TokenAccountInfo for vault - ${vaultB}`);
}
return [vaultInfoA, vaultInfoB];
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/impl/whirlpool-client-impl.ts
|
import type { Address } from "@coral-xyz/anchor";
import { AddressUtil, TransactionBuilder } from "@orca-so/common-sdk";
import { Keypair, PublicKey } from "@solana/web3.js";
import invariant from "tiny-invariant";
import type { WhirlpoolContext } from "../context";
import { initTickArrayIx } from "../instructions";
import {
collectAllForPositionAddressesTxns,
collectProtocolFees,
} from "../instructions/composites";
import { WhirlpoolIx } from "../ix";
import type {
WhirlpoolAccountFetchOptions,
WhirlpoolAccountFetcherInterface,
} from "../network/public/fetcher";
import { IGNORE_CACHE, PREFER_CACHE } from "../network/public/fetcher";
import type { WhirlpoolRouter } from "../router/public";
import { WhirlpoolRouterBuilder } from "../router/public";
import type { WhirlpoolData } from "../types/public";
import { SPLASH_POOL_TICK_SPACING } from "../types/public";
import { getTickArrayDataForPosition } from "../utils/builder/position-builder-util";
import { PDAUtil, PoolUtil, PriceMath, TickUtil } from "../utils/public";
import type { Position, Whirlpool, WhirlpoolClient } from "../whirlpool-client";
import { PositionImpl } from "./position-impl";
import {
getRewardInfos,
getTokenMintInfos,
getTokenVaultAccountInfos,
} from "./util";
import { WhirlpoolImpl } from "./whirlpool-impl";
import type { TokenExtensionContextForPool } from "../utils/public/token-extension-util";
import {
NO_TOKEN_EXTENSION_CONTEXT,
TokenExtensionUtil,
} from "../utils/public/token-extension-util";
import Decimal from "decimal.js";
export class WhirlpoolClientImpl implements WhirlpoolClient {
constructor(readonly ctx: WhirlpoolContext) {}
public getContext(): WhirlpoolContext {
return this.ctx;
}
public getFetcher(): WhirlpoolAccountFetcherInterface {
return this.ctx.fetcher;
}
public getRouter(poolAddresses: Address[]): Promise<WhirlpoolRouter> {
return WhirlpoolRouterBuilder.buildWithPools(this.ctx, poolAddresses);
}
public async getPool(
poolAddress: Address,
opts = PREFER_CACHE,
): Promise<Whirlpool> {
const account = await this.ctx.fetcher.getPool(poolAddress, opts);
if (!account) {
throw new Error(`Unable to fetch Whirlpool at address at ${poolAddress}`);
}
const tokenInfos = await getTokenMintInfos(this.ctx.fetcher, account, opts);
const vaultInfos = await getTokenVaultAccountInfos(
this.ctx.fetcher,
account,
opts,
);
const rewardInfos = await getRewardInfos(this.ctx.fetcher, account, opts);
return new WhirlpoolImpl(
this.ctx,
AddressUtil.toPubKey(poolAddress),
tokenInfos[0],
tokenInfos[1],
vaultInfos[0],
vaultInfos[1],
rewardInfos,
account,
);
}
public async getPools(
poolAddresses: Address[],
opts = PREFER_CACHE,
): Promise<Whirlpool[]> {
const accounts = Array.from(
(await this.ctx.fetcher.getPools(poolAddresses, opts)).values(),
).filter((account): account is WhirlpoolData => !!account);
if (accounts.length !== poolAddresses.length) {
throw new Error(
`Unable to fetch all Whirlpools at addresses ${poolAddresses}`,
);
}
const tokenMints = new Set<string>();
const tokenAccounts = new Set<string>();
accounts.forEach((account) => {
tokenMints.add(account.tokenMintA.toBase58());
tokenMints.add(account.tokenMintB.toBase58());
tokenAccounts.add(account.tokenVaultA.toBase58());
tokenAccounts.add(account.tokenVaultB.toBase58());
account.rewardInfos.forEach((rewardInfo) => {
if (PoolUtil.isRewardInitialized(rewardInfo)) {
tokenAccounts.add(rewardInfo.vault.toBase58());
}
});
});
await this.ctx.fetcher.getMintInfos(Array.from(tokenMints), opts);
await this.ctx.fetcher.getTokenInfos(Array.from(tokenAccounts), opts);
const whirlpools: Whirlpool[] = [];
for (let i = 0; i < accounts.length; i++) {
const account = accounts[i];
const poolAddress = poolAddresses[i];
const tokenInfos = await getTokenMintInfos(
this.ctx.fetcher,
account,
PREFER_CACHE,
);
const vaultInfos = await getTokenVaultAccountInfos(
this.ctx.fetcher,
account,
PREFER_CACHE,
);
const rewardInfos = await getRewardInfos(
this.ctx.fetcher,
account,
PREFER_CACHE,
);
whirlpools.push(
new WhirlpoolImpl(
this.ctx,
AddressUtil.toPubKey(poolAddress),
tokenInfos[0],
tokenInfos[1],
vaultInfos[0],
vaultInfos[1],
rewardInfos,
account,
),
);
}
return whirlpools;
}
public async getPosition(
positionAddress: Address,
opts = PREFER_CACHE,
): Promise<Position> {
const account = await this.ctx.fetcher.getPosition(positionAddress, opts);
if (!account) {
throw new Error(
`Unable to fetch Position at address at ${positionAddress}`,
);
}
const whirlAccount = await this.ctx.fetcher.getPool(
account.whirlpool,
opts,
);
if (!whirlAccount) {
throw new Error(
`Unable to fetch Whirlpool for Position at address at ${positionAddress}`,
);
}
const positionMint = await this.ctx.fetcher.getMintInfo(
account.positionMint,
opts,
);
if (!positionMint) {
throw new Error(
`Unable to fetch Mint for Position at address at ${positionAddress}`,
);
}
const [lowerTickArray, upperTickArray] = await getTickArrayDataForPosition(
this.ctx,
account,
whirlAccount,
opts,
);
if (!lowerTickArray || !upperTickArray) {
throw new Error(
`Unable to fetch TickArrays for Position at address at ${positionAddress}`,
);
}
return new PositionImpl(
this.ctx,
AddressUtil.toPubKey(positionAddress),
account,
whirlAccount,
lowerTickArray,
upperTickArray,
positionMint.tokenProgram,
);
}
public async getPositions(
positionAddresses: Address[],
opts = PREFER_CACHE,
): Promise<Record<string, Position | null>> {
// TODO: Prefetch and use fetcher as a cache - Think of a cleaner way to prefetch
const positions = Array.from(
(await this.ctx.fetcher.getPositions(positionAddresses, opts)).values(),
);
const whirlpoolAddrs = positions
.map((position) => position?.whirlpool.toBase58())
.flatMap((x) => (!!x ? x : []));
await this.ctx.fetcher.getPools(whirlpoolAddrs, opts);
const positionMintAddrs = positions
.map((position) => position?.positionMint.toBase58())
.flatMap((x) => (!!x ? x : []));
await this.ctx.fetcher.getMintInfos(positionMintAddrs, opts);
const tickArrayAddresses: Set<string> = new Set();
await Promise.all(
positions.map(async (pos) => {
if (pos) {
const pool = await this.ctx.fetcher.getPool(
pos.whirlpool,
PREFER_CACHE,
);
if (pool) {
const lowerTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
pos.tickLowerIndex,
pool.tickSpacing,
pos.whirlpool,
this.ctx.program.programId,
).publicKey;
const upperTickArrayPda = PDAUtil.getTickArrayFromTickIndex(
pos.tickUpperIndex,
pool.tickSpacing,
pos.whirlpool,
this.ctx.program.programId,
).publicKey;
tickArrayAddresses.add(lowerTickArrayPda.toBase58());
tickArrayAddresses.add(upperTickArrayPda.toBase58());
}
}
}),
);
await this.ctx.fetcher.getTickArrays(
Array.from(tickArrayAddresses),
IGNORE_CACHE,
);
// Use getPosition and the prefetched values to generate the Positions
const results = await Promise.all(
positionAddresses.map(async (pos) => {
try {
const position = await this.getPosition(pos, PREFER_CACHE);
return [pos, position];
} catch {
return [pos, null];
}
}),
);
return Object.fromEntries(results);
}
public async createSplashPool(
whirlpoolsConfig: Address,
tokenMintA: Address,
tokenMintB: Address,
initialPrice = new Decimal(1),
funder: Address,
opts = PREFER_CACHE,
): Promise<{ poolKey: PublicKey; tx: TransactionBuilder }> {
const correctTokenOrder = PoolUtil.orderMints(tokenMintA, tokenMintB).map(
(addr) => addr.toString(),
);
invariant(
correctTokenOrder[0] === tokenMintA.toString(),
"Token order needs to be flipped to match the canonical ordering (i.e. sorted on the byte repr. of the mint pubkeys)",
);
const mintInfos = await this.getFetcher().getMintInfos(
[tokenMintA, tokenMintB],
opts,
);
invariant(
mintInfos.size === 2,
"At least one of the token mints cannot be found.",
);
const tokenExtensionCtx: TokenExtensionContextForPool = {
...NO_TOKEN_EXTENSION_CONTEXT,
tokenMintWithProgramA: mintInfos.get(tokenMintA.toString())!,
tokenMintWithProgramB: mintInfos.get(tokenMintB.toString())!,
};
whirlpoolsConfig = AddressUtil.toPubKey(whirlpoolsConfig);
const feeTierKey = PDAUtil.getFeeTier(
this.ctx.program.programId,
whirlpoolsConfig,
SPLASH_POOL_TICK_SPACING,
).publicKey;
const whirlpoolPda = PDAUtil.getWhirlpool(
this.ctx.program.programId,
whirlpoolsConfig,
new PublicKey(tokenMintA),
new PublicKey(tokenMintB),
SPLASH_POOL_TICK_SPACING,
);
const tokenDecimalsA = mintInfos.get(tokenMintA.toString())?.decimals ?? 0;
const tokenDecimalsB = mintInfos.get(tokenMintB.toString())?.decimals ?? 0;
const initSqrtPrice = PriceMath.priceToSqrtPriceX64(
initialPrice,
tokenDecimalsA,
tokenDecimalsB,
);
const tokenVaultAKeypair = Keypair.generate();
const tokenVaultBKeypair = Keypair.generate();
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
const tokenBadgeA = PDAUtil.getTokenBadge(
this.ctx.program.programId,
whirlpoolsConfig,
AddressUtil.toPubKey(tokenMintA),
).publicKey;
const tokenBadgeB = PDAUtil.getTokenBadge(
this.ctx.program.programId,
whirlpoolsConfig,
AddressUtil.toPubKey(tokenMintB),
).publicKey;
const baseParams = {
initSqrtPrice,
whirlpoolsConfig,
whirlpoolPda,
tokenMintA: new PublicKey(tokenMintA),
tokenMintB: new PublicKey(tokenMintB),
tokenVaultAKeypair,
tokenVaultBKeypair,
feeTierKey,
tickSpacing: SPLASH_POOL_TICK_SPACING,
funder: new PublicKey(funder),
};
const initPoolIx = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? WhirlpoolIx.initializePoolIx(this.ctx.program, baseParams)
: WhirlpoolIx.initializePoolV2Ix(this.ctx.program, {
...baseParams,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
tokenBadgeA,
tokenBadgeB,
});
txBuilder.addInstruction(initPoolIx);
const [startTickIndex, endTickIndex] = TickUtil.getFullRangeTickIndex(
SPLASH_POOL_TICK_SPACING,
);
const startInitializableTickIndex = TickUtil.getStartTickIndex(
startTickIndex,
SPLASH_POOL_TICK_SPACING,
);
const endInitializableTickIndex = TickUtil.getStartTickIndex(
endTickIndex,
SPLASH_POOL_TICK_SPACING,
);
const startTickArrayPda = PDAUtil.getTickArray(
this.ctx.program.programId,
whirlpoolPda.publicKey,
startInitializableTickIndex,
);
const endTickArrayPda = PDAUtil.getTickArray(
this.ctx.program.programId,
whirlpoolPda.publicKey,
endInitializableTickIndex,
);
txBuilder.addInstruction(
initTickArrayIx(this.ctx.program, {
startTick: startInitializableTickIndex,
tickArrayPda: startTickArrayPda,
whirlpool: whirlpoolPda.publicKey,
funder: AddressUtil.toPubKey(funder),
}),
);
txBuilder.addInstruction(
initTickArrayIx(this.ctx.program, {
startTick: endInitializableTickIndex,
tickArrayPda: endTickArrayPda,
whirlpool: whirlpoolPda.publicKey,
funder: AddressUtil.toPubKey(funder),
}),
);
return {
poolKey: whirlpoolPda.publicKey,
tx: txBuilder,
};
}
public async createPool(
whirlpoolsConfig: Address,
tokenMintA: Address,
tokenMintB: Address,
tickSpacing: number,
initialTick: number,
funder: Address,
opts = PREFER_CACHE,
): Promise<{ poolKey: PublicKey; tx: TransactionBuilder }> {
invariant(
TickUtil.checkTickInBounds(initialTick),
"initialTick is out of bounds.",
);
invariant(
TickUtil.isTickInitializable(initialTick, tickSpacing),
`initial tick ${initialTick} is not an initializable tick for tick-spacing ${tickSpacing}`,
);
const correctTokenOrder = PoolUtil.orderMints(tokenMintA, tokenMintB).map(
(addr) => addr.toString(),
);
invariant(
correctTokenOrder[0] === tokenMintA.toString(),
"Token order needs to be flipped to match the canonical ordering (i.e. sorted on the byte repr. of the mint pubkeys)",
);
const mintInfos = await this.ctx.fetcher.getMintInfos(
[tokenMintA, tokenMintB],
opts,
);
const tokenExtensionCtx: TokenExtensionContextForPool = {
...NO_TOKEN_EXTENSION_CONTEXT,
tokenMintWithProgramA: mintInfos.get(tokenMintA.toString())!,
tokenMintWithProgramB: mintInfos.get(tokenMintB.toString())!,
};
whirlpoolsConfig = AddressUtil.toPubKey(whirlpoolsConfig);
const feeTierKey = PDAUtil.getFeeTier(
this.ctx.program.programId,
whirlpoolsConfig,
tickSpacing,
).publicKey;
const initSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(initialTick);
const tokenVaultAKeypair = Keypair.generate();
const tokenVaultBKeypair = Keypair.generate();
const whirlpoolPda = PDAUtil.getWhirlpool(
this.ctx.program.programId,
whirlpoolsConfig,
new PublicKey(tokenMintA),
new PublicKey(tokenMintB),
tickSpacing,
);
const feeTier = await this.ctx.fetcher.getFeeTier(feeTierKey, opts);
invariant(!!feeTier, `Fee tier for ${tickSpacing} doesn't exist`);
const txBuilder = new TransactionBuilder(
this.ctx.provider.connection,
this.ctx.provider.wallet,
this.ctx.txBuilderOpts,
);
const tokenBadgeA = PDAUtil.getTokenBadge(
this.ctx.program.programId,
whirlpoolsConfig,
AddressUtil.toPubKey(tokenMintA),
).publicKey;
const tokenBadgeB = PDAUtil.getTokenBadge(
this.ctx.program.programId,
whirlpoolsConfig,
AddressUtil.toPubKey(tokenMintB),
).publicKey;
const baseParams = {
initSqrtPrice,
whirlpoolsConfig,
whirlpoolPda,
tokenMintA: new PublicKey(tokenMintA),
tokenMintB: new PublicKey(tokenMintB),
tokenVaultAKeypair,
tokenVaultBKeypair,
feeTierKey,
tickSpacing,
funder: new PublicKey(funder),
};
const initPoolIx = !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? WhirlpoolIx.initializePoolIx(this.ctx.program, baseParams)
: WhirlpoolIx.initializePoolV2Ix(this.ctx.program, {
...baseParams,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
tokenBadgeA,
tokenBadgeB,
});
const initialTickArrayStartTick = TickUtil.getStartTickIndex(
initialTick,
tickSpacing,
);
const initialTickArrayPda = PDAUtil.getTickArray(
this.ctx.program.programId,
whirlpoolPda.publicKey,
initialTickArrayStartTick,
);
txBuilder.addInstruction(initPoolIx);
txBuilder.addInstruction(
initTickArrayIx(this.ctx.program, {
startTick: initialTickArrayStartTick,
tickArrayPda: initialTickArrayPda,
whirlpool: whirlpoolPda.publicKey,
funder: AddressUtil.toPubKey(funder),
}),
);
return {
poolKey: whirlpoolPda.publicKey,
tx: txBuilder,
};
}
public async collectFeesAndRewardsForPositions(
positionAddresses: Address[],
opts?: WhirlpoolAccountFetchOptions,
): Promise<TransactionBuilder[]> {
const walletKey = this.ctx.wallet.publicKey;
return collectAllForPositionAddressesTxns(
this.ctx,
{
positions: positionAddresses,
receiver: walletKey,
positionAuthority: walletKey,
positionOwner: walletKey,
payer: walletKey,
},
opts,
);
}
public async collectProtocolFeesForPools(
poolAddresses: Address[],
): Promise<TransactionBuilder> {
return collectProtocolFees(this.ctx, poolAddresses);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/update-fees-and-rewards-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to update fees and reward values for a position.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param position - PublicKey for the position will be opened for.
* @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index.
* @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index.
*/
export type UpdateFeesAndRewardsParams = {
whirlpool: PublicKey;
position: PublicKey;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
};
/**
* Update the accrued fees and rewards for a position.
*
* #### Special Errors
* `TickNotFound` - Provided tick array account does not contain the tick for this position.
* `LiquidityZero` - Position has zero liquidity and therefore already has the most updated fees and reward values.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - UpdateFeesAndRewardsParams object
* @returns - Instruction to perform the action.
*/
export function updateFeesAndRewardsIx(
program: Program<Whirlpool>,
params: UpdateFeesAndRewardsParams,
): Instruction {
const { whirlpool, position, tickArrayLower, tickArrayUpper } = params;
const ix = program.instruction.updateFeesAndRewards({
accounts: {
whirlpool,
position,
tickArrayLower,
tickArrayUpper,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-reward-authority-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to update the reward authority at a particular rewardIndex on a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool to update.
* @param rewardIndex - The reward index that we'd like to update. (0 <= index <= NUM_REWARDS).
* @param rewardAuthority - The current rewardAuthority in the Whirlpool at the rewardIndex
* @param newRewardAuthority - The new rewardAuthority in the Whirlpool at the rewardIndex
*/
export type SetRewardAuthorityParams = {
whirlpool: PublicKey;
rewardIndex: number;
rewardAuthority: PublicKey;
newRewardAuthority: PublicKey;
};
/**
* Set the whirlpool reward authority at the provided `reward_index`.
* Only the current reward authority for this reward index has permission to invoke this instruction.
*
* #### Special Errors
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetRewardAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setRewardAuthorityIx(
program: Program<Whirlpool>,
params: SetRewardAuthorityParams,
): Instruction {
const { whirlpool, rewardAuthority, newRewardAuthority, rewardIndex } =
params;
const ix = program.instruction.setRewardAuthority(rewardIndex, {
accounts: {
whirlpool,
rewardAuthority,
newRewardAuthority,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/swap-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type BN from "bn.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Raw parameters and accounts to swap on a Whirlpool
*
* @category Instruction Types
* @param swapInput - Parameters in {@link SwapInput}
* @param whirlpool - PublicKey for the whirlpool that the swap will occur on
* @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet
* @param tokenOwnerAccountB - PublicKey for the associated token account for tokenB in the collection wallet
* @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.
* @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.
* @param oracle - PublicKey for the oracle account for this Whirlpool.
* @param tokenAuthority - authority to withdraw tokens from the input token account
*/
export type SwapParams = SwapInput & {
whirlpool: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
oracle: PublicKey;
tokenAuthority: PublicKey;
};
/**
* Parameters that describe the nature of a swap on a Whirlpool.
*
* @category Instruction Types
* @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A.
* @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents
* the input token of the swap.
* @param amount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).
* @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).
* @param sqrtPriceLimit - The maximum/minimum price the swap will swap to.
* @param tickArray0 - PublicKey of the tick-array where the Whirlpool's currentTickIndex resides in
* @param tickArray1 - The next tick-array in the swap direction. If the swap will not reach the next tick-aray, input the same array as tickArray0.
* @param tickArray2 - The next tick-array in the swap direction after tickArray2. If the swap will not reach the next tick-aray, input the same array as tickArray1.
* @param supplementalTickArrays - (V2 only) Optional array of PublicKey for supplemental tick arrays. swap instruction will ignore this parameter.
*/
export type SwapInput = {
amount: BN;
otherAmountThreshold: BN;
sqrtPriceLimit: BN;
amountSpecifiedIsInput: boolean;
aToB: boolean;
tickArray0: PublicKey;
tickArray1: PublicKey;
tickArray2: PublicKey;
supplementalTickArrays?: PublicKey[];
};
/**
* Parameters to swap on a Whirlpool with developer fees
*
* @category Instruction Types
* @param swapInput - Parameters in {@link SwapInput}
* @param devFeeAmount - FeeAmount (developer fees) charged on this swap
*/
export type DevFeeSwapInput = SwapInput & {
devFeeAmount: BN;
};
/**
* Perform a swap in this Whirlpool
*
* #### Special Errors
* - `ZeroTradableAmount` - User provided parameter `amount` is 0.
* - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.
* - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.
* - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.
* - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.
* - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.
* - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.
* - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.
* - `AmountCalcOverflow` - The required token amount exceeds the u64 range.
* - `AmountRemainingOverflow` - Result does not match the specified amount.
* - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool.
* - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false.
*
* ### Parameters
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - {@link SwapParams}
* @returns - Instruction to perform the action.
*/
export function swapIx(
program: Program<Whirlpool>,
params: SwapParams,
): Instruction {
const {
amount,
otherAmountThreshold,
sqrtPriceLimit,
amountSpecifiedIsInput,
aToB,
whirlpool,
tokenAuthority,
tokenOwnerAccountA,
tokenVaultA,
tokenOwnerAccountB,
tokenVaultB,
tickArray0,
tickArray1,
tickArray2,
oracle,
} = params;
const ix = program.instruction.swap(
amount,
otherAmountThreshold,
sqrtPriceLimit,
amountSpecifiedIsInput,
aToB,
{
accounts: {
tokenProgram: TOKEN_PROGRAM_ID,
tokenAuthority: tokenAuthority,
whirlpool,
tokenOwnerAccountA,
tokenVaultA,
tokenOwnerAccountB,
tokenVaultB,
tickArray0,
tickArray1,
tickArray2,
oracle,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/open-bundled-position-ix.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { Program } from "@coral-xyz/anchor";
import type { Instruction, PDA } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import { SystemProgram } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to open a bundled position in a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the bundled position will be opened for.
* @param bundledPositionPda - PDA for the derived bundled position address.
* @param positionBundle - PublicKey for the position bundle.
* @param positionBundleTokenAccount - The associated token address for the position bundle token in the owners wallet.
* @param positionBundleAuthority - authority that owns the token corresponding to this desired bundled position.
* @param bundleIndex - The bundle index that holds the bundled position.
* @param tickLowerIndex - The tick specifying the lower end of the bundled position range.
* @param tickUpperIndex - The tick specifying the upper end of the bundled position range.
* @param funder - The account that would fund the creation of this account
*/
export type OpenBundledPositionParams = {
whirlpool: PublicKey;
bundledPositionPda: PDA;
positionBundle: PublicKey;
positionBundleTokenAccount: PublicKey;
positionBundleAuthority: PublicKey;
bundleIndex: number;
tickLowerIndex: number;
tickUpperIndex: number;
funder: PublicKey;
};
/**
* Open a bundled position in a Whirlpool.
* No new tokens are issued because the owner of the position bundle becomes the owner of the position.
* The position will start off with 0 liquidity.
*
* #### Special Errors
* `InvalidBundleIndex` - If the provided bundle index is out of bounds.
* `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - OpenBundledPositionParams object
* @returns - Instruction to perform the action.
*/
export function openBundledPositionIx(
program: Program<Whirlpool>,
params: OpenBundledPositionParams,
): Instruction {
const {
whirlpool,
bundledPositionPda,
positionBundle,
positionBundleTokenAccount,
positionBundleAuthority,
bundleIndex,
tickLowerIndex,
tickUpperIndex,
funder,
} = params;
const ix = program.instruction.openBundledPosition(
bundleIndex,
tickLowerIndex,
tickUpperIndex,
{
accounts: {
bundledPosition: bundledPositionPda.publicKey,
positionBundle,
positionBundleTokenAccount,
positionBundleAuthority,
whirlpool,
funder,
systemProgram: SystemProgram.programId,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-collect-protocol-fees-authority-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to set the collect fee authority in a WhirlpoolsConfig
*
* @category Instruction Types
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param collectProtocolFeesAuthority - The current collectProtocolFeesAuthority in the WhirlpoolsConfig
* @param newCollectProtocolFeesAuthority - The new collectProtocolFeesAuthority in the WhirlpoolsConfig
*/
export type SetCollectProtocolFeesAuthorityParams = {
whirlpoolsConfig: PublicKey;
collectProtocolFeesAuthority: PublicKey;
newCollectProtocolFeesAuthority: PublicKey;
};
/**
* Sets the fee authority to collect protocol fees for a WhirlpoolsConfig.
* Only the current collect protocol fee authority has permission to invoke this instruction.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetCollectProtocolFeesAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setCollectProtocolFeesAuthorityIx(
program: Program<Whirlpool>,
params: SetCollectProtocolFeesAuthorityParams,
): Instruction {
const {
whirlpoolsConfig,
collectProtocolFeesAuthority,
newCollectProtocolFeesAuthority,
} = params;
const ix = program.instruction.setCollectProtocolFeesAuthority({
accounts: {
whirlpoolsConfig,
collectProtocolFeesAuthority,
newCollectProtocolFeesAuthority,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-reward-authority-by-super-authority-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to update the reward authority at a particular rewardIndex on a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space.
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param rewardIndex - The reward index that we'd like to update. (0 <= index <= NUM_REWARDS).
* @param rewardEmissionsSuperAuthority - The current rewardEmissionsSuperAuthority in the WhirlpoolsConfig
* @param newRewardAuthority - The new rewardAuthority in the Whirlpool at the rewardIndex
*/
export type SetRewardAuthorityBySuperAuthorityParams = {
whirlpool: PublicKey;
whirlpoolsConfig: PublicKey;
rewardIndex: number;
rewardEmissionsSuperAuthority: PublicKey;
newRewardAuthority: PublicKey;
};
/**
* Set the whirlpool reward authority at the provided `reward_index`.
* Only the current reward super authority has permission to invoke this instruction.
*
* #### Special Errors
* - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,
* or exceeds NUM_REWARDS.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetRewardAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setRewardAuthorityBySuperAuthorityIx(
program: Program<Whirlpool>,
params: SetRewardAuthorityBySuperAuthorityParams,
): Instruction {
const {
whirlpoolsConfig,
whirlpool,
rewardEmissionsSuperAuthority,
newRewardAuthority,
rewardIndex,
} = params;
const ix = program.instruction.setRewardAuthorityBySuperAuthority(
rewardIndex,
{
accounts: {
whirlpoolsConfig,
whirlpool,
rewardEmissionsSuperAuthority,
newRewardAuthority,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/decrease-liquidity-ix.ts
|
import type { BN, Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to remove liquidity from a position.
*
* @category Instruction Types
* @param liquidityAmount - The total amount of Liquidity the user is withdrawing
* @param tokenMinA - The minimum amount of token A to remove from the position.
* @param tokenMinB - The minimum amount of token B to remove from the position.
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param position - PublicKey for the position will be opened for.
* @param positionTokenAccount - PublicKey for the position token's associated token address.
* @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from.
* @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from.
* @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.
* @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.
* @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index.
* @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index.
* @param positionAuthority - authority that owns the token corresponding to this desired position.
*/
export type DecreaseLiquidityParams = {
whirlpool: PublicKey;
position: PublicKey;
positionTokenAccount: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
positionAuthority: PublicKey;
} & DecreaseLiquidityInput;
/**
* @category Instruction Types
*/
export type DecreaseLiquidityInput = {
tokenMinA: BN;
tokenMinB: BN;
liquidityAmount: BN;
};
/**
* Remove liquidity to a position in the Whirlpool.
*
* #### Special Errors
* - `LiquidityZero` - Provided liquidity amount is zero.
* - `LiquidityTooHigh` - Provided liquidity exceeds u128::max.
* - `TokenMinSubceeded` - The required token to perform this operation subceeds the user defined amount.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - DecreaseLiquidityParams object
* @returns - Instruction to perform the action.
*/
export function decreaseLiquidityIx(
program: Program<Whirlpool>,
params: DecreaseLiquidityParams,
): Instruction {
const {
liquidityAmount,
tokenMinA,
tokenMinB,
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
tickArrayLower,
tickArrayUpper,
} = params;
const ix = program.instruction.decreaseLiquidity(
liquidityAmount,
tokenMinA,
tokenMinB,
{
accounts: {
whirlpool,
tokenProgram: TOKEN_PROGRAM_ID,
positionAuthority,
position,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
tickArrayLower,
tickArrayUpper,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/collect-reward-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to collect rewards from a reward index in a position.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param position - PublicKey for the position will be opened for.
* @param positionTokenAccount - PublicKey for the position token's associated token address.
* @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).
* @param rewardOwnerAccount - PublicKey for the reward token account that the reward will deposit into.
* @param rewardVault - PublicKey of the vault account that reward will be withdrawn from.
* @param positionAuthority - authority that owns the token corresponding to this desired position.
*/
export type CollectRewardParams = {
whirlpool: PublicKey;
position: PublicKey;
positionTokenAccount: PublicKey;
rewardIndex: number;
rewardOwnerAccount: PublicKey;
rewardVault: PublicKey;
positionAuthority: PublicKey;
};
/**
* Collect rewards accrued for this reward index in a position.
* Call updateFeesAndRewards before this to update the position to the newest accrued values.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - CollectRewardParams object
* @returns - Instruction to perform the action.
*/
export function collectRewardIx(
program: Program<Whirlpool>,
params: CollectRewardParams,
): Instruction {
const {
whirlpool,
positionAuthority,
position,
positionTokenAccount,
rewardOwnerAccount,
rewardVault,
rewardIndex,
} = params;
const ix = program.instruction.collectReward(rewardIndex, {
accounts: {
whirlpool,
positionAuthority,
position,
positionTokenAccount,
rewardOwnerAccount,
rewardVault,
tokenProgram: TOKEN_PROGRAM_ID,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-protocol-fee-rate-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to set fee rate for a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space.
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.
* @param protocolFeeRate - The new default protocol fee rate for this pool. Stored as a basis point of the total fees collected by feeRate.
*/
export type SetProtocolFeeRateParams = {
whirlpool: PublicKey;
whirlpoolsConfig: PublicKey;
feeAuthority: PublicKey;
protocolFeeRate: number;
};
/**
* Sets the protocol fee rate for a Whirlpool.
* Only the current fee authority has permission to invoke this instruction.
*
* #### Special Errors
* - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetFeeRateParams object
* @returns - Instruction to perform the action.
*/
export function setProtocolFeeRateIx(
program: Program<Whirlpool>,
params: SetProtocolFeeRateParams,
): Instruction {
const { whirlpoolsConfig, whirlpool, feeAuthority, protocolFeeRate } = params;
const ix = program.instruction.setProtocolFeeRate(protocolFeeRate, {
accounts: {
whirlpoolsConfig,
whirlpool,
feeAuthority,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-position-bundle-ix.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { Program } from "@coral-xyz/anchor";
import type { Instruction, PDA } from "@orca-so/common-sdk";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
import type { Keypair, PublicKey } from "@solana/web3.js";
import { SystemProgram } from "@solana/web3.js";
import { METADATA_PROGRAM_ADDRESS, WHIRLPOOL_NFT_UPDATE_AUTH } from "..";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to initialize a PositionBundle account.
*
* @category Instruction Types
* @param owner - PublicKey for the wallet that will host the minted position bundle token.
* @param positionBundlePda - PDA for the derived position bundle address.
* @param positionBundleMintKeypair - Keypair for the mint for the position bundle token.
* @param positionBundleTokenAccount - The associated token address for the position bundle token in the owners wallet.
* @param funder - The account that would fund the creation of this account
*/
export type InitializePositionBundleParams = {
owner: PublicKey;
positionBundlePda: PDA;
positionBundleMintKeypair: Keypair;
positionBundleTokenAccount: PublicKey;
funder: PublicKey;
};
/**
* Initializes a PositionBundle account.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - InitializePositionBundleParams object
* @returns - Instruction to perform the action.
*/
export function initializePositionBundleIx(
program: Program<Whirlpool>,
params: InitializePositionBundleParams,
): Instruction {
const {
owner,
positionBundlePda,
positionBundleMintKeypair,
positionBundleTokenAccount,
funder,
} = params;
const ix = program.instruction.initializePositionBundle({
accounts: {
positionBundle: positionBundlePda.publicKey,
positionBundleMint: positionBundleMintKeypair.publicKey,
positionBundleTokenAccount,
positionBundleOwner: owner,
funder,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: SystemProgram.programId,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [positionBundleMintKeypair],
};
}
/**
* Initializes a PositionBundle account.
* Additional Metaplex metadata is appended to identify the token.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - InitializePositionBundleParams object
* @returns - Instruction to perform the action.
*/
export function initializePositionBundleWithMetadataIx(
program: Program<Whirlpool>,
params: InitializePositionBundleParams & { positionBundleMetadataPda: PDA },
): Instruction {
const {
owner,
positionBundlePda,
positionBundleMintKeypair,
positionBundleTokenAccount,
positionBundleMetadataPda,
funder,
} = params;
const ix = program.instruction.initializePositionBundleWithMetadata({
accounts: {
positionBundle: positionBundlePda.publicKey,
positionBundleMint: positionBundleMintKeypair.publicKey,
positionBundleMetadata: positionBundleMetadataPda.publicKey,
positionBundleTokenAccount,
positionBundleOwner: owner,
funder,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: SystemProgram.programId,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
metadataProgram: METADATA_PROGRAM_ADDRESS,
metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [positionBundleMintKeypair],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/two-hop-swap-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type BN from "bn.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to execute a two-hop swap on a Whirlpool.
*
* @category Instruction Types
* @param whirlpoolOne - PublicKey for the whirlpool that the swap-one will occur on
* @param whirlpoolTwo - PublicKey for the whirlpool that the swap-two will occur on
* @param tokenOwnerAccountOneA - PublicKey for the associated token account for tokenA in whirlpoolOne in the collection wallet
* @param tokenOwnerAccountOneB - PublicKey for the associated token account for tokenB in whirlpoolOne in the collection wallet
* @param tokenOwnerAccountTwoA - PublicKey for the associated token account for tokenA in whirlpoolTwo in the collection wallet
* @param tokenOwnerAccountTwoB - PublicKey for the associated token account for tokenB in whirlpoolTwo in the collection wallet
* @param tokenVaultOneA - PublicKey for the tokenA vault for whirlpoolOne.
* @param tokenVaultOneB - PublicKey for the tokenB vault for whirlpoolOne.
* @param tokenVaultTwoA - PublicKey for the tokenA vault for whirlpoolTwo.
* @param tokenVaultTwoB - PublicKey for the tokenB vault for whirlpoolTwo.
* @param oracleOne - PublicKey for the oracle account for this whirlpoolOne.
* @param oracleTwo - PublicKey for the oracle account for this whirlpoolTwo.
* @param tokenAuthority - authority to withdraw tokens from the input token account
* @param swapInput - Parameters in {@link TwoHopSwapInput}
*/
export type TwoHopSwapParams = TwoHopSwapInput & {
whirlpoolOne: PublicKey;
whirlpoolTwo: PublicKey;
tokenOwnerAccountOneA: PublicKey;
tokenOwnerAccountOneB: PublicKey;
tokenOwnerAccountTwoA: PublicKey;
tokenOwnerAccountTwoB: PublicKey;
tokenVaultOneA: PublicKey;
tokenVaultOneB: PublicKey;
tokenVaultTwoA: PublicKey;
tokenVaultTwoB: PublicKey;
oracleOne: PublicKey;
oracleTwo: PublicKey;
tokenAuthority: PublicKey;
};
/**
* Parameters that define a two-hop swap on a Whirlpool.
*
* @category Instruction Types
* @param amount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).
* @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).
* @param amountSpecifiedIsInput - Specifies the token the paramneter `amount`represets. If true, the amount represents
* the input token of the swap.
* @param aToBOne - The direction of the swap-one. True if swapping from A to B. False if swapping from B to A.
* @param aToBTwo - The direction of the swap-two. True if swapping from A to B. False if swapping from B to A.
* @param sqrtPriceLimitOne - The maximum/minimum price that swap-one will swap to.
* @param sqrtPriceLimitTwo - The maximum/minimum price that swap-two will swap to.
* @param tickArrayOne0 - PublicKey of the tick-array of swap-One where the Whirlpool's currentTickIndex resides in
* @param tickArrayOne1 - The next tick-array in the swap direction of swap-One. If the swap will not reach the next tick-aray, input the same array as tickArray0.
* @param tickArrayOne2 - The next tick-array in the swap direction after tickArray2 of swap-One. If the swap will not reach the next tick-aray, input the same array as tickArray1.
* @param tickArrayTwo0 - PublicKey of the tick-array of swap-Two where the Whirlpool's currentTickIndex resides in
* @param tickArrayTwo1 - The next tick-array in the swap direction of swap-Two. If the swap will not reach the next tick-aray, input the same array as tickArray0.
* @param tickArrayTwo2 - The next tick-array in the swap direction after tickArray2 of swap-Two. If the swap will not reach the next tick-aray, input the same array as tickArray1.
* @param supplementalTickArraysOne - (V2 only) Optional array of PublicKey for supplemental tick arrays of whirlpoolOne. twoHopSwap instruction will ignore this parameter.
* @param supplementalTickArraysTwo - (V2 only) Optional array of PublicKey for supplemental tick arrays of whirlpoolTwo. twoHopSwap instruction will ignore this parameter.
*/
export type TwoHopSwapInput = {
amount: BN;
otherAmountThreshold: BN;
amountSpecifiedIsInput: boolean;
aToBOne: boolean;
aToBTwo: boolean;
sqrtPriceLimitOne: BN;
sqrtPriceLimitTwo: BN;
tickArrayOne0: PublicKey;
tickArrayOne1: PublicKey;
tickArrayOne2: PublicKey;
tickArrayTwo0: PublicKey;
tickArrayTwo1: PublicKey;
tickArrayTwo2: PublicKey;
supplementalTickArraysOne?: PublicKey[];
supplementalTickArraysTwo?: PublicKey[];
};
/**
* Perform a two-hop swap in this Whirlpool
*
* #### Special Errors
* - `ZeroTradableAmount` - User provided parameter `amount` is 0.
* - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.
* - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.
* - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.
* - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.
* - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.
* - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.
* - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.
* - `InvalidIntermediaryMint` - Error if the intermediary mint between hop one and two do not equal.
* - `DuplicateTwoHopPool` - Error if whirlpool one & two are the same pool.
* - `AmountCalcOverflow` - The required token amount exceeds the u64 range.
* - `AmountRemainingOverflow` - Result does not match the specified amount.
* - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool.
* - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false.
* - `IntermediateTokenAmountMismatch` - The amount of tokens received from the first hop does not match the amount sent to the second hop.
*
* ### Parameters
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - {@link TwoHopSwapParams} object
* @returns - Instruction to perform the action.
*/
export function twoHopSwapIx(
program: Program<Whirlpool>,
params: TwoHopSwapParams,
): Instruction {
const {
amount,
otherAmountThreshold,
amountSpecifiedIsInput,
aToBOne,
aToBTwo,
sqrtPriceLimitOne,
sqrtPriceLimitTwo,
whirlpoolOne,
whirlpoolTwo,
tokenAuthority,
tokenOwnerAccountOneA,
tokenVaultOneA,
tokenOwnerAccountOneB,
tokenVaultOneB,
tokenOwnerAccountTwoA,
tokenVaultTwoA,
tokenOwnerAccountTwoB,
tokenVaultTwoB,
tickArrayOne0,
tickArrayOne1,
tickArrayOne2,
tickArrayTwo0,
tickArrayTwo1,
tickArrayTwo2,
oracleOne,
oracleTwo,
} = params;
const ix = program.instruction.twoHopSwap(
amount,
otherAmountThreshold,
amountSpecifiedIsInput,
aToBOne,
aToBTwo,
sqrtPriceLimitOne,
sqrtPriceLimitTwo,
{
accounts: {
tokenProgram: TOKEN_PROGRAM_ID,
tokenAuthority,
whirlpoolOne,
whirlpoolTwo,
tokenOwnerAccountOneA,
tokenVaultOneA,
tokenOwnerAccountOneB,
tokenVaultOneB,
tokenOwnerAccountTwoA,
tokenVaultTwoA,
tokenOwnerAccountTwoB,
tokenVaultTwoB,
tickArrayOne0,
tickArrayOne1,
tickArrayOne2,
tickArrayTwo0,
tickArrayTwo1,
tickArrayTwo2,
oracleOne,
oracleTwo,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.