repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __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/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
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/close-bundled-position-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 close a bundled position in a Whirlpool.
*
* @category Instruction Types
* @param bundledPosition - PublicKey for the bundled position.
* @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 receiver - PublicKey for the wallet that will receive the rented lamports.
*/
export type CloseBundledPositionParams = {
bundledPosition: PublicKey;
positionBundle: PublicKey;
positionBundleTokenAccount: PublicKey;
positionBundleAuthority: PublicKey;
bundleIndex: number;
receiver: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - CloseBundledPositionParams object
* @returns - Instruction to perform the action.
*/
export function closeBundledPositionIx(
program: Program<Whirlpool>,
params: CloseBundledPositionParams,
): Instruction {
const {
bundledPosition,
positionBundle,
positionBundleTokenAccount,
positionBundleAuthority,
bundleIndex,
receiver,
} = params;
const ix = program.instruction.closeBundledPosition(bundleIndex, {
accounts: {
bundledPosition,
positionBundle,
positionBundleTokenAccount,
positionBundleAuthority,
receiver,
},
});
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/delete-position-bundle-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 delete a PositionBundle account.
*
* @category Instruction Types
* @param owner - PublicKey for the wallet that owns the position bundle token.
* @param positionBundle - PublicKey for the position bundle.
* @param positionBundleMint - PublicKey for the mint for the position bundle token.
* @param positionBundleTokenAccount - The associated token address for the position bundle token in the owners wallet.
* @param receiver - PublicKey for the wallet that will receive the rented lamports.
*/
export type DeletePositionBundleParams = {
owner: PublicKey;
positionBundle: PublicKey;
positionBundleMint: PublicKey;
positionBundleTokenAccount: PublicKey;
receiver: PublicKey;
};
/**
* Deletes a PositionBundle account.
*
* #### Special Errors
* `PositionBundleNotDeletable` - The provided position bundle has open positions.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - DeletePositionBundleParams object
* @returns - Instruction to perform the action.
*/
export function deletePositionBundleIx(
program: Program<Whirlpool>,
params: DeletePositionBundleParams,
): Instruction {
const {
owner,
positionBundle,
positionBundleMint,
positionBundleTokenAccount,
receiver,
} = params;
const ix = program.instruction.deletePositionBundle({
accounts: {
positionBundle: positionBundle,
positionBundleMint: positionBundleMint,
positionBundleTokenAccount,
positionBundleOwner: owner,
receiver,
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-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 feeRate - The new fee rate for this fee-tier. Stored as a hundredths of a basis point.
*/
export type SetFeeRateParams = {
whirlpool: PublicKey;
whirlpoolsConfig: PublicKey;
feeAuthority: PublicKey;
feeRate: number;
};
/**
* 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.
*
* @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 setFeeRateIx(
program: Program<Whirlpool>,
params: SetFeeRateParams,
): Instruction {
const { whirlpoolsConfig, whirlpool, feeAuthority, feeRate } = params;
const ix = program.instruction.setFeeRate(feeRate, {
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-tick-array-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 type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to initialize a TickArray account.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the initialized tick-array will host ticks for.
* @param tickArrayPda - PDA for the tick array account that will be initialized
* @param startTick - The starting tick index for this tick-array. Has to be a multiple of TickArray size & the tick spacing of this pool.
* @param funder - The account that would fund the creation of this account
*/
export type InitTickArrayParams = {
whirlpool: PublicKey;
tickArrayPda: PDA;
startTick: number;
funder: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - InitTickArrayParams object
* @returns - Instruction to perform the action.
*/
export function initTickArrayIx(
program: Program<Whirlpool>,
params: InitTickArrayParams,
): Instruction {
const { whirlpool, funder, tickArrayPda } = params;
const ix = program.instruction.initializeTickArray(params.startTick, {
accounts: {
whirlpool,
funder,
tickArray: tickArrayPda.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
});
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-default-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";
import { PDAUtil } from "../utils/public";
/**
* Parameters to set the default fee rate for a FeeTier.
*
* @category Instruction Types
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this fee-tier is initialized in
* @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.
* @param tickSpacing - The tick spacing of the fee-tier that we would like to update.
* @param defaultFeeRate - The new default fee rate for this fee-tier. Stored as a hundredths of a basis point.
*/
export type SetDefaultFeeRateParams = {
whirlpoolsConfig: PublicKey;
feeAuthority: PublicKey;
tickSpacing: number;
defaultFeeRate: number;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetDefaultFeeRateParams object
* @returns - Instruction to perform the action.
*/
export function setDefaultFeeRateIx(
program: Program<Whirlpool>,
params: SetDefaultFeeRateParams,
): Instruction {
const { whirlpoolsConfig, feeAuthority, tickSpacing, defaultFeeRate } =
params;
const feeTierPda = PDAUtil.getFeeTier(
program.programId,
whirlpoolsConfig,
tickSpacing,
);
const ix = program.instruction.setDefaultFeeRate(defaultFeeRate, {
accounts: {
whirlpoolsConfig,
feeTier: feeTierPda.publicKey,
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-reward-ix.ts
|
import * as anchor from "@coral-xyz/anchor";
import type { Program } from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { Keypair, PublicKey } from "@solana/web3.js";
import { SystemProgram } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to initialize a rewards for a Whirlpool
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool config space that the fee-tier will be initialized for.
* @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).
* @param rewardMint - PublicKey for the reward mint that we'd use for the reward index.
* @param rewardVaultKeypair - Keypair of the vault for this reward index.
* @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool
* @param funder - The account that would fund the creation of this account
*/
export type InitializeRewardParams = {
whirlpool: PublicKey;
rewardIndex: number;
rewardMint: PublicKey;
rewardVaultKeypair: Keypair;
rewardAuthority: PublicKey;
funder: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - InitializeRewardParams object
* @returns - Instruction to perform the action.
*/
export function initializeRewardIx(
program: Program<Whirlpool>,
params: InitializeRewardParams,
): Instruction {
const {
rewardAuthority,
funder,
whirlpool,
rewardMint,
rewardVaultKeypair,
rewardIndex,
} = params;
const ix = program.instruction.initializeReward(rewardIndex, {
accounts: {
rewardAuthority,
funder,
whirlpool,
rewardMint,
rewardVault: rewardVaultKeypair.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: SystemProgram.programId,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [rewardVaultKeypair],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-config-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Keypair, PublicKey } from "@solana/web3.js";
import { SystemProgram } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to initialize a WhirlpoolsConfig account.
*
* @category Instruction Types
* @param whirlpoolsConfigKeypair - Generated keypair for the WhirlpoolsConfig.
* @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees.
* @param collect_protocol_fees_authority - Authority authorized to collect protocol fees.
* @param rewardEmissionsSuperAuthority - Authority authorized to set reward authorities in pools.
* @param defaultProtocolFeeRate - The default protocol fee rate. Stored as a basis point of the total fees collected by feeRate.
* @param funder - The account that would fund the creation of this account
*/
export type InitConfigParams = {
whirlpoolsConfigKeypair: Keypair;
feeAuthority: PublicKey;
collectProtocolFeesAuthority: PublicKey;
rewardEmissionsSuperAuthority: PublicKey;
defaultProtocolFeeRate: number;
funder: PublicKey;
};
/**
* Initializes a WhirlpoolsConfig account that hosts info & authorities
* required to govern a set of Whirlpools.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - InitConfigParams object
* @returns - Instruction to perform the action.
*/
export function initializeConfigIx(
program: Program<Whirlpool>,
params: InitConfigParams,
): Instruction {
const {
feeAuthority,
collectProtocolFeesAuthority,
rewardEmissionsSuperAuthority,
defaultProtocolFeeRate,
funder,
} = params;
const ix = program.instruction.initializeConfig(
feeAuthority,
collectProtocolFeesAuthority,
rewardEmissionsSuperAuthority,
defaultProtocolFeeRate,
{
accounts: {
config: params.whirlpoolsConfigKeypair.publicKey,
funder,
systemProgram: SystemProgram.programId,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [params.whirlpoolsConfigKeypair],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/close-position-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 close a position in a Whirlpool.
*
* @category Instruction Types
* @param receiver - PublicKey for the wallet that will receive the rented lamports.
* @param position - PublicKey for the position.
* @param positionMint - PublicKey for the mint token for the Position token.
* @param positionTokenAccount - The associated token address for the position token in the owners wallet.
* @param positionAuthority - Authority that owns the position token.
*/
export type ClosePositionParams = {
receiver: PublicKey;
position: PublicKey;
positionMint: PublicKey;
positionTokenAccount: PublicKey;
positionAuthority: PublicKey;
};
/**
* Close a position in a Whirlpool. Burns the position token in the owner's wallet.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - ClosePositionParams object
* @returns - Instruction to perform the action.
*/
export function closePositionIx(
program: Program<Whirlpool>,
params: ClosePositionParams,
): Instruction {
const {
positionAuthority,
receiver: receiver,
position: position,
positionMint: positionMint,
positionTokenAccount,
} = params;
const ix = program.instruction.closePosition({
accounts: {
positionAuthority,
receiver,
position,
positionMint,
positionTokenAccount,
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-reward-emissions-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 set rewards emissions for a reward in a Whirlpool
*
* @category Instruction Types
* @param whirlpoolsConfig - PublicKey for the WhirlpoolsConfig that we want to update.
* @param rewardEmissionsSuperAuthority - Current reward emission super authority in this WhirlpoolsConfig
* @param newRewardEmissionsSuperAuthority - New reward emission super authority for this WhirlpoolsConfig
*/
export type SetRewardEmissionsSuperAuthorityParams = {
whirlpoolsConfig: PublicKey;
rewardEmissionsSuperAuthority: PublicKey;
newRewardEmissionsSuperAuthority: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetRewardEmissionsSuperAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setRewardEmissionsSuperAuthorityIx(
program: Program<Whirlpool>,
params: SetRewardEmissionsSuperAuthorityParams,
): Instruction {
const {
whirlpoolsConfig,
rewardEmissionsSuperAuthority,
newRewardEmissionsSuperAuthority,
} = params;
const ix = program.instruction.setRewardEmissionsSuperAuthority({
accounts: {
whirlpoolsConfig,
rewardEmissionsSuperAuthority: rewardEmissionsSuperAuthority,
newRewardEmissionsSuperAuthority,
},
});
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-protocol-fees-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 protocol fees for a Whirlpool
*
* @category Instruction Types
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.
* @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.
* @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet
* @param tokenOwnerAccountB - PublicKey for the associated token account for tokenA in the collection wallet
* @param collectProtocolFeesAuthority - assigned authority in the WhirlpoolsConfig that can collect protocol fees
*/
export type CollectProtocolFeesParams = {
whirlpoolsConfig: PublicKey;
whirlpool: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
collectProtocolFeesAuthority: PublicKey;
};
/**
* Collect protocol fees accrued in this Whirlpool.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - CollectProtocolFeesParams object
* @returns - Instruction to perform the action.
*/
export function collectProtocolFeesIx(
program: Program<Whirlpool>,
params: CollectProtocolFeesParams,
): Instruction {
const {
whirlpoolsConfig,
whirlpool,
collectProtocolFeesAuthority,
tokenVaultA,
tokenVaultB,
tokenOwnerAccountA: tokenDestinationA,
tokenOwnerAccountB: tokenDestinationB,
} = params;
const ix = program.instruction.collectProtocolFees({
accounts: {
whirlpoolsConfig,
whirlpool,
collectProtocolFeesAuthority,
tokenVaultA,
tokenVaultB,
tokenDestinationA,
tokenDestinationB,
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-fee-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 fee authority in a WhirlpoolsConfig
*
* @category Instruction Types
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param feeAuthority - The current feeAuthority in the WhirlpoolsConfig
* @param newFeeAuthority - The new feeAuthority in the WhirlpoolsConfig
*/
export type SetFeeAuthorityParams = {
whirlpoolsConfig: PublicKey;
feeAuthority: PublicKey;
newFeeAuthority: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetFeeAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setFeeAuthorityIx(
program: Program<Whirlpool>,
params: SetFeeAuthorityParams,
): Instruction {
const { whirlpoolsConfig, feeAuthority, newFeeAuthority } = params;
const ix = program.instruction.setFeeAuthority({
accounts: {
whirlpoolsConfig,
feeAuthority,
newFeeAuthority,
},
});
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-default-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 the default fee rate for a FeeTier.
*
* @category Instruction Types
* @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 defaultProtocolFeeRate - The new default protocol fee rate for this config. Stored as a basis point of the total fees collected by feeRate.
*/
export type SetDefaultProtocolFeeRateParams = {
whirlpoolsConfig: PublicKey;
feeAuthority: PublicKey;
defaultProtocolFeeRate: number;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetDefaultFeeRateParams object
* @returns - Instruction to perform the action.
*/
export function setDefaultProtocolFeeRateIx(
program: Program<Whirlpool>,
params: SetDefaultProtocolFeeRateParams,
): Instruction {
const { whirlpoolsConfig, feeAuthority, defaultProtocolFeeRate } = params;
const ix = program.instruction.setDefaultProtocolFeeRate(
defaultProtocolFeeRate,
{
accounts: {
whirlpoolsConfig,
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/open-position-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction, PDA } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import { METADATA_PROGRAM_ADDRESS, WHIRLPOOL_NFT_UPDATE_AUTH } from "..";
import type { Whirlpool } from "../artifacts/whirlpool";
import type {
OpenPositionBumpsData,
OpenPositionWithMetadataBumpsData,
} from "../types/public/anchor-types";
import { openPositionAccounts } from "../utils/instructions-util";
/**
* Parameters to open a position in a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param ownerKey - PublicKey for the wallet that will host the minted position token.
* @param positionPda - PDA for the derived position address.
* @param positionMintAddress - PublicKey for the mint token for the Position token.
* @param positionTokenAccount - The associated token address for the position token in the owners wallet.
* @param tickLowerIndex - The tick specifying the lower end of the position range.
* @param tickUpperIndex - The tick specifying the upper end of the position range.
* @param funder - The account that would fund the creation of this account
*/
export type OpenPositionParams = {
whirlpool: PublicKey;
owner: PublicKey;
positionPda: PDA;
positionMintAddress: PublicKey;
positionTokenAccount: PublicKey;
tickLowerIndex: number;
tickUpperIndex: number;
funder: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - OpenPositionParams object
* @returns - Instruction to perform the action.
*/
export function openPositionIx(
program: Program<Whirlpool>,
params: OpenPositionParams,
): Instruction {
const { positionPda, tickLowerIndex, tickUpperIndex } = params;
const bumps: OpenPositionBumpsData = {
positionBump: positionPda.bump,
};
const ix = program.instruction.openPosition(
bumps,
tickLowerIndex,
tickUpperIndex,
{
accounts: openPositionAccounts(params),
},
);
// TODO: Require Keypair and auto sign this ix
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
/**
* 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.
*
* @category Instructions
* @param context - Context 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.
*/
export function openPositionWithMetadataIx(
program: Program<Whirlpool>,
params: OpenPositionParams & { metadataPda: PDA },
): Instruction {
const { positionPda, metadataPda, tickLowerIndex, tickUpperIndex } = params;
const bumps: OpenPositionWithMetadataBumpsData = {
positionBump: positionPda.bump,
metadataBump: metadataPda.bump,
};
const ix = program.instruction.openPositionWithMetadata(
bumps,
tickLowerIndex,
tickUpperIndex,
{
accounts: {
...openPositionAccounts(params),
positionMetadataAccount: metadataPda.publicKey,
metadataProgram: METADATA_PROGRAM_ADDRESS,
metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH,
},
},
);
// TODO: Require Keypair and auto sign this ix
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-fee-tier-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { 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";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to initialize a FeeTier account.
*
* @category Instruction Types
* @param whirlpoolsConfig - PublicKey for the whirlpool config space that the fee-tier will be initialized for.
* @param feeTierPda - PDA for the fee-tier account that will be initialized
* @param tickSpacing - The tick spacing this fee tier recommends its default fee rate for.
* @param defaultFeeRate - The default fee rate for this fee-tier. Stored as a hundredths of a basis point.
* @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees.
* @param funder - The account that would fund the creation of this account
*/
export type InitFeeTierParams = {
whirlpoolsConfig: PublicKey;
feeTierPda: PDA;
tickSpacing: number;
defaultFeeRate: number;
feeAuthority: PublicKey;
funder: PublicKey;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - InitFeeTierParams object
* @returns - Instruction to perform the action.
*/
export function initializeFeeTierIx(
program: Program<Whirlpool>,
params: InitFeeTierParams,
): Instruction {
const {
feeTierPda,
whirlpoolsConfig,
tickSpacing,
feeAuthority,
defaultFeeRate,
funder,
} = params;
const ix = program.instruction.initializeFeeTier(
tickSpacing,
defaultFeeRate,
{
accounts: {
config: whirlpoolsConfig,
feeTier: feeTierPda.publicKey,
feeAuthority,
funder,
systemProgram: SystemProgram.programId,
},
},
);
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/index.ts
|
export * from "./close-bundled-position-ix";
export * from "./close-position-ix";
export * from "./close-position-with-token-extensions-ix";
export * from "./collect-fees-ix";
export * from "./collect-protocol-fees-ix";
export * from "./collect-reward-ix";
export * from "./composites";
export * from "./decrease-liquidity-ix";
export * from "./delete-position-bundle-ix";
export * from "./increase-liquidity-ix";
export * from "./initialize-config-ix";
export * from "./initialize-fee-tier-ix";
export * from "./initialize-pool-ix";
export * from "./initialize-position-bundle-ix";
export * from "./initialize-reward-ix";
export * from "./initialize-tick-array-ix";
export * from "./open-bundled-position-ix";
export * from "./open-position-ix";
export * from "./open-position-with-token-extensions-ix";
export * from "./set-collect-protocol-fees-authority-ix";
export * from "./set-default-fee-rate-ix";
export * from "./set-default-protocol-fee-rate-ix";
export * from "./set-fee-authority-ix";
export * from "./set-fee-rate-ix";
export * from "./set-protocol-fee-rate-ix";
export * from "./set-reward-authority-by-super-authority-ix";
export * from "./set-reward-authority-ix";
export * from "./set-reward-emissions-ix";
export * from "./set-reward-emissions-super-authority-ix";
export * from "./swap-ix";
export * from "./two-hop-swap-ix";
export * from "./update-fees-and-rewards-ix";
export * from "./v2";
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/collect-fees-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to collect fees from 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 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 positionAuthority - authority that owns the token corresponding to this desired position.
*/
export type CollectFeesParams = {
whirlpool: PublicKey;
position: PublicKey;
positionTokenAccount: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
positionAuthority: PublicKey;
};
/**
* Collect fees accrued for this 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 - CollectFeesParams object
* @returns - Instruction to perform the action.
*/
export function collectFeesIx(
program: Program<Whirlpool>,
params: CollectFeesParams,
): Instruction {
const {
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
} = params;
const ix = program.instruction.collectFees({
accounts: {
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
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/open-position-with-token-extensions-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction, PDA } from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import { WHIRLPOOL_NFT_UPDATE_AUTH } from "..";
import type { Whirlpool } from "../artifacts/whirlpool";
import { openPositionWithTokenExtensionsAccounts } from "../utils/instructions-util";
/**
* Parameters to open a position (based on Token-2022) in a Whirlpool.
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool that the position will be opened for.
* @param ownerKey - PublicKey for the wallet that will host the minted position token.
* @param positionPda - PDA for the derived position address.
* @param positionMint - PublicKey for the mint token for the Position token.
* @param positionTokenAccount - The associated token address for the position token in the owners wallet.
* @param funder - The account that would fund the creation of this account
* @param tickLowerIndex - The tick specifying the lower end of the position range.
* @param tickUpperIndex - The tick specifying the upper end of the position range.
* @param withTokenMetadataExtension - If true, the position token will have a TokenMetadata extension.
*/
export type OpenPositionWithTokenExtensionsParams = {
whirlpool: PublicKey;
owner: PublicKey;
positionPda: PDA;
positionMint: PublicKey;
positionTokenAccount: PublicKey;
funder: PublicKey;
tickLowerIndex: number;
tickUpperIndex: number;
withTokenMetadataExtension: boolean;
};
/**
* 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.
*
* @category Instructions
* @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.
*/
export function openPositionWithTokenExtensionsIx(
program: Program<Whirlpool>,
params: OpenPositionWithTokenExtensionsParams,
): Instruction {
const { tickLowerIndex, tickUpperIndex, withTokenMetadataExtension } = params;
const ix = program.instruction.openPositionWithTokenExtensions(
tickLowerIndex,
tickUpperIndex,
withTokenMetadataExtension,
{
accounts: {
...openPositionWithTokenExtensionsAccounts(params),
metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH,
},
},
);
// TODO: Require Keypair and auto sign this ix
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-pool-ix.ts
|
import type { BN, Program } from "@coral-xyz/anchor";
import type { Instruction, PDA } from "@orca-so/common-sdk";
import { TOKEN_PROGRAM_ID } from "@solana/spl-token";
import type { Keypair, PublicKey } from "@solana/web3.js";
import { SystemProgram, SYSVAR_RENT_PUBKEY } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
import type { WhirlpoolBumpsData } from "../types/public/anchor-types";
/**
* Parameters to initialize a Whirlpool account.
*
* @category Instruction Types
* @param initSqrtPrice - The desired initial sqrt-price for this pool
* @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in
* @param whirlpoolPda - PDA for the whirlpool account that would be initialized
* @param tokenMintA - Mint public key for token A
* @param tokenMintB - Mint public key for token B
* @param tokenVaultAKeypair - Keypair of the token A vault for this pool
* @param tokenVaultBKeypair - Keypair of the token B vault for this pool
* @param feeTierKey - PublicKey of the fee-tier account that this pool would use for the fee-rate
* @param tickSpacing - The desired tick spacing for this pool.
* @param funder - The account that would fund the creation of this account
*/
export type InitPoolParams = {
initSqrtPrice: BN;
whirlpoolsConfig: PublicKey;
whirlpoolPda: PDA;
tokenMintA: PublicKey;
tokenMintB: PublicKey;
tokenVaultAKeypair: Keypair;
tokenVaultBKeypair: Keypair;
feeTierKey: PublicKey;
tickSpacing: number;
funder: PublicKey;
};
/**
* 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
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - InitPoolParams object
* @returns - Instruction to perform the action.
*/
export function initializePoolIx(
program: Program<Whirlpool>,
params: InitPoolParams,
): Instruction {
const {
initSqrtPrice,
tokenMintA,
tokenMintB,
whirlpoolsConfig,
whirlpoolPda,
feeTierKey,
tokenVaultAKeypair,
tokenVaultBKeypair,
tickSpacing,
funder,
} = params;
const whirlpoolBumps: WhirlpoolBumpsData = {
whirlpoolBump: whirlpoolPda.bump,
};
const ix = program.instruction.initializePool(
whirlpoolBumps,
tickSpacing,
initSqrtPrice,
{
accounts: {
whirlpoolsConfig,
tokenMintA,
tokenMintB,
funder,
whirlpool: whirlpoolPda.publicKey,
tokenVaultA: tokenVaultAKeypair.publicKey,
tokenVaultB: tokenVaultBKeypair.publicKey,
feeTier: feeTierKey,
tokenProgram: TOKEN_PROGRAM_ID,
systemProgram: SystemProgram.programId,
rent: SYSVAR_RENT_PUBKEY,
},
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [tokenVaultAKeypair, tokenVaultBKeypair],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-reward-emissions-ix.ts
|
import type { BN, 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 rewards emissions for a reward in a Whirlpool
*
* @category Instruction Types
* @param whirlpool - PublicKey for the whirlpool which the reward resides in.
* @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).
* @param rewardVaultKey - PublicKey of the vault for this reward index.
* @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool
* @param emissionsPerSecondX64 - The new emissions per second to set for this reward.
*/
export type SetRewardEmissionsParams = {
whirlpool: PublicKey;
rewardIndex: number;
rewardVaultKey: PublicKey;
rewardAuthority: PublicKey;
emissionsPerSecondX64: BN;
};
/**
* 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetRewardEmissionsParams object
* @returns - Instruction to perform the action.
*/
export function setRewardEmissionsIx(
program: Program<Whirlpool>,
params: SetRewardEmissionsParams,
): Instruction {
const {
rewardAuthority,
whirlpool,
rewardIndex,
rewardVaultKey: rewardVault,
emissionsPerSecondX64,
} = params;
const ix = program.instruction.setRewardEmissions(
rewardIndex,
emissionsPerSecondX64,
{
accounts: {
rewardAuthority,
whirlpool,
rewardVault,
},
},
);
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/increase-liquidity-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
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";
import type { Instruction } from "@orca-so/common-sdk";
/**
* Parameters to increase liquidity for a position.
*
* @category Instruction Types
* @param liquidityAmount - The total amount of Liquidity the user is willing to deposit.
* @param tokenMaxA - The maximum amount of token A to add to the position.
* @param tokenMaxB - The maximum amount of token B to add to 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 IncreaseLiquidityParams = {
whirlpool: PublicKey;
position: PublicKey;
positionTokenAccount: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
positionAuthority: PublicKey;
} & IncreaseLiquidityInput;
/**
* Input parameters to deposit liquidity into a position.
*
* This type is usually generated by a quote class to estimate the amount of tokens required to
* deposit a certain amount of liquidity into a position.
*
* @category Instruction Types
* @param tokenMaxA - the maximum amount of tokenA allowed to withdraw from the source wallet.
* @param tokenMaxB - the maximum amount of tokenB allowed to withdraw from the source wallet.
* @param liquidityAmount - the desired amount of liquidity to deposit into the position/
*/
export type IncreaseLiquidityInput = {
tokenMaxA: BN;
tokenMaxB: BN;
liquidityAmount: BN;
};
/**
* Add liquidity to a position in the Whirlpool.
*
* #### 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.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - IncreaseLiquidityParams object
* @returns - Instruction to perform the action.
*/
export function increaseLiquidityIx(
program: Program<Whirlpool>,
params: IncreaseLiquidityParams,
): Instruction {
const {
liquidityAmount,
tokenMaxA,
tokenMaxB,
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
tickArrayLower,
tickArrayUpper,
} = params;
const ix = program.instruction.increaseLiquidity(
liquidityAmount,
tokenMaxA,
tokenMaxB,
{
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/close-position-with-token-extensions-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../artifacts/whirlpool";
/**
* Parameters to close a position (based on Token-2022) in a Whirlpool.
*
* @category Instruction Types
* @param receiver - PublicKey for the wallet that will receive the rented lamports.
* @param position - PublicKey for the position.
* @param positionMint - PublicKey for the mint token for the Position token.
* @param positionTokenAccount - The associated token address for the position token in the owners wallet.
* @param positionAuthority - Authority that owns the position token.
*/
export type ClosePositionWithTokenExtensionsParams = {
receiver: PublicKey;
position: PublicKey;
positionMint: PublicKey;
positionTokenAccount: PublicKey;
positionAuthority: PublicKey;
};
/**
* 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.
*/
export function closePositionWithTokenExtensionsIx(
program: Program<Whirlpool>,
params: ClosePositionWithTokenExtensionsParams,
): Instruction {
const ix = program.instruction.closePositionWithTokenExtensions({
accounts: {
...params,
token2022Program: TOKEN_2022_PROGRAM_ID,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/swap-with-route.ts
|
import type {
Percentage,
ResolvedTokenAddressInstruction,
} from "@orca-so/common-sdk";
import {
AddressUtil,
EMPTY_INSTRUCTION,
TokenUtil,
TransactionBuilder,
ZERO,
} from "@orca-so/common-sdk";
import type { Account } from "@solana/spl-token";
import {
NATIVE_MINT,
TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
createCloseAccountInstruction,
getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import type { TransactionInstruction } from "@solana/web3.js";
import { PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import type {
AtaAccountInfo,
SubTradeRoute,
TradeRoute,
WhirlpoolContext,
} from "../..";
import { PDAUtil, SwapUtils, twoHopSwapQuoteFromSwapQuotes } from "../..";
import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher";
import { PREFER_CACHE } from "../../network/public/fetcher";
import { adjustForSlippage } from "../../utils/position-util";
import { contextOptionsToBuilderOptions } from "../../utils/txn-utils";
import { swapIx } from "../swap-ix";
import { twoHopSwapIx } from "../two-hop-swap-ix";
export type SwapFromRouteParams = {
route: TradeRoute;
slippage: Percentage;
wallet: PublicKey;
resolvedAtaAccounts: AtaAccountInfo[] | null;
};
export async function getSwapFromRoute(
ctx: WhirlpoolContext,
params: SwapFromRouteParams,
opts: WhirlpoolAccountFetchOptions = PREFER_CACHE,
txBuilder: TransactionBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
contextOptionsToBuilderOptions(ctx.opts),
),
) {
const { route, wallet, resolvedAtaAccounts, slippage } = params;
const requiredAtas = new Set<string>();
const requiredIntermediateAtas = new Set<string>();
const requiredTickArrays = [];
let hasNativeMint = false;
let nativeMintAmount = new BN(0);
function addOrNative(mint: string, amount: BN) {
if (mint === NATIVE_MINT.toBase58()) {
hasNativeMint = true;
nativeMintAmount = nativeMintAmount.add(amount);
} else {
requiredAtas.add(mint);
}
}
for (let i = 0; i < route.subRoutes.length; i++) {
const routeFragment = route.subRoutes[i];
const slippageAdjustedRoute = adjustQuoteForSlippage(
routeFragment,
slippage,
);
if (slippageAdjustedRoute.hopQuotes.length == 1) {
const { quote, mintA, mintB } = slippageAdjustedRoute.hopQuotes[0];
requiredTickArrays.push(
...[quote.tickArray0, quote.tickArray1, quote.tickArray2],
);
const inputAmount = quote.amountSpecifiedIsInput
? quote.amount
: quote.otherAmountThreshold;
addOrNative(mintA.toString(), quote.aToB ? inputAmount : ZERO);
addOrNative(mintB.toString(), !quote.aToB ? inputAmount : ZERO);
} else if (slippageAdjustedRoute.hopQuotes.length == 2) {
const {
quote: quoteOne,
mintA: mintOneA,
mintB: mintOneB,
} = slippageAdjustedRoute.hopQuotes[0];
const {
quote: quoteTwo,
mintA: mintTwoA,
mintB: mintTwoB,
} = slippageAdjustedRoute.hopQuotes[1];
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quoteOne, quoteTwo);
requiredTickArrays.push(
...[
twoHopQuote.tickArrayOne0,
twoHopQuote.tickArrayOne1,
twoHopQuote.tickArrayOne2,
twoHopQuote.tickArrayTwo0,
twoHopQuote.tickArrayTwo1,
twoHopQuote.tickArrayTwo2,
],
);
const inputAmount = quoteOne.amountSpecifiedIsInput
? quoteOne.estimatedAmountIn
: quoteOne.otherAmountThreshold;
addOrNative(mintOneA.toString(), quoteOne.aToB ? inputAmount : ZERO);
addOrNative(mintOneB.toString(), !quoteOne.aToB ? inputAmount : ZERO);
addOrNative(mintTwoA.toString(), ZERO);
addOrNative(mintTwoB.toString(), ZERO);
requiredIntermediateAtas.add(
quoteOne.aToB ? mintOneB.toString() : mintOneA.toString(),
);
}
}
// No need to check if TickArrays are initialized after SparseSwap implementation
// Handle non-native mints only first
requiredAtas.delete(NATIVE_MINT.toBase58());
const ataInstructionMap = await cachedResolveOrCreateNonNativeATAs(
wallet,
requiredAtas,
requiredIntermediateAtas,
(keys) => {
// TODO: if atas are not up to date, there might be failures, not sure if there's
// any good way, other than to re-fetch each time?
if (resolvedAtaAccounts != null) {
return Promise.resolve(
keys.map((key) =>
resolvedAtaAccounts.find(
(ata) => ata.address?.toBase58() === key.toBase58(),
),
) as Account[],
);
} else {
return ctx.fetcher
.getTokenInfos(keys, opts)
.then((result) => Array.from(result.values()));
}
},
undefined, // use default
ctx.accountResolverOpts.allowPDAOwnerAddress,
);
const ataIxes = Object.values(ataInstructionMap);
if (hasNativeMint) {
const solIx = TokenUtil.createWrappedNativeAccountInstruction(
wallet,
nativeMintAmount,
await ctx.fetcher.getAccountRentExempt(),
undefined, // use default
undefined, // use default
ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
txBuilder.addInstruction(solIx);
ataInstructionMap[NATIVE_MINT.toBase58()] = solIx;
}
txBuilder.addInstructions(ataIxes);
// Slippage adjustment
const slippageAdjustedQuotes = route.subRoutes.map((quote) =>
adjustQuoteForSlippage(quote, slippage),
);
for (let i = 0; i < slippageAdjustedQuotes.length; i++) {
const routeFragment = slippageAdjustedQuotes[i];
if (routeFragment.hopQuotes.length == 1) {
const { quote, whirlpool, mintA, mintB, vaultA, vaultB } =
routeFragment.hopQuotes[0];
const [wp, tokenVaultA, tokenVaultB] = AddressUtil.toPubKeys([
whirlpool,
vaultA,
vaultB,
]);
const accA = ataInstructionMap[mintA.toString()].address;
const accB = ataInstructionMap[mintB.toString()].address;
const oraclePda = PDAUtil.getOracle(ctx.program.programId, wp);
txBuilder.addInstruction(
swapIx(ctx.program, {
whirlpool: wp,
tokenOwnerAccountA: accA,
tokenOwnerAccountB: accB,
tokenVaultA,
tokenVaultB,
oracle: oraclePda.publicKey,
tokenAuthority: wallet,
...quote,
}),
);
} else if (routeFragment.hopQuotes.length == 2) {
const {
quote: quoteOne,
whirlpool: whirlpoolOne,
mintA: mintOneA,
mintB: mintOneB,
vaultA: vaultOneA,
vaultB: vaultOneB,
} = routeFragment.hopQuotes[0];
const {
quote: quoteTwo,
whirlpool: whirlpoolTwo,
mintA: mintTwoA,
mintB: mintTwoB,
vaultA: vaultTwoA,
vaultB: vaultTwoB,
} = routeFragment.hopQuotes[1];
const [
wpOne,
wpTwo,
tokenVaultOneA,
tokenVaultOneB,
tokenVaultTwoA,
tokenVaultTwoB,
] = AddressUtil.toPubKeys([
whirlpoolOne,
whirlpoolTwo,
vaultOneA,
vaultOneB,
vaultTwoA,
vaultTwoB,
]);
const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quoteOne, quoteTwo);
const oracleOne = PDAUtil.getOracle(
ctx.program.programId,
wpOne,
).publicKey;
const oracleTwo = PDAUtil.getOracle(
ctx.program.programId,
wpTwo,
).publicKey;
const tokenOwnerAccountOneA =
ataInstructionMap[mintOneA.toString()].address;
const tokenOwnerAccountOneB =
ataInstructionMap[mintOneB.toString()].address;
const tokenOwnerAccountTwoA =
ataInstructionMap[mintTwoA.toString()].address;
const tokenOwnerAccountTwoB =
ataInstructionMap[mintTwoB.toString()].address;
txBuilder.addInstruction(
twoHopSwapIx(ctx.program, {
...twoHopQuote,
whirlpoolOne: wpOne,
whirlpoolTwo: wpTwo,
tokenOwnerAccountOneA,
tokenOwnerAccountOneB,
tokenOwnerAccountTwoA,
tokenOwnerAccountTwoB,
tokenVaultOneA,
tokenVaultOneB,
tokenVaultTwoA,
tokenVaultTwoB,
oracleOne,
oracleTwo,
tokenAuthority: wallet,
}),
);
}
}
return txBuilder;
}
function adjustQuoteForSlippage(
quote: SubTradeRoute,
slippage: Percentage,
): SubTradeRoute {
const { hopQuotes } = quote;
if (hopQuotes.length === 1) {
return {
...quote,
hopQuotes: [
{
...hopQuotes[0],
quote: {
...hopQuotes[0].quote,
...SwapUtils.calculateSwapAmountsFromQuote(
hopQuotes[0].quote.amount,
hopQuotes[0].quote.estimatedAmountIn,
hopQuotes[0].quote.estimatedAmountOut,
slippage,
hopQuotes[0].quote.amountSpecifiedIsInput,
),
},
},
],
};
} else if (quote.hopQuotes.length === 2) {
const swapQuoteOne = quote.hopQuotes[0];
const swapQuoteTwo = quote.hopQuotes[1];
const amountSpecifiedIsInput = swapQuoteOne.quote.amountSpecifiedIsInput;
let updatedQuote = {
...quote,
};
if (amountSpecifiedIsInput) {
updatedQuote.hopQuotes = [
updatedQuote.hopQuotes[0],
{
...swapQuoteTwo,
quote: {
...swapQuoteTwo.quote,
otherAmountThreshold: adjustForSlippage(
swapQuoteTwo.quote.estimatedAmountOut,
slippage,
false,
),
},
},
];
} else {
updatedQuote.hopQuotes = [
{
...swapQuoteOne,
quote: {
...swapQuoteOne.quote,
otherAmountThreshold: adjustForSlippage(
swapQuoteOne.quote.estimatedAmountIn,
slippage,
true,
),
},
},
updatedQuote.hopQuotes[1],
];
}
return updatedQuote;
}
return quote;
}
/**
* Internal duplicate of resolveOrCreateAta
* This could be ported over to common-sdk?
*
* IMPORTANT: wrappedSolAmountIn should only be used for input/source token that
* could be SOL. This is because when SOL is the output, it is the end
* destination, and thus does not need to be wrapped with an amount.
*
* @param ownerAddress The user's public key
* @param tokenMint Token mint address
* @param intermediateTokenMints Any mints from the tokenMint set that are intermediates in a two-hop swap
* @param getTokenAccounts Function to get token accounts
* @param payer Payer that would pay the rent for the creation of the ATAs
* @param allowPDAOwnerAddress Optional. Allow PDA to be used as the ATA owner address
* @returns
*/
async function cachedResolveOrCreateNonNativeATAs(
ownerAddress: PublicKey,
tokenMints: Set<string>,
intermediateTokenMints: Set<string>,
getTokenAccounts: (
keys: PublicKey[],
) => Promise<Array<AtaAccountInfo | null>>,
payer = ownerAddress,
allowPDAOwnerAddress: boolean = false,
): Promise<{ [tokenMint: string]: ResolvedTokenAddressInstruction }> {
const instructionMap: {
[tokenMint: string]: ResolvedTokenAddressInstruction;
} = {};
const tokenMintArray = Array.from(tokenMints).map((tm) => new PublicKey(tm));
const tokenAtas = tokenMintArray.map((tm) =>
getAssociatedTokenAddressSync(tm, ownerAddress, allowPDAOwnerAddress),
);
const tokenAccounts = await getTokenAccounts(tokenAtas);
tokenAccounts.forEach((tokenAccount, index) => {
const ataAddress = tokenAtas[index]!;
let resolvedInstruction;
if (tokenAccount) {
// ATA whose owner has been changed is abnormal entity.
// To prevent to send swap/withdraw/collect output to the ATA, an error should be thrown.
if (!tokenAccount.owner.equals(ownerAddress)) {
throw new Error(
`ATA with change of ownership detected: ${ataAddress.toBase58()}`,
);
}
resolvedInstruction = { address: ataAddress, ...EMPTY_INSTRUCTION };
} else {
const tokenMint = tokenMintArray[index];
const createAtaInstructions = [
createAssociatedTokenAccountInstruction(
payer,
ataAddress,
ownerAddress,
tokenMint,
),
];
let cleanupInstructions: TransactionInstruction[] = [];
if (intermediateTokenMints.has(tokenMint.toBase58())) {
cleanupInstructions = [
createCloseAccountInstruction(ataAddress, ownerAddress, ownerAddress),
];
}
resolvedInstruction = {
address: ataAddress,
instructions: createAtaInstructions,
cleanupInstructions: cleanupInstructions,
signers: [],
};
}
// WhirlpoolRouter does not handle TokenExtension, so token program is always standard TokenProgram.
instructionMap[tokenMintArray[index].toBase58()] = {
tokenProgram: TOKEN_PROGRAM_ID,
...resolvedInstruction,
};
});
return instructionMap;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/collect-all-txn.ts
|
import type { Address } from "@coral-xyz/anchor";
import type {
Instruction,
ResolvedTokenAddressInstruction,
} from "@orca-so/common-sdk";
import {
TokenUtil,
TransactionBuilder,
ZERO,
resolveOrCreateATAs,
} from "@orca-so/common-sdk";
import { NATIVE_MINT, getAssociatedTokenAddressSync } from "@solana/spl-token";
import { PublicKey } from "@solana/web3.js";
import type { PositionData, WhirlpoolContext } from "../..";
import { WhirlpoolIx } from "../../ix";
import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher";
import { PREFER_CACHE } from "../../network/public/fetcher";
import type { WhirlpoolData } from "../../types/public";
import { PDAUtil, PoolUtil, TickUtil } from "../../utils/public";
import {
checkMergedTransactionSizeIsValid,
convertListToMap,
} from "../../utils/txn-utils";
import { getTokenMintsFromWhirlpools } from "../../utils/whirlpool-ata-utils";
import { updateFeesAndRewardsIx } from "../update-fees-and-rewards-ix";
import { TokenExtensionUtil } from "../../utils/public/token-extension-util";
/**
* Parameters to collect all fees and rewards from a list of positions.
*
* @category Instruction Types
* @param positionAddrs - An array of Whirlpool position addresses.
* @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key.
* @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key.
* @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key.
* @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key.
*/
export type CollectAllPositionAddressParams = {
positions: Address[];
} & CollectAllParams;
/**
* Parameters to collect all fees and rewards from a list of positions.
*
* @category Instruction Types
* @param positions - An array of Whirlpool positions.
* @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key.
* @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key.
* @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key.
* @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key.
*/
export type CollectAllPositionParams = {
positions: Record<string, PositionData>;
} & CollectAllParams;
/**
* Common parameters between {@link CollectAllPositionParams} & {@link CollectAllPositionAddressParams}
*
* @category Instruction Types
* @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key.
* @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key.
* @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key.
* @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key.
*/
export type CollectAllParams = {
receiver?: PublicKey;
positionOwner?: PublicKey;
positionAuthority?: PublicKey;
payer?: PublicKey;
};
/**
* Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions.
*
* @category Instructions
* @experimental
* @param ctx - WhirlpoolContext object for the current environment.
* @param params - CollectAllPositionAddressParams object
* @param opts an {@link WhirlpoolAccountFetchOptions} 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.
*/
export async function collectAllForPositionAddressesTxns(
ctx: WhirlpoolContext,
params: CollectAllPositionAddressParams,
opts: WhirlpoolAccountFetchOptions = PREFER_CACHE,
): Promise<TransactionBuilder[]> {
const { positions, ...rest } = params;
const fetchedPositions = await ctx.fetcher.getPositions(positions, opts);
const positionMap: Record<string, PositionData> = {};
fetchedPositions.forEach((pos, addr) => {
if (pos) {
positionMap[addr] = pos;
}
});
return collectAllForPositionsTxns(ctx, { positions: positionMap, ...rest });
}
/**
* Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions.
*
* @experimental
* @param ctx - WhirlpoolContext object for the current environment.
* @param params - CollectAllPositionParams object
* @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions.
*/
export async function collectAllForPositionsTxns(
ctx: WhirlpoolContext,
params: CollectAllPositionParams,
): Promise<TransactionBuilder[]> {
const { positions, receiver, positionAuthority, positionOwner, payer } =
params;
const receiverKey = receiver ?? ctx.wallet.publicKey;
const positionAuthorityKey = positionAuthority ?? ctx.wallet.publicKey;
const positionOwnerKey = positionOwner ?? ctx.wallet.publicKey;
const payerKey = payer ?? ctx.wallet.publicKey;
const positionList = Object.entries(positions);
if (positionList.length === 0) {
return [];
}
const whirlpoolAddrs = positionList.map(([, pos]) =>
pos.whirlpool.toBase58(),
);
const whirlpools = await ctx.fetcher.getPools(whirlpoolAddrs, PREFER_CACHE);
const allMints = getTokenMintsFromWhirlpools(Array.from(whirlpools.values()));
const accountExemption = await ctx.fetcher.getAccountRentExempt();
const positionMintAddrs = positionList.map(([, pos]) => pos.positionMint);
const positionMintInfos = await ctx.fetcher.getMintInfos(positionMintAddrs);
// make cache
await ctx.fetcher.getMintInfos(allMints.mintMap);
// resolvedAtas[mint] => Instruction & { address }
// if already ATA exists, Instruction will be EMPTY_INSTRUCTION
const resolvedAtas = convertListToMap(
await resolveOrCreateATAs(
ctx.connection,
receiverKey,
allMints.mintMap.map((tokenMint) => ({ tokenMint })),
async () => accountExemption,
payerKey,
true, // CreateIdempotent
ctx.accountResolverOpts.allowPDAOwnerAddress,
ctx.accountResolverOpts.createWrappedSolAccountMethod,
),
allMints.mintMap.map((mint) => mint.toBase58()),
);
const latestBlockhash = await ctx.connection.getLatestBlockhash();
const txBuilders: TransactionBuilder[] = [];
// build tasks
// For TokenProgram-TokenProgram pair pool, collectFees and 3 collectReward instructions can be packed into one transaction.
// But if pool has TokenExtension, especially TransferHook, we can no longer pack all instructions into one transaction.
// So transactions need to be broken up at a finer granularity.
const collectionTasks: CollectionTask[] = [];
positionList.forEach(([positionAddr, position]) => {
const whirlpool = whirlpools.get(position.whirlpool.toBase58());
if (!whirlpool) {
throw new Error(
`Unable to process positionMint ${position.positionMint.toBase58()} - unable to derive whirlpool ${position.whirlpool.toBase58()}`,
);
}
const positionMintInfo = positionMintInfos.get(
position.positionMint.toBase58(),
);
if (!positionMintInfo) {
throw new Error(
`Unable to process positionMint ${position.positionMint.toBase58()} - missing mint info`,
);
}
// add fee collection task
collectionTasks.push({
collectionType: "fee",
positionAddr,
position,
whirlpool,
positionMintTokenProgramId: positionMintInfo.tokenProgram,
});
// add reward collection task
whirlpool.rewardInfos.forEach((rewardInfo, index) => {
if (PoolUtil.isRewardInitialized(rewardInfo)) {
collectionTasks.push({
collectionType: "reward",
rewardIndex: index,
positionAddr,
position,
whirlpool,
positionMintTokenProgramId: positionMintInfo.tokenProgram,
});
}
});
});
let cursor = 0;
let pendingTxBuilder = null;
let touchedMints = null;
let lastUpdatedPosition = null;
let reattempt = false;
while (cursor < collectionTasks.length) {
if (!pendingTxBuilder || !touchedMints) {
pendingTxBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
touchedMints = new Set<string>();
resolvedAtas[NATIVE_MINT.toBase58()] =
TokenUtil.createWrappedNativeAccountInstruction(
receiverKey,
ZERO,
accountExemption,
undefined, // use default
undefined, // use default
ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
}
// Build collect instructions
const task = collectionTasks[cursor];
const alreadyUpdated = lastUpdatedPosition === task.positionAddr;
const collectIxForPosition = await constructCollectIxForPosition(
ctx,
task,
alreadyUpdated,
positionOwnerKey,
positionAuthorityKey,
resolvedAtas,
touchedMints,
);
const positionTxBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
positionTxBuilder.addInstructions(collectIxForPosition);
// Attempt to push the new instructions into the pending builder
// Iterate to the next task if possible
// Create a builder and reattempt if the current one is full.
const mergeable = await checkMergedTransactionSizeIsValid(
ctx,
[pendingTxBuilder, positionTxBuilder],
latestBlockhash,
);
if (mergeable) {
pendingTxBuilder.addInstruction(positionTxBuilder.compressIx(false));
cursor += 1;
lastUpdatedPosition = task.positionAddr;
reattempt = false;
} else {
if (reattempt) {
throw new Error(
`Unable to fit collection ix for ${task.position.positionMint.toBase58()} in a Transaction.`,
);
}
txBuilders.push(pendingTxBuilder);
pendingTxBuilder = null;
touchedMints = null;
lastUpdatedPosition = null;
reattempt = true;
}
}
if (pendingTxBuilder) {
txBuilders.push(pendingTxBuilder);
}
return txBuilders;
}
type CollectionTask = FeeCollectionTask | RewardCollectionTask;
type FeeCollectionTask = {
collectionType: "fee";
} & CollectionTaskBase;
type RewardCollectionTask = {
collectionType: "reward";
rewardIndex: number;
} & CollectionTaskBase;
type CollectionTaskBase = {
positionAddr: string;
position: PositionData;
positionMintTokenProgramId: PublicKey;
whirlpool: WhirlpoolData;
};
// TODO: Once individual collect ix for positions is implemented, maybe migrate over if it can take custom ATA?
const constructCollectIxForPosition = async (
ctx: WhirlpoolContext,
task: CollectionTask,
alreadyUpdated: boolean,
positionOwner: PublicKey,
positionAuthority: PublicKey,
resolvedAtas: Record<string, ResolvedTokenAddressInstruction>,
touchedMints: Set<string>,
) => {
const ixForPosition: Instruction[] = [];
const {
whirlpool: whirlpoolKey,
liquidity,
tickLowerIndex,
tickUpperIndex,
positionMint,
} = task.position;
const positionMintTokenProgramId = task.positionMintTokenProgramId;
const whirlpool = task.whirlpool;
const { tickSpacing } = whirlpool;
const mintA = whirlpool.tokenMintA.toBase58();
const mintB = whirlpool.tokenMintB.toBase58();
const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
whirlpool,
PREFER_CACHE,
);
const positionTokenAccount = getAssociatedTokenAddressSync(
positionMint,
positionOwner,
ctx.accountResolverOpts.allowPDAOwnerAddress,
positionMintTokenProgramId,
);
// Update fee and reward values if necessary
if (!liquidity.eq(ZERO) && !alreadyUpdated) {
ixForPosition.push(
updateFeesAndRewardsIx(ctx.program, {
position: new PublicKey(task.positionAddr),
whirlpool: whirlpoolKey,
tickArrayLower: PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolKey,
TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing),
).publicKey,
tickArrayUpper: PDAUtil.getTickArray(
ctx.program.programId,
whirlpoolKey,
TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing),
).publicKey,
}),
);
}
if (task.collectionType === "fee") {
// Collect Fee
if (!touchedMints.has(mintA)) {
ixForPosition.push(resolvedAtas[mintA]);
touchedMints.add(mintA);
}
if (!touchedMints.has(mintB)) {
ixForPosition.push(resolvedAtas[mintB]);
touchedMints.add(mintB);
}
const collectFeesBaseParams = {
whirlpool: whirlpoolKey,
position: new PublicKey(task.positionAddr),
positionAuthority,
positionTokenAccount,
tokenOwnerAccountA: resolvedAtas[mintA].address,
tokenOwnerAccountB: resolvedAtas[mintB].address,
tokenVaultA: whirlpool.tokenVaultA,
tokenVaultB: whirlpool.tokenVaultB,
};
ixForPosition.push(
!TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? WhirlpoolIx.collectFeesIx(ctx.program, collectFeesBaseParams)
: WhirlpoolIx.collectFeesV2Ix(ctx.program, {
...collectFeesBaseParams,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
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
)),
}),
);
} else {
// Collect Rewards
// TODO: handle empty vault values?
const index = task.rewardIndex;
const rewardInfo = whirlpool.rewardInfos[index];
const mintReward = rewardInfo.mint.toBase58();
if (!touchedMints.has(mintReward)) {
ixForPosition.push(resolvedAtas[mintReward]);
touchedMints.add(mintReward);
}
const collectRewardBaseParams = {
whirlpool: whirlpoolKey,
position: new PublicKey(task.positionAddr),
positionAuthority,
positionTokenAccount,
rewardIndex: index,
rewardOwnerAccount: resolvedAtas[mintReward].address,
rewardVault: rewardInfo.vault,
};
ixForPosition.push(
!TokenExtensionUtil.isV2IxRequiredReward(tokenExtensionCtx, index)
? WhirlpoolIx.collectRewardIx(ctx.program, collectRewardBaseParams)
: WhirlpoolIx.collectRewardV2Ix(ctx.program, {
...collectRewardBaseParams,
rewardMint:
tokenExtensionCtx.rewardTokenMintsWithProgram[index]!.address,
rewardTokenProgram:
tokenExtensionCtx.rewardTokenMintsWithProgram[index]!
.tokenProgram,
rewardTransferHookAccounts:
await TokenExtensionUtil.getExtraAccountMetasForTransferHook(
ctx.connection,
tokenExtensionCtx.rewardTokenMintsWithProgram[index]!,
collectRewardBaseParams.rewardVault,
collectRewardBaseParams.rewardOwnerAccount,
collectRewardBaseParams.whirlpool, // vault to owner, so pool is authority
),
}),
);
}
return ixForPosition;
};
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/index.ts
|
export * from "./collect-all-txn";
export * from "./collect-protocol-fees";
export * from "./swap-async";
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/collect-protocol-fees.ts
|
import type { Address } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import {
AddressUtil,
TokenUtil,
TransactionBuilder,
} from "@orca-so/common-sdk";
import { NATIVE_MINT } from "@solana/spl-token";
import { PACKET_DATA_SIZE } from "@solana/web3.js";
import type { WhirlpoolContext } from "../..";
import { PREFER_CACHE } from "../../network/public/fetcher";
import {
TokenMintTypes,
addNativeMintHandlingIx,
getTokenMintsFromWhirlpools,
resolveAtaForMints,
} from "../../utils/whirlpool-ata-utils";
import { collectProtocolFeesIx } from "../collect-protocol-fees-ix";
import { TokenExtensionUtil } from "../../utils/public/token-extension-util";
import { collectProtocolFeesV2Ix } from "../v2";
export async function collectProtocolFees(
ctx: WhirlpoolContext,
poolAddresses: Address[],
): Promise<TransactionBuilder> {
const receiverKey = ctx.wallet.publicKey;
const payerKey = ctx.wallet.publicKey;
const whirlpoolDatas = Array.from(
(await ctx.fetcher.getPools(poolAddresses, PREFER_CACHE)).values(),
);
// make cache
const mints = getTokenMintsFromWhirlpools(
whirlpoolDatas,
TokenMintTypes.POOL_ONLY,
).mintMap;
await ctx.fetcher.getMintInfos(mints);
const accountExemption = await ctx.fetcher.getAccountRentExempt();
const { ataTokenAddresses, resolveAtaIxs } = await resolveAtaForMints(ctx, {
mints: mints,
accountExemption,
receiver: receiverKey,
payer: payerKey,
});
const latestBlockhash = await ctx.connection.getLatestBlockhash();
let txBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
).addInstructions(resolveAtaIxs);
const instructions: Instruction[] = [];
for (const poolAddress of poolAddresses) {
const pool = await ctx.fetcher.getPool(poolAddress);
if (!pool) {
throw new Error(`Pool not found: ${poolAddress}`);
}
const poolConfig = await ctx.fetcher.getConfig(pool.whirlpoolsConfig);
if (!poolConfig) {
throw new Error(`Config not found: ${pool.whirlpoolsConfig}`);
}
if (
poolConfig.collectProtocolFeesAuthority.toBase58() !==
ctx.wallet.publicKey.toBase58()
) {
throw new Error(`Wallet is not the collectProtocolFeesAuthority`);
}
const poolHandlesNativeMint =
TokenUtil.isNativeMint(pool.tokenMintA) ||
TokenUtil.isNativeMint(pool.tokenMintB);
const txBuilderHasNativeMint = !!ataTokenAddresses[NATIVE_MINT.toBase58()];
if (poolHandlesNativeMint && !txBuilderHasNativeMint) {
addNativeMintHandlingIx(
txBuilder,
ataTokenAddresses,
receiverKey,
accountExemption,
ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
}
const tokenExtensionCtx =
await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
pool,
PREFER_CACHE,
);
const baseParams = {
whirlpoolsConfig: pool.whirlpoolsConfig,
whirlpool: AddressUtil.toPubKey(poolAddress),
tokenVaultA: pool.tokenVaultA,
tokenVaultB: pool.tokenVaultB,
tokenOwnerAccountA: ataTokenAddresses[pool.tokenMintA.toBase58()],
tokenOwnerAccountB: ataTokenAddresses[pool.tokenMintB.toBase58()],
collectProtocolFeesAuthority: poolConfig.collectProtocolFeesAuthority,
};
// add collect ixn
instructions.push(
!TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx)
? collectProtocolFeesIx(ctx.program, baseParams)
: collectProtocolFeesV2Ix(ctx.program, {
...baseParams,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
baseParams.tokenVaultA,
baseParams.tokenOwnerAccountA,
baseParams.whirlpool, // vault to protocol, so pool is authority
baseParams.tokenVaultB,
baseParams.tokenOwnerAccountB,
baseParams.whirlpool, // vault to protocol, so pool is authority
)),
}),
);
}
txBuilder.addInstructions(instructions);
const txSize = await txBuilder.txnSize({ latestBlockhash });
if (txSize > PACKET_DATA_SIZE) {
throw new Error(`Transaction size is too large: ${txSize}`);
}
return txBuilder;
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/swap-async.ts
|
import {
resolveOrCreateATAs,
TransactionBuilder,
U64_MAX,
ZERO,
} from "@orca-so/common-sdk";
import type { PublicKey } from "@solana/web3.js";
import type { Whirlpool, WhirlpoolContext } from "../..";
import { SwapUtils } from "../..";
import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher";
import type { SwapInput } from "../swap-ix";
import { swapIx } from "../swap-ix";
import { TokenExtensionUtil } from "../../utils/public/token-extension-util";
import { swapV2Ix } from "../v2";
import { NATIVE_MINT } from "@solana/spl-token";
export type SwapAsyncParams = {
swapInput: SwapInput;
whirlpool: Whirlpool;
wallet: PublicKey;
};
/**
* Swap instruction builder method with resolveATA & additional checks.
* @param ctx - WhirlpoolContext object for the current environment.
* @param params - {@link SwapAsyncParams}
* @param opts - {@link WhirlpoolAccountFetchOptions} to use for account fetching.
* @returns
*/
export async function swapAsync(
ctx: WhirlpoolContext,
params: SwapAsyncParams,
_opts: WhirlpoolAccountFetchOptions,
): Promise<TransactionBuilder> {
const { wallet, whirlpool, swapInput } = params;
const { aToB, amount, otherAmountThreshold, amountSpecifiedIsInput } =
swapInput;
const txBuilder = new TransactionBuilder(
ctx.connection,
ctx.wallet,
ctx.txBuilderOpts,
);
// No need to check if TickArrays are initialized after SparseSwap implementation
const data = whirlpool.getData();
// In ExactOut mode, max input amount is otherAmountThreshold
const inputTokenMint = aToB ? data.tokenMintA : data.tokenMintB;
const maxInputAmount = amountSpecifiedIsInput ? amount : otherAmountThreshold;
if (inputTokenMint.equals(NATIVE_MINT) && maxInputAmount.eq(U64_MAX)) {
// Strictly speaking, the upper limit would be the wallet balance minus rent and fees,
// but that calculation is impractical.
// Since this function is called to perform a transaction, we can expect the otherAmountThreshold
// to be smaller than the wallet balance, and a run-time error would make the problem clear at worst.
// Here, the obviously impossible case (a value using defaultOtherAmountThreshold) will be an error.
throw new Error("Wrapping U64_MAX amount of SOL is not possible");
}
const [resolvedAtaA, resolvedAtaB] = await resolveOrCreateATAs(
ctx.connection,
wallet,
[
{
tokenMint: data.tokenMintA,
wrappedSolAmountIn: aToB ? maxInputAmount : ZERO,
},
{
tokenMint: data.tokenMintB,
wrappedSolAmountIn: !aToB ? maxInputAmount : ZERO,
},
],
() => ctx.fetcher.getAccountRentExempt(),
undefined, // use default
true, // use idempotent to allow multiple simultaneous calls
ctx.accountResolverOpts.allowPDAOwnerAddress,
ctx.accountResolverOpts.createWrappedSolAccountMethod,
);
const { address: ataAKey, ...tokenOwnerAccountAIx } = resolvedAtaA;
const { address: ataBKey, ...tokenOwnerAccountBIx } = resolvedAtaB;
txBuilder.addInstructions([tokenOwnerAccountAIx, tokenOwnerAccountBIx]);
const inputTokenAccount = aToB ? ataAKey : ataBKey;
const outputTokenAccount = aToB ? ataBKey : ataAKey;
const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext(
ctx.fetcher,
data,
);
const baseParams = SwapUtils.getSwapParamsFromQuote(
swapInput,
ctx,
whirlpool,
inputTokenAccount,
outputTokenAccount,
wallet,
);
return txBuilder.addInstruction(
!TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx) &&
!params.swapInput.supplementalTickArrays
? swapIx(ctx.program, baseParams)
: swapV2Ix(ctx.program, {
...baseParams,
tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address,
tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address,
tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram,
tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram,
...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool(
ctx.connection,
tokenExtensionCtx,
baseParams.aToB
? baseParams.tokenOwnerAccountA
: baseParams.tokenVaultA,
baseParams.aToB
? baseParams.tokenVaultA
: baseParams.tokenOwnerAccountA,
baseParams.aToB ? baseParams.tokenAuthority : baseParams.whirlpool,
baseParams.aToB
? baseParams.tokenVaultB
: baseParams.tokenOwnerAccountB,
baseParams.aToB
? baseParams.tokenOwnerAccountB
: baseParams.tokenVaultB,
baseParams.aToB ? baseParams.whirlpool : baseParams.tokenAuthority,
)),
supplementalTickArrays: params.swapInput.supplementalTickArrays,
}),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/set-config-extension-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 token badge authority in a WhirlpoolsConfigExtension
*
* @category Instruction Types
* @param whirlpoolsConfig - PublicKey for the whirlpools config account
* @param whirlpoolsConfigExtension - The public key for the WhirlpoolsConfigExtension
* @param configExtensionAuthority - The current configExtensionAuthority in the WhirlpoolsConfigExtension
* @param newConfigExtensionAuthority - The new configExtensionAuthority in the WhirlpoolsConfigExtension
*/
export type SetConfigExtensionAuthorityParams = {
whirlpoolsConfig: PublicKey;
whirlpoolsConfigExtension: PublicKey;
configExtensionAuthority: PublicKey;
newConfigExtensionAuthority: PublicKey;
};
/**
* Sets the config extension authority for a WhirlpoolsConfigExtension.
* Only the current config extension authority has permission to invoke this instruction.
*
* @category Instructions
* @param context - Context object containing services required to generate the instruction
* @param params - SetTokenBadgeAuthorityParams object
* @returns - Instruction to perform the action.
*/
export function setConfigExtensionAuthorityIx(
program: Program<Whirlpool>,
params: SetConfigExtensionAuthorityParams,
): Instruction {
const {
whirlpoolsConfig,
whirlpoolsConfigExtension,
configExtensionAuthority,
newConfigExtensionAuthority,
} = params;
const ix = program.instruction.setConfigExtensionAuthority({
accounts: {
whirlpoolsConfig,
whirlpoolsConfigExtension,
configExtensionAuthority,
newConfigExtensionAuthority,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/swap-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { AccountMeta, PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../../artifacts/whirlpool";
import type { SwapInput } from "../../types/public";
import { MEMO_PROGRAM_ADDRESS } from "../../types/public";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
toSupplementalTickArrayAccountMetas,
} from "../../utils/remaining-accounts-util";
/**
* 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 tokenMintA - PublicKey for the token A mint.
* @param tokenMintB - PublicKey for the token B mint.
* @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 tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A.
* @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B.
* @param tokenProgramA - PublicKey for the token program for token A.
* @param tokenProgramB - PublicKey for the token program for token B.
* @param oracle - PublicKey for the oracle account for this Whirlpool.
* @param tokenAuthority - authority to withdraw tokens from the input token account
*/
export type SwapV2Params = SwapInput & {
whirlpool: PublicKey;
tokenMintA: PublicKey;
tokenMintB: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
tokenTransferHookAccountsA?: AccountMeta[];
tokenTransferHookAccountsB?: AccountMeta[];
tokenProgramA: PublicKey;
tokenProgramB: PublicKey;
oracle: PublicKey;
tokenAuthority: PublicKey;
};
/**
* 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 SwapV2Params}
* @returns - Instruction to perform the action.
*/
export function swapV2Ix(
program: Program<Whirlpool>,
params: SwapV2Params,
): Instruction {
const {
amount,
otherAmountThreshold,
sqrtPriceLimit,
amountSpecifiedIsInput,
aToB,
whirlpool,
tokenAuthority,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenVaultA,
tokenOwnerAccountB,
tokenVaultB,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
tokenProgramA,
tokenProgramB,
tickArray0,
tickArray1,
tickArray2,
oracle,
supplementalTickArrays,
} = params;
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA)
.addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB)
.addSlice(
RemainingAccountsType.SupplementalTickArrays,
toSupplementalTickArrayAccountMetas(supplementalTickArrays),
)
.build();
const ix = program.instruction.swapV2(
amount,
otherAmountThreshold,
sqrtPriceLimit,
amountSpecifiedIsInput,
aToB,
remainingAccountsInfo,
{
accounts: {
tokenProgramA,
tokenProgramB,
memoProgram: MEMO_PROGRAM_ADDRESS,
tokenAuthority: tokenAuthority,
whirlpool,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenVaultA,
tokenOwnerAccountB,
tokenVaultB,
tickArray0,
tickArray1,
tickArray2,
oracle,
},
remainingAccounts,
},
);
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/delete-token-badge-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 delete a TokenBadge account.
*
* @category Instruction Types
* @param whirlpoolsConfig - PublicKey for the whirlpools config account
* @param whirlpoolsConfigExtension - PublicKey for the whirlpools config extension account
* @param tokenBadgeAuthority - PublicKey for the token badge authority
* @param tokenMint - Publickey for the mint for which the TokenBadge have been initialized
* @param tokenBadge - PublicKey for the token badge account to be deleted
* @param receiver - PublicKey for the account that will receive the rent
*/
export type DeleteTokenBadgeParams = {
whirlpoolsConfig: PublicKey;
whirlpoolsConfigExtension: PublicKey;
tokenBadgeAuthority: PublicKey;
tokenMint: PublicKey;
tokenBadge: PublicKey;
receiver: PublicKey;
};
/**
* Deletes a TokenBadge account.
*
* @category Instructions
* @param program - program object containing services required to generate the instruction
* @param params - DeleteTokenBadgeParams object
* @returns - Instruction to perform the action.
*/
export function deleteTokenBadgeIx(
program: Program<Whirlpool>,
params: DeleteTokenBadgeParams,
): Instruction {
const {
whirlpoolsConfig,
whirlpoolsConfigExtension,
tokenBadgeAuthority,
tokenMint,
tokenBadge,
receiver,
} = params;
const ix = program.instruction.deleteTokenBadge({
accounts: {
whirlpoolsConfig,
whirlpoolsConfigExtension,
tokenBadgeAuthority,
tokenMint,
tokenBadge,
receiver,
},
});
return {
instructions: [ix],
cleanupInstructions: [],
signers: [],
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
|
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/decrease-liquidity-ix.ts
|
import type { Program } from "@coral-xyz/anchor";
import type { Instruction } from "@orca-so/common-sdk";
import type { AccountMeta, PublicKey } from "@solana/web3.js";
import type { Whirlpool } from "../../artifacts/whirlpool";
import type { DecreaseLiquidityInput } from "../..";
import { MEMO_PROGRAM_ADDRESS } from "../..";
import {
RemainingAccountsBuilder,
RemainingAccountsType,
} from "../../utils/remaining-accounts-util";
/**
* 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 positionAuthority - authority that owns the token corresponding to this desired position.
* @param tokenMintA - PublicKey for the token A mint.
* @param tokenMintB - PublicKey for the token B mint.
* @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 tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A.
* @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B.
* @param tokenProgramA - PublicKey for the token program for token A.
* @param tokenProgramB - PublicKey for the token program for token B.
* @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 DecreaseLiquidityV2Params = {
whirlpool: PublicKey;
position: PublicKey;
positionTokenAccount: PublicKey;
positionAuthority: PublicKey;
tokenMintA: PublicKey;
tokenMintB: PublicKey;
tokenOwnerAccountA: PublicKey;
tokenOwnerAccountB: PublicKey;
tokenVaultA: PublicKey;
tokenVaultB: PublicKey;
tokenTransferHookAccountsA?: AccountMeta[];
tokenTransferHookAccountsB?: AccountMeta[];
tokenProgramA: PublicKey;
tokenProgramB: PublicKey;
tickArrayLower: PublicKey;
tickArrayUpper: PublicKey;
} & DecreaseLiquidityInput;
/**
* 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 - DecreaseLiquidityV2Params object
* @returns - Instruction to perform the action.
*/
export function decreaseLiquidityV2Ix(
program: Program<Whirlpool>,
params: DecreaseLiquidityV2Params,
): Instruction {
const {
liquidityAmount,
tokenMinA,
tokenMinB,
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
tokenTransferHookAccountsA,
tokenTransferHookAccountsB,
tokenProgramA,
tokenProgramB,
tickArrayLower,
tickArrayUpper,
} = params;
const [remainingAccountsInfo, remainingAccounts] =
new RemainingAccountsBuilder()
.addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA)
.addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB)
.build();
const ix = program.instruction.decreaseLiquidityV2(
liquidityAmount,
tokenMinA,
tokenMinB,
remainingAccountsInfo,
{
accounts: {
whirlpool,
positionAuthority,
position,
positionTokenAccount,
tokenMintA,
tokenMintB,
tokenOwnerAccountA,
tokenOwnerAccountB,
tokenVaultA,
tokenVaultB,
tokenProgramA,
tokenProgramB,
tickArrayLower,
tickArrayUpper,
memoProgram: MEMO_PROGRAM_ADDRESS,
},
remainingAccounts,
},
);
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.