repo_id
stringclasses 279
values | file_path
stringlengths 43
179
| content
stringlengths 1
4.18M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/increaseLiquidity.test.ts
|
import { describe, it, beforeAll } from "vitest";
import { increaseLiquidityInstructions } from "../src/increaseLiquidity";
import { rpc, signer, sendTransaction } from "./utils/mockRpc";
import { setupMint, setupAta } from "./utils/token";
import { fetchPosition, getPositionAddress } from "@orca-so/whirlpools-client";
import { fetchToken } from "@solana-program/token-2022";
import type { Address } from "@solana/web3.js";
import assert from "assert";
import {
setupPosition,
setupTEPosition,
setupWhirlpool,
} from "./utils/program";
import { DEFAULT_FUNDER, setDefaultFunder } from "../src/config";
import {
setupAtaTE,
setupMintTE,
setupMintTEFee,
} from "./utils/tokenExtensions";
const mintTypes = new Map([
["A", setupMint],
["B", setupMint],
["TEA", setupMintTE],
["TEB", setupMintTE],
["TEFee", setupMintTEFee],
]);
const ataTypes = new Map([
["A", setupAta],
["B", setupAta],
["TEA", setupAtaTE],
["TEB", setupAtaTE],
["TEFee", setupAtaTE],
]);
const poolTypes = new Map([
["A-B", setupWhirlpool],
["A-TEA", setupWhirlpool],
["TEA-TEB", setupWhirlpool],
["A-TEFee", setupWhirlpool],
]);
const positionTypes = new Map([
["equally centered", { tickLower: -100, tickUpper: 100 }],
["one sided A", { tickLower: -100, tickUpper: -1 }],
["one sided B", { tickLower: 1, tickUpper: 100 }],
]);
describe("Increase Liquidity Instructions", () => {
const tickSpacing = 64;
const tokenBalance = 1_000_000n;
const atas: Map<string, Address> = new Map();
const positions: Map<string, Address> = new Map();
beforeAll(async () => {
const mints: Map<string, Address> = new Map();
for (const [name, setup] of mintTypes) {
mints.set(name, await setup());
}
for (const [name, setup] of ataTypes) {
const mint = mints.get(name)!;
atas.set(name, await setup(mint, { amount: tokenBalance }));
}
const pools: Map<string, Address> = new Map();
for (const [name, setup] of poolTypes) {
const [mintAKey, mintBKey] = name.split("-");
const mintA = mints.get(mintAKey)!;
const mintB = mints.get(mintBKey)!;
pools.set(name, await setup(mintA, mintB, tickSpacing));
}
for (const [poolName, poolAddress] of pools) {
for (const [positionTypeName, tickRange] of positionTypes) {
const position = await setupPosition(poolAddress, tickRange);
positions.set(`${poolName} ${positionTypeName}`, position);
const positionTE = await setupTEPosition(poolAddress, tickRange);
positions.set(`TE ${poolName} ${positionTypeName}`, positionTE);
}
}
});
const testIncreaseLiquidity = async (
positionName: string,
poolName: string,
) => {
const positionMint = positions.get(positionName)!;
const [mintAKey, mintBKey] = poolName.split("-");
const ataA = atas.get(mintAKey)!;
const ataB = atas.get(mintBKey)!;
const param = { liquidity: 10_000n };
const { quote, instructions } = await increaseLiquidityInstructions(
rpc,
positionMint,
param,
);
const tokenBeforeA = await fetchToken(rpc, ataA);
const tokenBeforeB = await fetchToken(rpc, ataB);
await sendTransaction(instructions);
const positionAddress = await getPositionAddress(positionMint);
const position = await fetchPosition(rpc, positionAddress[0]);
const tokenAfterA = await fetchToken(rpc, ataA);
const tokenAfterB = await fetchToken(rpc, ataB);
const balanceChangeTokenA =
tokenBeforeA.data.amount - tokenAfterA.data.amount;
const balanceChangeTokenB =
tokenBeforeB.data.amount - tokenAfterB.data.amount;
assert.strictEqual(quote.tokenEstA, balanceChangeTokenA);
assert.strictEqual(quote.tokenEstB, balanceChangeTokenB);
assert.strictEqual(quote.liquidityDelta, position.data.liquidity);
};
for (const poolName of poolTypes.keys()) {
for (const positionTypeName of positionTypes.keys()) {
const positionName = `${poolName} ${positionTypeName}`;
it(`Increase liquidity for ${positionName}`, async () => {
await testIncreaseLiquidity(positionName, poolName);
});
const positionNameTE = `TE ${poolName} ${positionTypeName}`;
it(`Increase liquidity for ${positionNameTE}`, async () => {
await testIncreaseLiquidity(positionNameTE, poolName);
});
}
}
it("Should throw error if authority is default address", async () => {
const liquidity = 100_000n;
setDefaultFunder(DEFAULT_FUNDER);
await assert.rejects(
increaseLiquidityInstructions(rpc, positions.entries().next().value, {
liquidity,
}),
);
setDefaultFunder(signer);
});
it("Should throw error increase liquidity amount by token is equal or greater than the token balance", async () => {
const tokenAAmount = 1_000_000n;
await assert.rejects(
increaseLiquidityInstructions(rpc, positions.entries().next().value, {
tokenA: tokenAAmount,
}),
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/swap.test.ts
|
import { describe } from "vitest";
describe.skip("Swap", () => {
// TODO: <-
});
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/utils/program.ts
|
import {
fetchAllMaybeTickArray,
fetchWhirlpool,
getFeeTierAddress,
getInitializeConfigInstruction,
getInitializeFeeTierInstruction,
getInitializePoolV2Instruction,
getInitializeTickArrayInstruction,
getOpenPositionInstruction,
getOpenPositionWithTokenExtensionsInstruction,
getPositionAddress,
getTickArrayAddress,
getTokenBadgeAddress,
getWhirlpoolAddress,
} from "@orca-so/whirlpools-client";
import { address, type Address, type IInstruction } from "@solana/web3.js";
import { rpc, sendTransaction, signer } from "./mockRpc";
import {
SPLASH_POOL_TICK_SPACING,
WHIRLPOOLS_CONFIG_ADDRESS,
} from "../../src/config";
import {
getInitializableTickIndex,
getTickArrayStartTickIndex,
tickIndexToSqrtPrice,
} from "@orca-so/whirlpools-core";
import {
TOKEN_2022_PROGRAM_ADDRESS,
ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
fetchMint,
findAssociatedTokenPda,
} from "@solana-program/token-2022";
import { getNextKeypair } from "./keypair";
import { TOKEN_PROGRAM_ADDRESS } from "@solana-program/token";
export async function setupConfigAndFeeTiers(): Promise<Address> {
const keypair = getNextKeypair();
const instructions: IInstruction[] = [];
instructions.push(
getInitializeConfigInstruction({
config: keypair,
funder: signer,
feeAuthority: signer.address,
collectProtocolFeesAuthority: signer.address,
rewardEmissionsSuperAuthority: signer.address,
defaultProtocolFeeRate: 100,
}),
);
const defaultFeeTierPda = await getFeeTierAddress(keypair.address, 128);
instructions.push(
getInitializeFeeTierInstruction({
config: keypair.address,
feeTier: defaultFeeTierPda[0],
funder: signer,
feeAuthority: signer,
tickSpacing: 128,
defaultFeeRate: 1000,
}),
);
const concentratedFeeTierPda = await getFeeTierAddress(keypair.address, 64);
instructions.push(
getInitializeFeeTierInstruction({
config: keypair.address,
feeTier: concentratedFeeTierPda[0],
funder: signer,
feeAuthority: signer,
tickSpacing: 64,
defaultFeeRate: 300,
}),
);
const splashFeeTierPda = await getFeeTierAddress(
keypair.address,
SPLASH_POOL_TICK_SPACING,
);
instructions.push(
getInitializeFeeTierInstruction({
config: keypair.address,
feeTier: splashFeeTierPda[0],
funder: signer,
feeAuthority: signer,
tickSpacing: SPLASH_POOL_TICK_SPACING,
defaultFeeRate: 1000,
}),
);
await sendTransaction(instructions);
return keypair.address;
}
export async function setupWhirlpool(
tokenA: Address,
tokenB: Address,
tickSpacing: number,
config: { initialSqrtPrice?: bigint } = {},
): Promise<Address> {
const feeTierAddress = await getFeeTierAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tickSpacing,
);
const whirlpoolAddress = await getWhirlpoolAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tokenA,
tokenB,
tickSpacing,
);
const vaultA = getNextKeypair();
const vaultB = getNextKeypair();
const badgeA = await getTokenBadgeAddress(WHIRLPOOLS_CONFIG_ADDRESS, tokenA);
const badgeB = await getTokenBadgeAddress(WHIRLPOOLS_CONFIG_ADDRESS, tokenB);
const mintA = await fetchMint(rpc, tokenA);
const mintB = await fetchMint(rpc, tokenB);
const programA = mintA.programAddress;
const programB = mintB.programAddress;
const sqrtPrice = config.initialSqrtPrice ?? tickIndexToSqrtPrice(0);
const instructions: IInstruction[] = [];
instructions.push(
getInitializePoolV2Instruction({
whirlpool: whirlpoolAddress[0],
feeTier: feeTierAddress[0],
tokenMintA: tokenA,
tokenMintB: tokenB,
tickSpacing,
whirlpoolsConfig: WHIRLPOOLS_CONFIG_ADDRESS,
funder: signer,
tokenVaultA: vaultA,
tokenVaultB: vaultB,
tokenBadgeA: badgeA[0],
tokenBadgeB: badgeB[0],
tokenProgramA: programA,
tokenProgramB: programB,
initialSqrtPrice: sqrtPrice,
}),
);
await sendTransaction(instructions);
return whirlpoolAddress[0];
}
export async function setupPosition(
whirlpool: Address,
config: { tickLower?: number; tickUpper?: number; liquidity?: bigint } = {},
): Promise<Address> {
const positionMint = getNextKeypair();
const whirlpoolAccount = await fetchWhirlpool(rpc, whirlpool);
const tickLower = config.tickLower ?? -100;
const tickUpper = config.tickLower ?? 100;
const initializableLowerTickIndex = getInitializableTickIndex(
tickLower,
whirlpoolAccount.data.tickSpacing,
false,
);
const initializableUpperTickIndex = getInitializableTickIndex(
tickUpper,
whirlpoolAccount.data.tickSpacing,
true,
);
const lowerTickArrayIndex = getTickArrayStartTickIndex(
initializableLowerTickIndex,
whirlpoolAccount.data.tickSpacing,
);
const upperTickArrayIndex = getTickArrayStartTickIndex(
initializableUpperTickIndex,
whirlpoolAccount.data.tickSpacing,
);
const [
positionAddress,
positionTokenAccount,
lowerTickArrayAddress,
upperTickArrayAddress,
] = await Promise.all([
getPositionAddress(positionMint.address),
findAssociatedTokenPda({
owner: signer.address,
mint: positionMint.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool, lowerTickArrayIndex).then((x) => x[0]),
getTickArrayAddress(whirlpool, upperTickArrayIndex).then((x) => x[0]),
]);
const [lowerTickArray, upperTickArray] = await fetchAllMaybeTickArray(rpc, [
lowerTickArrayAddress,
upperTickArrayAddress,
]);
const instructions: IInstruction[] = [];
if (!lowerTickArray.exists) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool,
funder: signer,
tickArray: lowerTickArrayAddress,
startTickIndex: lowerTickArrayIndex,
}),
);
}
if (!upperTickArray.exists && lowerTickArrayIndex !== upperTickArrayIndex) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool,
funder: signer,
tickArray: upperTickArrayAddress,
startTickIndex: upperTickArrayIndex,
}),
);
}
instructions.push(
getOpenPositionInstruction({
funder: signer,
owner: signer.address,
position: positionAddress[0],
positionMint: positionMint,
positionTokenAccount: positionTokenAccount,
whirlpool: whirlpool,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
tickLowerIndex: initializableLowerTickIndex,
tickUpperIndex: initializableUpperTickIndex,
positionBump: positionAddress[1],
}),
);
await sendTransaction(instructions);
return positionMint.address;
}
export async function setupTEPosition(
whirlpool: Address,
config: { tickLower?: number; tickUpper?: number; liquidity?: bigint } = {},
): Promise<Address> {
const metadataUpdateAuth = address(
"3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr",
);
const positionMint = getNextKeypair();
const whirlpoolAccount = await fetchWhirlpool(rpc, whirlpool);
const tickLower = config.tickLower ?? -100;
const tickUpper = config.tickLower ?? 100;
const initializableLowerTickIndex = getInitializableTickIndex(
tickLower,
whirlpoolAccount.data.tickSpacing,
false,
);
const initializableUpperTickIndex = getInitializableTickIndex(
tickUpper,
whirlpoolAccount.data.tickSpacing,
true,
);
const lowerTickArrayIndex = getTickArrayStartTickIndex(
initializableLowerTickIndex,
whirlpoolAccount.data.tickSpacing,
);
const upperTickArrayIndex = getTickArrayStartTickIndex(
initializableUpperTickIndex,
whirlpoolAccount.data.tickSpacing,
);
const [
positionAddress,
positionTokenAccount,
lowerTickArrayAddress,
upperTickArrayAddress,
] = await Promise.all([
getPositionAddress(positionMint.address),
findAssociatedTokenPda({
owner: signer.address,
mint: positionMint.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool, lowerTickArrayIndex).then((x) => x[0]),
getTickArrayAddress(whirlpool, upperTickArrayIndex).then((x) => x[0]),
]);
const [lowerTickArray, upperTickArray] = await fetchAllMaybeTickArray(rpc, [
lowerTickArrayAddress,
upperTickArrayAddress,
]);
const instructions: IInstruction[] = [];
if (!lowerTickArray.exists) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool,
funder: signer,
tickArray: lowerTickArrayAddress,
startTickIndex: lowerTickArrayIndex,
}),
);
}
if (!upperTickArray.exists && lowerTickArrayIndex !== upperTickArrayIndex) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool,
funder: signer,
tickArray: upperTickArrayAddress,
startTickIndex: upperTickArrayIndex,
}),
);
}
instructions.push(
getOpenPositionWithTokenExtensionsInstruction({
funder: signer,
owner: signer.address,
position: positionAddress[0],
positionMint: positionMint,
positionTokenAccount: positionTokenAccount,
whirlpool: whirlpool,
token2022Program: TOKEN_2022_PROGRAM_ADDRESS,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
metadataUpdateAuth: metadataUpdateAuth,
tickLowerIndex: initializableLowerTickIndex,
tickUpperIndex: initializableUpperTickIndex,
withTokenMetadataExtension: true,
}),
);
await sendTransaction(instructions);
return positionMint.address;
}
export async function setupPositionBundle(
whirlpool: Address,
config: { tickLower?: number; tickUpper?: number; liquidity?: bigint }[] = [],
): Promise<Address> {
// TODO: implement when solana-bankrun supports gpa
const _ = config;
return whirlpool;
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/utils/mockRpc.ts
|
import type {
Address,
IInstruction,
VariableSizeDecoder,
} from "@solana/web3.js";
import {
appendTransactionMessageInstructions,
assertIsAddress,
createSolanaRpcFromTransport,
createTransactionMessage,
getAddressDecoder,
getAddressEncoder,
getBase58Decoder,
getBase64Decoder,
getBase64EncodedWireTransaction,
getBase64Encoder,
getTransactionDecoder,
lamports,
pipe,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners,
} from "@solana/web3.js";
import assert from "assert";
import type { ProgramTestContext } from "solana-bankrun/dist/internal";
import { Account, startAnchor } from "solana-bankrun/dist/internal";
import { SYSTEM_PROGRAM_ADDRESS } from "@solana-program/system";
import { setDefaultFunder, setWhirlpoolsConfig } from "../../src/config";
import { setupConfigAndFeeTiers } from "./program";
import { getAddMemoInstruction } from "@solana-program/memo";
import { randomUUID } from "crypto";
import { getNextKeypair } from "./keypair";
export const signer = getNextKeypair();
setDefaultFunder(signer);
function toBytes(address: Address): Uint8Array {
return new Uint8Array(getAddressEncoder().encode(address));
}
let _testContext: ProgramTestContext | null = null;
export async function getTestContext(): Promise<ProgramTestContext> {
if (_testContext == null) {
_testContext = await startAnchor(
"../../",
[],
[
[
toBytes(signer.address),
new Account(
BigInt(100e9),
new Uint8Array(),
toBytes(SYSTEM_PROGRAM_ADDRESS),
false,
0n,
),
],
],
);
const configAddress = await setupConfigAndFeeTiers();
setWhirlpoolsConfig(configAddress);
}
return _testContext;
}
export async function deleteAccount(address: Address) {
const testContext = await getTestContext();
testContext.setAccount(
toBytes(address),
new Account(
BigInt(0),
new Uint8Array(),
toBytes(SYSTEM_PROGRAM_ADDRESS),
false,
0n,
),
);
}
export async function sendTransaction(ixs: IInstruction[]) {
const blockhash = await rpc.getLatestBlockhash().send();
// Sine blockhash is not guaranteed to be unique, we need to add a random memo to the tx
// so that we can fire two seemingly identical transactions in a row.
const memo = getAddMemoInstruction({
memo: randomUUID().toString(),
});
const transaction = await pipe(
createTransactionMessage({ version: 0 }),
(x) => appendTransactionMessageInstructions([memo, ...ixs], x),
(x) => setTransactionMessageFeePayerSigner(signer, x),
(x) => setTransactionMessageLifetimeUsingBlockhash(blockhash.value, x),
(x) => signTransactionMessageWithSigners(x),
);
const serialized = getBase64EncodedWireTransaction(transaction);
const signature = await rpc.sendTransaction(serialized).send();
return signature;
}
const decoders: Record<string, VariableSizeDecoder<string>> = {
base58: getBase58Decoder(),
base64: getBase64Decoder(),
};
async function getAccountData<T>(address: unknown, opts: unknown): Promise<T> {
assert(typeof opts === "object");
assert(opts != null);
let encoding: string;
if ("encoding" in opts) {
assert(typeof opts.encoding === "string");
encoding = opts.encoding;
} else {
encoding = "base58";
}
const decoder = decoders[encoding];
if (decoder == null) {
throw new Error(`No decoder found for ${encoding}`);
}
assert(typeof address === "string");
assertIsAddress(address);
const testContext = await getTestContext();
const account = await testContext.banksClient.getAccount(toBytes(address));
if (account == null || account.lamports === 0n) {
return null as T;
}
return {
data: [decoder.decode(account.data), encoding],
executable: false,
lamports: lamports(account.lamports),
owner: getAddressDecoder().decode(account.owner),
rentEpoch: 0n,
space: account.data.length,
} as T;
}
function getResponseWithContext<T>(value: unknown): T {
return {
jsonrpc: "2.0",
result: {
context: {
slot: 1,
},
value,
},
} as T;
}
function getResponse<T>(value: unknown): T {
return {
jsonrpc: "2.0",
result: value,
} as T;
}
async function mockTransport<T>(
config: Readonly<{
payload: unknown;
signal?: AbortSignal;
}>,
): Promise<T> {
assert(typeof config.payload === "object");
assert(config.payload != null);
assert("method" in config.payload);
assert(typeof config.payload.method === "string");
assert("params" in config.payload);
assert(Array.isArray(config.payload.params));
const testContext = await getTestContext();
switch (config.payload.method) {
case "getAccountInfo":
const address = config.payload.params[0];
assert(typeof address === "string");
const accountData = await getAccountData(
address,
config.payload.params[1],
);
return getResponseWithContext<T>(accountData);
case "getMultipleAccounts":
const addresses = config.payload.params[0];
const opts = config.payload.params[1];
assert(Array.isArray(addresses));
const accountsData = await Promise.all(
addresses.map((x) => getAccountData(x, opts)),
);
return getResponseWithContext<T>(accountsData);
case "getProgramAccounts":
throw new Error("gpa is not yet exposed through solana-bankrun");
case "getTokenAccountsByOwner":
throw new Error(
"getTokenAccountsByOwner is not yet exposed through solana-bankrun",
);
case "getMinimumBalanceForRentExemption":
const space = config.payload.params[0];
assert(typeof space === "number");
const rent = await testContext.banksClient.getRent();
const exemptAmount = rent.minimumBalance(BigInt(space));
return getResponse<T>(exemptAmount);
case "getLatestBlockhash":
const blockhash = await testContext.banksClient.getLatestBlockhash();
assert(blockhash != null);
return getResponseWithContext<T>({
blockhash: blockhash.blockhash,
lastValidBlockHeight: blockhash.lastValidBlockHeight,
});
case "sendTransaction":
const serialized = config.payload.params[0];
assert(typeof serialized === "string");
const wireTransaction = new Uint8Array(
getBase64Encoder().encode(serialized),
);
const transaction = getTransactionDecoder().decode(wireTransaction);
const signatureBytes = Object.values(transaction.signatures)[0];
const signature = getBase58Decoder().decode(
signatureBytes ?? new Uint8Array(),
);
const { result } =
await testContext.banksClient.tryProcessVersionedTransaction(
wireTransaction,
);
assert(result == null, result ?? "");
return getResponse<T>(signature);
case "getEpochInfo":
const slot = await testContext.banksClient.getSlot();
return getResponse<T>({
epoch: slot / 32n,
absoluteSlot: slot,
blockheight: slot,
slotIndex: slot % 32n,
slotsInEpoch: 32n,
transactionCount: 0n,
});
case "getBalance":
const addressForBalance = config.payload.params[0];
assert(typeof addressForBalance === "string");
const accountDataForBalance = await getAccountData(
addressForBalance,
config.payload.params[1],
);
assert(accountDataForBalance !== null);
assert(typeof accountDataForBalance === "object");
assert("lamports" in accountDataForBalance);
const lamports = accountDataForBalance.lamports;
return getResponseWithContext<T>(lamports);
}
return Promise.reject(
`Method ${config.payload.method} not supported in mock transport`,
);
}
export const rpc = createSolanaRpcFromTransport(mockTransport);
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/utils/keypair.ts
|
import type { KeyPairSigner } from "@solana/web3.js";
import { generateKeyPairSigner } from "@solana/web3.js";
import { orderMints } from "../../src/token";
const keypairs = await Promise.all(
Array(100)
.fill(0)
.map(() => generateKeyPairSigner()),
);
const orderedKeypairs = [...keypairs].sort((a, b) =>
orderMints(a.address, b.address)[0] === a.address ? -1 : 1,
);
let index = 0;
/**
* Because for certain functions mint keypairs need to be ordered correctly
* we made this function to get the next keypair in such a way that it
* is always ordered behind the previous one
*/
export function getNextKeypair(): KeyPairSigner {
return orderedKeypairs[index++];
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/utils/token.ts
|
import {
getCreateAccountInstruction,
getTransferSolInstruction,
} from "@solana-program/system";
import {
getMintSize,
getInitializeMint2Instruction,
TOKEN_PROGRAM_ADDRESS,
getCreateAssociatedTokenIdempotentInstruction,
findAssociatedTokenPda,
getMintToInstruction,
getSyncNativeInstruction,
} from "@solana-program/token";
import type { Address, IInstruction } from "@solana/web3.js";
import { signer, sendTransaction } from "./mockRpc";
import { NATIVE_MINT } from "../../src/token";
import { getNextKeypair } from "./keypair";
export async function setupAta(
mint: Address,
config: { amount?: number | bigint } = {},
): Promise<Address> {
const ata = await findAssociatedTokenPda({
mint,
owner: signer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const instructions: IInstruction[] = [];
instructions.push(
getCreateAssociatedTokenIdempotentInstruction({
mint,
owner: signer.address,
ata: ata[0],
payer: signer,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
}),
);
if (config.amount) {
if (mint === NATIVE_MINT) {
instructions.push(
getTransferSolInstruction({
source: signer,
destination: ata[0],
amount: config.amount,
}),
);
instructions.push(
getSyncNativeInstruction({
account: ata[0],
}),
);
} else {
instructions.push(
getMintToInstruction({
mint,
token: ata[0],
mintAuthority: signer,
amount: config.amount,
}),
);
}
}
await sendTransaction(instructions);
return ata[0];
}
export async function setupMint(
config: { decimals?: number } = {},
): Promise<Address> {
const keypair = getNextKeypair();
const instructions: IInstruction[] = [];
instructions.push(
getCreateAccountInstruction({
payer: signer,
newAccount: keypair,
lamports: 1e8,
space: getMintSize(),
programAddress: TOKEN_PROGRAM_ADDRESS,
}),
);
instructions.push(
getInitializeMint2Instruction({
mint: keypair.address,
mintAuthority: signer.address,
freezeAuthority: null,
decimals: config.decimals ?? 6,
}),
);
await sendTransaction(instructions);
return keypair.address;
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/tests/utils/tokenExtensions.ts
|
import type { ExtensionArgs } from "@solana-program/token-2022";
import {
findAssociatedTokenPda,
TOKEN_2022_PROGRAM_ADDRESS,
getCreateAssociatedTokenIdempotentInstruction,
getMintToInstruction,
getMintSize,
getInitializeMint2Instruction,
getInitializeTransferFeeConfigInstruction,
getSetTransferFeeInstruction,
} from "@solana-program/token-2022";
import type { Address, IInstruction } from "@solana/web3.js";
import { sendTransaction, signer } from "./mockRpc";
import { getCreateAccountInstruction } from "@solana-program/system";
import { DEFAULT_ADDRESS } from "../../src/config";
import { getNextKeypair } from "./keypair";
export async function setupAtaTE(
mint: Address,
config: { amount?: number | bigint } = {},
): Promise<Address> {
const ata = await findAssociatedTokenPda({
mint,
owner: signer.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
});
const instructions: IInstruction[] = [];
instructions.push(
getCreateAssociatedTokenIdempotentInstruction({
mint,
owner: signer.address,
ata: ata[0],
payer: signer,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
}),
);
if (config.amount) {
instructions.push(
getMintToInstruction({
mint,
token: ata[0],
mintAuthority: signer,
amount: config.amount,
}),
);
}
await sendTransaction(instructions);
return ata[0];
}
export async function setupMintTE(
config: { decimals?: number; extensions?: ExtensionArgs[] } = {},
): Promise<Address> {
const keypair = getNextKeypair();
const instructions: IInstruction[] = [];
instructions.push(
getCreateAccountInstruction({
payer: signer,
newAccount: keypair,
lamports: 1e8,
space: getMintSize(config.extensions),
programAddress: TOKEN_2022_PROGRAM_ADDRESS,
}),
);
for (const extension of config.extensions ?? []) {
switch (extension.__kind) {
case "TransferFeeConfig":
instructions.push(
getInitializeTransferFeeConfigInstruction({
mint: keypair.address,
transferFeeConfigAuthority: signer.address,
withdrawWithheldAuthority: signer.address,
transferFeeBasisPoints:
extension.olderTransferFee.transferFeeBasisPoints,
maximumFee: extension.olderTransferFee.maximumFee,
}),
);
}
}
instructions.push(
getInitializeMint2Instruction({
mint: keypair.address,
mintAuthority: signer.address,
freezeAuthority: null,
decimals: config.decimals ?? 6,
}),
);
for (const extension of config.extensions ?? []) {
switch (extension.__kind) {
case "TransferFeeConfig":
instructions.push(
getSetTransferFeeInstruction({
mint: keypair.address,
transferFeeConfigAuthority: signer.address,
transferFeeBasisPoints:
extension.newerTransferFee.transferFeeBasisPoints,
maximumFee: extension.newerTransferFee.maximumFee,
}),
);
}
}
await sendTransaction(instructions);
return keypair.address;
}
export async function setupMintTEFee(
config: { decimals?: number } = {},
): Promise<Address> {
return setupMintTE({
...config,
extensions: [
{
__kind: "TransferFeeConfig",
transferFeeConfigAuthority: DEFAULT_ADDRESS,
withdrawWithheldAuthority: DEFAULT_ADDRESS,
withheldAmount: 0n,
olderTransferFee: {
epoch: 0n,
maximumFee: 1e9,
transferFeeBasisPoints: 100,
},
newerTransferFee: {
epoch: 10n,
maximumFee: 1e9,
transferFeeBasisPoints: 150,
},
},
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/pool.ts
|
import type { Whirlpool } from "@orca-so/whirlpools-client";
import {
getFeeTierAddress,
getWhirlpoolAddress,
fetchWhirlpoolsConfig,
fetchFeeTier,
fetchMaybeWhirlpool,
fetchAllMaybeWhirlpool,
fetchAllFeeTierWithFilter,
feeTierWhirlpoolsConfigFilter,
} from "@orca-so/whirlpools-client";
import type {
Rpc,
GetAccountInfoApi,
GetMultipleAccountsApi,
Address,
GetProgramAccountsApi,
} from "@solana/web3.js";
import { SPLASH_POOL_TICK_SPACING, WHIRLPOOLS_CONFIG_ADDRESS } from "./config";
import { orderMints } from "./token";
import { sqrtPriceToPrice } from "@orca-so/whirlpools-core";
import { fetchAllMint } from "@solana-program/token";
/**
* Type representing a pool that is not yet initialized.
*/
export type InitializablePool = {
/** Indicates the pool is not initialized. */
initialized: false;
} & Pick<
Whirlpool,
| "whirlpoolsConfig"
| "tickSpacing"
| "feeRate"
| "protocolFeeRate"
| "tokenMintA"
| "tokenMintB"
>;
/**
* Type representing a pool that has been initialized.
* Extends the `Whirlpool` type, inheriting all its properties.
*/
export type InitializedPool = {
/** Indicates the pool is initialized. */
initialized: true;
price: number;
} & Whirlpool;
/**
* Combined type representing both initialized and uninitialized pools.
*/
export type PoolInfo = (InitializablePool | InitializedPool) & {
/** The address of the pool. */
address: Address;
};
/**
* Fetches the details of a specific Splash Pool.
*
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {Address} tokenMintOne - The first token mint address in the pool.
* @param {Address} tokenMintTwo - The second token mint address in the pool.
* @returns {Promise<PoolInfo>} - A promise that resolves to the pool information, which includes whether the pool is initialized or not.
*
* @example
* import { fetchSplashPool, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const tokenMintOne = address("So11111111111111111111111111111111111111112");
* const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //devUSDC
*
* const poolInfo = await fetchSplashPool(
* devnetRpc,
* tokenMintOne,
* tokenMintTwo
* );
*
* if (poolInfo.initialized) {
* console.log("Pool is initialized:", poolInfo);
* } else {
* console.log("Pool is not initialized:", poolInfo);
* };
*/
export async function fetchSplashPool(
rpc: Rpc<GetAccountInfoApi & GetMultipleAccountsApi>,
tokenMintOne: Address,
tokenMintTwo: Address,
): Promise<PoolInfo> {
return fetchConcentratedLiquidityPool(
rpc,
tokenMintOne,
tokenMintTwo,
SPLASH_POOL_TICK_SPACING,
);
}
/**
* Fetches the details of a specific Concentrated Liquidity Pool.
*
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {Address} tokenMintOne - The first token mint address in the pool.
* @param {Address} tokenMintTwo - The second token mint address in the pool.
* @param {number} tickSpacing - The tick spacing of the pool.
* @returns {Promise<PoolInfo>} - A promise that resolves to the pool information, which includes whether the pool is initialized or not.
*
* @example
* import { fetchConcentratedLiquidityPool, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
*
* const tokenMintOne = address("So11111111111111111111111111111111111111112");
* const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k");
* const tickSpacing = 64;
*
* const poolInfo = await fetchConcentratedLiquidityPool(
* devnetRpc,
* tokenMintOne,
* tokenMintTwo,
* tickSpacing
* );
*
* if (poolInfo.initialized) {
* console.log("Pool is initialized:", poolInfo);
* } else {
* console.log("Pool is not initialized:", poolInfo);
* };
*/
export async function fetchConcentratedLiquidityPool(
rpc: Rpc<GetAccountInfoApi & GetMultipleAccountsApi>,
tokenMintOne: Address,
tokenMintTwo: Address,
tickSpacing: number,
): Promise<PoolInfo> {
const [tokenMintA, tokenMintB] = orderMints(tokenMintOne, tokenMintTwo);
const feeTierAddress = await getFeeTierAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tickSpacing,
).then((x) => x[0]);
const poolAddress = await getWhirlpoolAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tokenMintA,
tokenMintB,
tickSpacing,
).then((x) => x[0]);
// TODO: this is multiple rpc calls. Can we do it in one?
const [configAccount, feeTierAccount, poolAccount] = await Promise.all([
fetchWhirlpoolsConfig(rpc, WHIRLPOOLS_CONFIG_ADDRESS),
fetchFeeTier(rpc, feeTierAddress),
fetchMaybeWhirlpool(rpc, poolAddress),
]);
const [mintA, mintB] = await fetchAllMint(rpc, [tokenMintA, tokenMintB]);
if (poolAccount.exists) {
const poolPrice = sqrtPriceToPrice(
poolAccount.data.sqrtPrice,
mintA.data.decimals,
mintB.data.decimals,
);
return {
initialized: true,
address: poolAddress,
price: poolPrice,
...poolAccount.data,
};
} else {
return {
initialized: false,
address: poolAddress,
whirlpoolsConfig: WHIRLPOOLS_CONFIG_ADDRESS,
tickSpacing,
feeRate: feeTierAccount.data.defaultFeeRate,
protocolFeeRate: configAccount.data.defaultProtocolFeeRate,
tokenMintA: tokenMintA,
tokenMintB: tokenMintB,
};
}
}
/**
* Fetches all possible liquidity pools between two token mints in Orca Whirlpools.
* If a pool does not exist, it creates a placeholder account for the uninitialized pool with default data
*
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {Address} tokenMintOne - The first token mint address in the pool.
* @param {Address} tokenMintTwo - The second token mint address in the pool.
* @returns {Promise<PoolInfo[]>} - A promise that resolves to an array of pool information for each pool between the two tokens.
*
* @example
* import { fetchWhirlpoolsByTokenPair, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
*
* const tokenMintOne = address("So11111111111111111111111111111111111111112");
* const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k");
*
* const poolInfos = await fetchWhirlpoolsByTokenPair(
* devnetRpc,
* tokenMintOne,
* tokenMintTwo
* );
*
* poolInfos.forEach((poolInfo) => {
* if (poolInfo.initialized) {
* console.log("Pool is initialized:", poolInfo);
* } else {
* console.log("Pool is not initialized:", poolInfo);
* }
* });
*/
export async function fetchWhirlpoolsByTokenPair(
rpc: Rpc<GetAccountInfoApi & GetMultipleAccountsApi & GetProgramAccountsApi>,
tokenMintOne: Address,
tokenMintTwo: Address,
): Promise<PoolInfo[]> {
const [tokenMintA, tokenMintB] = orderMints(tokenMintOne, tokenMintTwo);
const feeTierAccounts = await fetchAllFeeTierWithFilter(
rpc,
feeTierWhirlpoolsConfigFilter(WHIRLPOOLS_CONFIG_ADDRESS),
);
const supportedTickSpacings = feeTierAccounts.map((x) => x.data.tickSpacing);
const poolAddresses = await Promise.all(
supportedTickSpacings.map((x) =>
getWhirlpoolAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tokenMintA,
tokenMintB,
x,
).then((x) => x[0]),
),
);
// TODO: this is multiple rpc calls. Can we do it in one?
const [configAccount, poolAccounts] = await Promise.all([
fetchWhirlpoolsConfig(rpc, WHIRLPOOLS_CONFIG_ADDRESS),
fetchAllMaybeWhirlpool(rpc, poolAddresses),
]);
const [mintA, mintB] = await fetchAllMint(rpc, [tokenMintA, tokenMintB]);
const pools: PoolInfo[] = [];
for (let i = 0; i < supportedTickSpacings.length; i++) {
const tickSpacing = supportedTickSpacings[i];
const feeTierAccount = feeTierAccounts[i];
const poolAccount = poolAccounts[i];
const poolAddress = poolAddresses[i];
if (poolAccount.exists) {
const poolPrice = sqrtPriceToPrice(
poolAccount.data.sqrtPrice,
mintA.data.decimals,
mintB.data.decimals,
);
pools.push({
initialized: true,
address: poolAddress,
price: poolPrice,
...poolAccount.data,
});
} else {
pools.push({
initialized: false,
address: poolAddress,
whirlpoolsConfig: WHIRLPOOLS_CONFIG_ADDRESS,
tickSpacing,
feeRate: feeTierAccount.data.defaultFeeRate,
protocolFeeRate: configAccount.data.defaultProtocolFeeRate,
tokenMintA,
tokenMintB,
});
}
}
return pools;
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/createPool.ts
|
import {
getFeeTierAddress,
getInitializePoolV2Instruction,
getInitializeTickArrayInstruction,
getTickArrayAddress,
getTickArraySize,
getTokenBadgeAddress,
getWhirlpoolAddress,
getWhirlpoolSize,
} from "@orca-so/whirlpools-client";
import type {
Address,
GetAccountInfoApi,
GetMultipleAccountsApi,
IInstruction,
Lamports,
Rpc,
TransactionSigner,
} from "@solana/web3.js";
import { generateKeyPairSigner, lamports } from "@solana/web3.js";
import { fetchSysvarRent } from "@solana/sysvars";
import {
DEFAULT_ADDRESS,
FUNDER,
SPLASH_POOL_TICK_SPACING,
WHIRLPOOLS_CONFIG_ADDRESS,
} from "./config";
import {
getFullRangeTickIndexes,
getTickArrayStartTickIndex,
priceToSqrtPrice,
sqrtPriceToTickIndex,
} from "@orca-so/whirlpools-core";
import { fetchAllMint } from "@solana-program/token-2022";
import assert from "assert";
import { getTokenSizeForMint, orderMints } from "./token";
import { calculateMinimumBalanceForRentExemption } from "./sysvar";
/**
* Represents the instructions and metadata for creating a pool.
*/
export type CreatePoolInstructions = {
/** The list of instructions needed to create the pool. */
instructions: IInstruction[];
/** The estimated rent exemption cost for initializing the pool, in lamports. */
initializationCost: Lamports;
/** The address of the newly created pool. */
poolAddress: Address;
};
/**
* Creates the necessary instructions to initialize a Splash Pool on Orca Whirlpools.
*
* @param {SolanaRpc} rpc - A Solana RPC client for communicating with the blockchain.
* @param {Address} tokenMintA - The first token mint address to include in the pool.
* @param {Address} tokenMintB - The second token mint address to include in the pool.
* @param {number} [initialPrice=1] - The initial price of token 1 in terms of token 2.
* @param {TransactionSigner} [funder=FUNDER] - The account that will fund the initialization process.
*
* @returns {Promise<CreatePoolInstructions>} A promise that resolves to an object containing the pool creation instructions, the estimated initialization cost, and the pool address.
*
* @example
* import { createSplashPoolInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent.
*
* const tokenMintOne = address("So11111111111111111111111111111111111111112");
* const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // devUSDC
* const initialPrice = 0.01;
*
* const { poolAddress, instructions, initializationCost } = await createSplashPoolInstructions(
* devnetRpc,
* tokenMintOne,
* tokenMintTwo,
* initialPrice,
* wallet
* );
*
* console.log(`Pool Address: ${poolAddress}`);
* console.log(`Initialization Cost: ${initializationCost} lamports`);
*/
export function createSplashPoolInstructions(
rpc: Rpc<GetAccountInfoApi & GetMultipleAccountsApi>,
tokenMintA: Address,
tokenMintB: Address,
initialPrice: number = 1,
funder: TransactionSigner = FUNDER,
): Promise<CreatePoolInstructions> {
return createConcentratedLiquidityPoolInstructions(
rpc,
tokenMintA,
tokenMintB,
SPLASH_POOL_TICK_SPACING,
initialPrice,
funder,
);
}
/**
* Creates the necessary instructions to initialize a Concentrated Liquidity Pool (CLMM) on Orca Whirlpools.
*
* @param {SolanaRpc} rpc - A Solana RPC client for communicating with the blockchain.
* @param {Address} tokenMintA - The first token mint address to include in the pool.
* @param {Address} tokenMintB - The second token mint address to include in the pool.
* @param {number} tickSpacing - The spacing between price ticks for the pool.
* @param {number} [initialPrice=1] - The initial price of token 1 in terms of token 2.
* @param {TransactionSigner} [funder=FUNDER] - The account that will fund the initialization process.
*
* @returns {Promise<CreatePoolInstructions>} A promise that resolves to an object containing the pool creation instructions, the estimated initialization cost, and the pool address.
*
* @example
* import { createConcentratedLiquidityPoolInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent.
*
* const tokenMintOne = address("So11111111111111111111111111111111111111112");
* const tokenMintTwo = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // devUSDC
* const tickSpacing = 64;
* const initialPrice = 0.01;
*
* const { poolAddress, instructions, initializationCost } = await createConcentratedLiquidityPoolInstructions(
* devnetRpc,
* tokenMintOne,
* tokenMintTwo,
* tickSpacing,
* initialPrice,
* wallet
* );
*
* console.log(`Pool Address: ${poolAddress}`);
* console.log(`Initialization Cost: ${initializationCost} lamports`);
*/
export async function createConcentratedLiquidityPoolInstructions(
rpc: Rpc<GetAccountInfoApi & GetMultipleAccountsApi>,
tokenMintA: Address,
tokenMintB: Address,
tickSpacing: number,
initialPrice: number = 1,
funder: TransactionSigner = FUNDER,
): Promise<CreatePoolInstructions> {
assert(
funder.address !== DEFAULT_ADDRESS,
"Either supply a funder or set the default funder",
);
assert(
orderMints(tokenMintA, tokenMintB)[0] === tokenMintA,
"Token order needs to be flipped to match the canonical ordering (i.e. sorted on the byte repr. of the mint pubkeys)",
);
const instructions: IInstruction[] = [];
const rent = await fetchSysvarRent(rpc);
let nonRefundableRent: bigint = 0n;
// Since TE mint data is an extension of T mint data, we can use the same fetch function
const [mintA, mintB] = await fetchAllMint(rpc, [tokenMintA, tokenMintB]);
const decimalsA = mintA.data.decimals;
const decimalsB = mintB.data.decimals;
const tokenProgramA = mintA.programAddress;
const tokenProgramB = mintB.programAddress;
const initialSqrtPrice = priceToSqrtPrice(initialPrice, decimalsA, decimalsB);
const [
poolAddress,
feeTier,
tokenBadgeA,
tokenBadgeB,
tokenVaultA,
tokenVaultB,
] = await Promise.all([
getWhirlpoolAddress(
WHIRLPOOLS_CONFIG_ADDRESS,
tokenMintA,
tokenMintB,
tickSpacing,
).then((x) => x[0]),
getFeeTierAddress(WHIRLPOOLS_CONFIG_ADDRESS, tickSpacing).then((x) => x[0]),
getTokenBadgeAddress(WHIRLPOOLS_CONFIG_ADDRESS, tokenMintA).then(
(x) => x[0],
),
getTokenBadgeAddress(WHIRLPOOLS_CONFIG_ADDRESS, tokenMintB).then(
(x) => x[0],
),
generateKeyPairSigner(),
generateKeyPairSigner(),
]);
instructions.push(
getInitializePoolV2Instruction({
whirlpoolsConfig: WHIRLPOOLS_CONFIG_ADDRESS,
tokenMintA,
tokenMintB,
tokenBadgeA,
tokenBadgeB,
funder,
whirlpool: poolAddress,
tokenVaultA,
tokenVaultB,
tokenProgramA,
tokenProgramB,
feeTier,
tickSpacing,
initialSqrtPrice,
}),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getTokenSizeForMint(mintA),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getTokenSizeForMint(mintB),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getWhirlpoolSize(),
);
const fullRange = getFullRangeTickIndexes(tickSpacing);
const lowerTickIndex = getTickArrayStartTickIndex(
fullRange.tickLowerIndex,
tickSpacing,
);
const upperTickIndex = getTickArrayStartTickIndex(
fullRange.tickUpperIndex,
tickSpacing,
);
const initialTickIndex = sqrtPriceToTickIndex(initialSqrtPrice);
const currentTickIndex = getTickArrayStartTickIndex(
initialTickIndex,
tickSpacing,
);
const tickArrayIndexes = Array.from(
new Set([lowerTickIndex, upperTickIndex, currentTickIndex]),
);
const tickArrayAddresses = await Promise.all(
tickArrayIndexes.map((x) =>
getTickArrayAddress(poolAddress, x).then((x) => x[0]),
),
);
for (let i = 0; i < tickArrayIndexes.length; i++) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: poolAddress,
funder,
tickArray: tickArrayAddresses[i],
startTickIndex: tickArrayIndexes[i],
}),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getTickArraySize(),
);
}
return {
instructions,
poolAddress,
initializationCost: lamports(nonRefundableRent),
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/position.ts
|
import type { Position, PositionBundle } from "@orca-so/whirlpools-client";
import {
fetchAllMaybePosition,
fetchAllMaybePositionBundle,
fetchAllPosition,
fetchAllPositionWithFilter,
getBundledPositionAddress,
getPositionAddress,
getPositionBundleAddress,
positionWhirlpoolFilter,
} from "@orca-so/whirlpools-client";
import { _POSITION_BUNDLE_SIZE } from "@orca-so/whirlpools-core";
import { getTokenDecoder, TOKEN_PROGRAM_ADDRESS } from "@solana-program/token";
import { TOKEN_2022_PROGRAM_ADDRESS } from "@solana-program/token-2022";
import type {
Account,
Address,
GetMultipleAccountsApi,
GetProgramAccountsApi,
GetTokenAccountsByOwnerApi,
Rpc,
} from "@solana/web3.js";
import { getBase64Encoder } from "@solana/web3.js";
/**
* Represents a Position account.
*/
export type HydratedPosition = Account<Position> & {
isPositionBundle: false;
};
/**
* Represents a Position Bundle account including its associated positions.
*/
export type HydratedPositionBundle = Account<PositionBundle> & {
positions: Account<Position>[];
isPositionBundle: true;
};
/**
* Represents either a Position or Position Bundle account.
*/
export type PositionOrBundle = HydratedPosition | HydratedPositionBundle;
/**
* Represents a decoded Position or Position Bundle account.
* Includes the token program address associated with the position.
*/
export type PositionData = PositionOrBundle & {
/** The token program associated with the position (either TOKEN_PROGRAM_ADDRESS or TOKEN_2022_PROGRAM_ADDRESS). */
tokenProgram: Address;
};
function getPositionInBundleAddresses(
positionBundle: PositionBundle,
): Promise<Address>[] {
const buffer = Buffer.from(positionBundle.positionBitmap);
const positions: Promise<Address>[] = [];
for (let i = 0; i < _POSITION_BUNDLE_SIZE(); i++) {
const byteIndex = Math.floor(i / 8);
const bitIndex = i % 8;
if (buffer[byteIndex] & (1 << bitIndex)) {
positions.push(
getBundledPositionAddress(positionBundle.positionBundleMint, i).then(
(x) => x[0],
),
);
}
}
return positions;
}
/**
* Fetches all positions owned by a given wallet in the Orca Whirlpools.
* It looks for token accounts owned by the wallet using both the TOKEN_PROGRAM_ADDRESS and TOKEN_2022_PROGRAM_ADDRESS.
* For token accounts holding exactly 1 token (indicating a position or bundle), it fetches the corresponding position addresses,
* decodes the accounts, and returns an array of position or bundle data.
*
* @param {SolanaRpc} rpc - The Solana RPC client used to fetch token accounts and multiple accounts.
* @param {Address} owner - The wallet address whose positions you want to fetch.
* @returns {Promise<PositionData[]>} - A promise that resolves to an array of decoded position data for the given owner.
*
* @example
* import { fetchPositionsForOwner } from '@orca-so/whirlpools';
* import { generateKeyPairSigner, createSolanaRpc, devnet } from '@solana/web3.js';
*
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = address("INSERT_WALLET_ADDRESS");
*
* const positions = await fetchPositionsForOwner(devnetRpc, wallet.address);
*/
export async function fetchPositionsForOwner(
rpc: Rpc<GetTokenAccountsByOwnerApi & GetMultipleAccountsApi>,
owner: Address,
): Promise<PositionData[]> {
const [tokenAccounts, token2022Accounts] = await Promise.all([
rpc
.getTokenAccountsByOwner(
owner,
{ programId: TOKEN_PROGRAM_ADDRESS },
{ encoding: "base64" },
)
.send(),
rpc
.getTokenAccountsByOwner(
owner,
{ programId: TOKEN_2022_PROGRAM_ADDRESS },
{ encoding: "base64" },
)
.send(),
]);
const encoder = getBase64Encoder();
const decoder = getTokenDecoder();
const potentialTokens = [...tokenAccounts.value, ...token2022Accounts.value]
.map((x) => ({
...decoder.decode(encoder.encode(x.account.data[0])),
tokenProgram: x.account.owner,
}))
.filter((x) => x.amount === 1n);
const positionAddresses = await Promise.all(
potentialTokens.map((x) => getPositionAddress(x.mint).then((x) => x[0])),
);
const positionBundleAddresses = await Promise.all(
potentialTokens.map((x) =>
getPositionBundleAddress(x.mint).then((x) => x[0]),
),
);
// FIXME: need to batch if more than 100 position bundles?
const [positions, positionBundles] = await Promise.all([
fetchAllMaybePosition(rpc, positionAddresses),
fetchAllMaybePositionBundle(rpc, positionBundleAddresses),
]);
const bundledPositionAddresses = await Promise.all(
positionBundles
.filter((x) => x.exists)
.flatMap((x) => getPositionInBundleAddresses(x.data)),
);
const bundledPositions = await fetchAllPosition(
rpc,
bundledPositionAddresses,
);
const bundledPositionMap = bundledPositions.reduce((acc, x) => {
const current = acc.get(x.data.positionMint) ?? [];
return acc.set(x.data.positionMint, [...current, x]);
}, new Map<Address, Account<Position>[]>());
const positionsOrBundles: PositionData[] = [];
for (let i = 0; i < potentialTokens.length; i++) {
const position = positions[i];
const positionBundle = positionBundles[i];
const token = potentialTokens[i];
if (position.exists) {
positionsOrBundles.push({
...position,
tokenProgram: token.tokenProgram,
isPositionBundle: false,
});
}
if (positionBundle.exists) {
const positions =
bundledPositionMap.get(positionBundle.data.positionBundleMint) ?? [];
positionsOrBundles.push({
...positionBundle,
positions,
tokenProgram: token.tokenProgram,
isPositionBundle: true,
});
}
}
return positionsOrBundles;
}
/**
* Fetches all positions for a given Whirlpool.
*
* @param {SolanaRpc} rpc - The Solana RPC client used to fetch positions.
* @param {Address} whirlpool - The address of the Whirlpool.
* @returns {Promise<HydratedPosition[]>} - A promise that resolves to an array of hydrated positions.
*
* @example
* import { fetchPositionsInWhirlpool } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
*
* const whirlpool = address("Czfq3xZZDmsdGdUyrNLtRhGc47cXcZtLG4crryfu44zE");
* const positions = await fetchPositionsInWhirlpool(devnetRpc, whirlpool);
*/
export async function fetchPositionsInWhirlpool(
rpc: Rpc<GetProgramAccountsApi>,
whirlpool: Address,
): Promise<HydratedPosition[]> {
const positions = await fetchAllPositionWithFilter(
rpc,
positionWhirlpoolFilter(whirlpool),
);
return positions.map((x) => ({
...x,
isPositionBundle: false,
}));
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/harvest.ts
|
import type {
CollectFeesQuote,
CollectRewardsQuote,
} from "@orca-so/whirlpools-core";
import {
collectFeesQuote,
collectRewardsQuote,
getTickArrayStartTickIndex,
getTickIndexInArray,
} from "@orca-so/whirlpools-core";
import type {
Rpc,
GetAccountInfoApi,
Address,
IInstruction,
TransactionSigner,
GetMultipleAccountsApi,
GetMinimumBalanceForRentExemptionApi,
GetEpochInfoApi,
} from "@solana/web3.js";
import { DEFAULT_ADDRESS, FUNDER } from "./config";
import {
fetchAllTickArray,
fetchPosition,
fetchWhirlpool,
getCollectFeesV2Instruction,
getCollectRewardV2Instruction,
getPositionAddress,
getTickArrayAddress,
getUpdateFeesAndRewardsInstruction,
} from "@orca-so/whirlpools-client";
import { findAssociatedTokenPda } from "@solana-program/token";
import {
getCurrentTransferFee,
prepareTokenAccountsInstructions,
} from "./token";
import { fetchAllMaybeMint } from "@solana-program/token-2022";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import assert from "assert";
// TODO: Transfer hook
/**
* Represents the instructions and quotes for harvesting a position.
*/
export type HarvestPositionInstructions = {
/** A breakdown of the fees owed to the position owner, detailing the amounts for token A (`fee_owed_a`) and token B (`fee_owed_b`). */
feesQuote: CollectFeesQuote;
/** A breakdown of the rewards owed, detailing up to three reward tokens (`reward_owed_1`, `reward_owed_2`, and `reward_owed_3`). */
rewardsQuote: CollectRewardsQuote;
/** A list of instructions required to harvest the position. */
instructions: IInstruction[];
};
/**
* This function creates a set of instructions that collect any accumulated fees and rewards from a position.
* The liquidity remains in place, and the position stays open.
*
* @param {SolanaRpc} rpc
* A Solana RPC client used to interact with the blockchain.
* @param {Address} positionMintAddress
* The position mint address you want to harvest fees and rewards from.
* @param {TransactionSigner} [authority=FUNDER]
* The account that authorizes the transaction. Defaults to a predefined funder.
*
* @returns {Promise<HarvestPositionInstructions>}
* A promise that resolves to an object containing the instructions, fees, and rewards quotes.
* @example
* import { harvestPositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
* import { loadWallet } from './utils';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await loadWallet();
* const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K");
*
* const { feesQuote, rewardsQuote, instructions } = await harvestPositionInstructions(
* devnetRpc,
* positionMint,
* wallet
* );
*
* console.log(`Fees owed token A: ${feesQuote.feeOwedA}`);
* console.log(`Rewards '1' owed: ${rewardsQuote.rewards[0].rewardsOwed}`);
*/
export async function harvestPositionInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
positionMintAddress: Address,
authority: TransactionSigner = FUNDER,
): Promise<HarvestPositionInstructions> {
assert(
authority.address !== DEFAULT_ADDRESS,
"Either supply an authority or set the default funder",
);
const currentEpoch = await rpc.getEpochInfo().send();
const positionAddress = await getPositionAddress(positionMintAddress);
const position = await fetchPosition(rpc, positionAddress[0]);
const whirlpool = await fetchWhirlpool(rpc, position.data.whirlpool);
const [mintA, mintB, positionMint, ...rewardMints] = await fetchAllMaybeMint(
rpc,
[
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
positionMintAddress,
...whirlpool.data.rewardInfos
.map((x) => x.mint)
.filter((x) => x !== DEFAULT_ADDRESS),
],
);
assert(mintA.exists, "Token A not found");
assert(mintB.exists, "Token B not found");
assert(positionMint.exists, "Position mint not found");
const lowerTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickLowerIndex,
whirlpool.data.tickSpacing,
);
const upperTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickUpperIndex,
whirlpool.data.tickSpacing,
);
const [positionTokenAccount, lowerTickArrayAddress, upperTickArrayAddress] =
await Promise.all([
findAssociatedTokenPda({
owner: authority.address,
mint: positionMintAddress,
tokenProgram: positionMint.programAddress,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool.address, lowerTickArrayStartIndex).then(
(x) => x[0],
),
getTickArrayAddress(whirlpool.address, upperTickArrayStartIndex).then(
(x) => x[0],
),
]);
const [lowerTickArray, upperTickArray] = await fetchAllTickArray(rpc, [
lowerTickArrayAddress,
upperTickArrayAddress,
]);
const lowerTick =
lowerTickArray.data.ticks[
getTickIndexInArray(
position.data.tickLowerIndex,
lowerTickArrayStartIndex,
whirlpool.data.tickSpacing,
)
];
const upperTick =
upperTickArray.data.ticks[
getTickIndexInArray(
position.data.tickUpperIndex,
upperTickArrayStartIndex,
whirlpool.data.tickSpacing,
)
];
const feesQuote = collectFeesQuote(
whirlpool.data,
position.data,
lowerTick,
upperTick,
getCurrentTransferFee(mintA, currentEpoch.epoch),
getCurrentTransferFee(mintB, currentEpoch.epoch),
);
const currentUnixTimestamp = BigInt(Math.floor(Date.now() / 1000));
const rewardsQuote = collectRewardsQuote(
whirlpool.data,
position.data,
lowerTick,
upperTick,
currentUnixTimestamp,
getCurrentTransferFee(rewardMints[0], currentEpoch.epoch),
getCurrentTransferFee(rewardMints[1], currentEpoch.epoch),
getCurrentTransferFee(rewardMints[2], currentEpoch.epoch),
);
const requiredMints: Set<Address> = new Set();
if (feesQuote.feeOwedA > 0n || feesQuote.feeOwedB > 0n) {
requiredMints.add(whirlpool.data.tokenMintA);
requiredMints.add(whirlpool.data.tokenMintB);
}
for (let i = 0; i < rewardsQuote.rewards.length; i++) {
if (rewardsQuote.rewards[i].rewardsOwed > 0n) {
requiredMints.add(whirlpool.data.rewardInfos[i].mint);
}
}
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(
rpc,
authority,
Array.from(requiredMints),
);
const instructions: IInstruction[] = [];
instructions.push(...createInstructions);
if (position.data.liquidity > 0n) {
instructions.push(
getUpdateFeesAndRewardsInstruction({
whirlpool: whirlpool.address,
position: positionAddress[0],
tickArrayLower: lowerTickArrayAddress,
tickArrayUpper: upperTickArrayAddress,
}),
);
}
if (feesQuote.feeOwedA > 0n || feesQuote.feeOwedB > 0n) {
instructions.push(
getCollectFeesV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
}
for (let i = 0; i < rewardsQuote.rewards.length; i++) {
if (rewardsQuote.rewards[i].rewardsOwed === 0n) {
continue;
}
const rewardMint = rewardMints[i];
assert(rewardMint.exists, `Reward mint ${i} not found`);
instructions.push(
getCollectRewardV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
rewardOwnerAccount: tokenAccountAddresses[rewardMint.address],
rewardVault: whirlpool.data.rewardInfos[i].vault,
rewardIndex: i,
rewardMint: rewardMint.address,
rewardTokenProgram: rewardMint.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
}
instructions.push(...cleanupInstructions);
return {
feesQuote,
rewardsQuote,
instructions,
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/decreaseLiquidity.ts
|
import type { Whirlpool } from "@orca-so/whirlpools-client";
import {
fetchAllTickArray,
fetchPosition,
fetchWhirlpool,
getClosePositionInstruction,
getClosePositionWithTokenExtensionsInstruction,
getCollectFeesV2Instruction,
getCollectRewardV2Instruction,
getDecreaseLiquidityV2Instruction,
getPositionAddress,
getTickArrayAddress,
} from "@orca-so/whirlpools-client";
import type {
CollectFeesQuote,
CollectRewardsQuote,
DecreaseLiquidityQuote,
TickRange,
TransferFee,
} from "@orca-so/whirlpools-core";
import {
_MAX_TICK_INDEX,
_MIN_TICK_INDEX,
getTickArrayStartTickIndex,
decreaseLiquidityQuote,
decreaseLiquidityQuoteA,
decreaseLiquidityQuoteB,
collectFeesQuote,
collectRewardsQuote,
getTickIndexInArray,
} from "@orca-so/whirlpools-core";
import type {
Address,
GetAccountInfoApi,
GetEpochInfoApi,
GetMinimumBalanceForRentExemptionApi,
GetMultipleAccountsApi,
IInstruction,
Rpc,
TransactionSigner,
} from "@solana/web3.js";
import { DEFAULT_ADDRESS, FUNDER, SLIPPAGE_TOLERANCE_BPS } from "./config";
import {
findAssociatedTokenPda,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import {
getCurrentTransferFee,
prepareTokenAccountsInstructions,
} from "./token";
import {
fetchAllMint,
fetchAllMaybeMint,
TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import assert from "assert";
// TODO: allow specify number as well as bigint
// TODO: transfer hook
/**
* Represents the parameters for decreasing liquidity.
* You must choose only one of the properties (`liquidity`, `tokenA`, or `tokenB`).
* The SDK will compute the other two based on the input provided.
*/
export type DecreaseLiquidityQuoteParam =
| {
/** The amount of liquidity to decrease.*/
liquidity: bigint;
}
| {
/** The amount of Token A to withdraw.*/
tokenA: bigint;
}
| {
/** The amount of Token B to withdraw.*/
tokenB: bigint;
};
/**
* Represents the instructions and quote for decreasing liquidity in a position.
*/
export type DecreaseLiquidityInstructions = {
/** The quote details for decreasing liquidity, including the liquidity delta, estimated tokens, and minimum token amounts based on slippage tolerance. */
quote: DecreaseLiquidityQuote;
/** The list of instructions required to decrease liquidity. */
instructions: IInstruction[];
};
function getDecreaseLiquidityQuote(
param: DecreaseLiquidityQuoteParam,
pool: Whirlpool,
tickRange: TickRange,
slippageToleranceBps: number,
transferFeeA: TransferFee | undefined,
transferFeeB: TransferFee | undefined,
): DecreaseLiquidityQuote {
if ("liquidity" in param) {
return decreaseLiquidityQuote(
param.liquidity,
slippageToleranceBps,
pool.sqrtPrice,
tickRange.tickLowerIndex,
tickRange.tickUpperIndex,
transferFeeA,
transferFeeB,
);
} else if ("tokenA" in param) {
return decreaseLiquidityQuoteA(
param.tokenA,
slippageToleranceBps,
pool.sqrtPrice,
tickRange.tickLowerIndex,
tickRange.tickUpperIndex,
transferFeeA,
transferFeeB,
);
} else {
return decreaseLiquidityQuoteB(
param.tokenB,
slippageToleranceBps,
pool.sqrtPrice,
tickRange.tickLowerIndex,
tickRange.tickUpperIndex,
transferFeeA,
transferFeeB,
);
}
}
/**
* Generates instructions to decrease liquidity from an existing position in an Orca Whirlpool.
*
* @param {SolanaRpc} rpc - A Solana RPC client for fetching necessary accounts and pool data.
* @param {Address} positionMintAddress - The mint address of the NFT that represents ownership of the position from which liquidity will be removed.
* @param {DecreaseLiquidityQuoteParam} param - Defines the liquidity removal method (liquidity, tokenA, or tokenB).
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The acceptable slippage tolerance in basis points.
* @param {TransactionSigner} [authority=FUNDER] - The account authorizing the liquidity removal.
*
* @returns {Promise<DecreaseLiquidityInstructions>} A promise resolving to an object containing the decrease liquidity quote and instructions.
*
* @example
* import { decreaseLiquidityInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
* import { loadWallet } from './utils';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await loadWallet();
* const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K");
* const param = { tokenA: 10n };
* const { quote, instructions } = await decreaseLiquidityInstructions(
* devnetRpc,
* positionMint,
* param,
* 100,
* wallet
* );
*
* console.log(`Quote token max B: ${quote.tokenEstB}`);
*/
export async function decreaseLiquidityInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
positionMintAddress: Address,
param: DecreaseLiquidityQuoteParam,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
authority: TransactionSigner = FUNDER,
): Promise<DecreaseLiquidityInstructions> {
assert(
authority.address !== DEFAULT_ADDRESS,
"Either supply the authority or set the default funder",
);
const positionAddress = await getPositionAddress(positionMintAddress);
const position = await fetchPosition(rpc, positionAddress[0]);
const whirlpool = await fetchWhirlpool(rpc, position.data.whirlpool);
const currentEpoch = await rpc.getEpochInfo().send();
const [mintA, mintB, positionMint] = await fetchAllMint(rpc, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
positionMintAddress,
]);
const transferFeeA = getCurrentTransferFee(mintA, currentEpoch.epoch);
const transferFeeB = getCurrentTransferFee(mintB, currentEpoch.epoch);
const quote = getDecreaseLiquidityQuote(
param,
whirlpool.data,
position.data,
slippageToleranceBps,
transferFeeA,
transferFeeB,
);
const instructions: IInstruction[] = [];
const lowerTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickLowerIndex,
whirlpool.data.tickSpacing,
);
const upperTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickUpperIndex,
whirlpool.data.tickSpacing,
);
const [positionTokenAccount, tickArrayLower, tickArrayUpper] =
await Promise.all([
findAssociatedTokenPda({
owner: authority.address,
mint: positionMintAddress,
tokenProgram: positionMint.programAddress,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool.address, lowerTickArrayStartIndex).then(
(x) => x[0],
),
getTickArrayAddress(whirlpool.address, upperTickArrayStartIndex).then(
(x) => x[0],
),
]);
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(rpc, authority, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
]);
instructions.push(...createInstructions);
instructions.push(
getDecreaseLiquidityV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: position.address,
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
tickArrayLower,
tickArrayUpper,
liquidityAmount: quote.liquidityDelta,
tokenMinA: quote.tokenMinA,
tokenMinB: quote.tokenMinB,
remainingAccountsInfo: null,
}),
);
instructions.push(...cleanupInstructions);
return { quote, instructions };
}
/**
* Represents the instructions and quotes for closing a liquidity position in an Orca Whirlpool.
* Extends `DecreaseLiquidityInstructions` and adds additional fee and reward details.
*/
export type ClosePositionInstructions = DecreaseLiquidityInstructions & {
/** The fees collected from the position, including the amounts for token A (`fee_owed_a`) and token B (`fee_owed_b`). */
feesQuote: CollectFeesQuote;
/** The rewards collected from the position, including up to three reward tokens (`reward_owed_1`, `reward_owed_2`, and `reward_owed_3`). */
rewardsQuote: CollectRewardsQuote;
};
/**
* Generates instructions to close a liquidity position in an Orca Whirlpool. This includes collecting all fees,
* rewards, removing any remaining liquidity, and closing the position.
*
* @param {SolanaRpc} rpc - A Solana RPC client for fetching accounts and pool data.
* @param {Address} positionMintAddress - The mint address of the NFT that represents ownership of the position to be closed.
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The acceptable slippage tolerance in basis points.
* @param {TransactionSigner} [authority=FUNDER] - The account authorizing the transaction.
*
* @returns {Promise<ClosePositionInstructions>} A promise resolving to an object containing instructions, fees quote, rewards quote, and the liquidity quote for the closed position.
*
* @example
* import { closePositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
* import { loadWallet } from './utils';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await loadWallet();
* const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K");
*
* const { instructions, quote, feesQuote, rewardsQuote } = await closePositionInstructions(
* devnetRpc,
* positionMint,
* 100,
* wallet
* );
*
* console.log(`Quote token max B: ${quote.tokenEstB}`);
* console.log(`Fees owed token A: ${feesQuote.feeOwedA}`);
* console.log(`Rewards '1' owed: ${rewardsQuote.rewards[0].rewardsOwed}`);
* console.log(`Number of instructions:, ${instructions.length}`);
*/
export async function closePositionInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
positionMintAddress: Address,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
authority: TransactionSigner = FUNDER,
): Promise<ClosePositionInstructions> {
assert(
authority.address !== DEFAULT_ADDRESS,
"Either supply an authority or set the default funder",
);
const positionAddress = await getPositionAddress(positionMintAddress);
const position = await fetchPosition(rpc, positionAddress[0]);
const whirlpool = await fetchWhirlpool(rpc, position.data.whirlpool);
const currentEpoch = await rpc.getEpochInfo().send();
const [mintA, mintB, positionMint, ...rewardMints] = await fetchAllMaybeMint(
rpc,
[
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
positionMintAddress,
...whirlpool.data.rewardInfos
.map((x) => x.mint)
.filter((x) => x !== DEFAULT_ADDRESS),
],
);
assert(mintA.exists, "Token A not found");
assert(mintB.exists, "Token B not found");
assert(positionMint.exists, "Position mint not found");
const transferFeeA = getCurrentTransferFee(mintA, currentEpoch.epoch);
const transferFeeB = getCurrentTransferFee(mintB, currentEpoch.epoch);
const quote = getDecreaseLiquidityQuote(
{ liquidity: position.data.liquidity },
whirlpool.data,
position.data,
slippageToleranceBps,
transferFeeA,
transferFeeB,
);
const lowerTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickLowerIndex,
whirlpool.data.tickSpacing,
);
const upperTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickUpperIndex,
whirlpool.data.tickSpacing,
);
const [positionTokenAccount, lowerTickArrayAddress, upperTickArrayAddress] =
await Promise.all([
findAssociatedTokenPda({
owner: authority.address,
mint: positionMintAddress,
tokenProgram: positionMint.programAddress,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool.address, lowerTickArrayStartIndex).then(
(x) => x[0],
),
getTickArrayAddress(whirlpool.address, upperTickArrayStartIndex).then(
(x) => x[0],
),
]);
const [lowerTickArray, upperTickArray] = await fetchAllTickArray(rpc, [
lowerTickArrayAddress,
upperTickArrayAddress,
]);
const lowerTick =
lowerTickArray.data.ticks[
getTickIndexInArray(
position.data.tickLowerIndex,
lowerTickArrayStartIndex,
whirlpool.data.tickSpacing,
)
];
const upperTick =
upperTickArray.data.ticks[
getTickIndexInArray(
position.data.tickUpperIndex,
upperTickArrayStartIndex,
whirlpool.data.tickSpacing,
)
];
const feesQuote = collectFeesQuote(
whirlpool.data,
position.data,
lowerTick,
upperTick,
transferFeeA,
transferFeeB,
);
const currentUnixTimestamp = BigInt(Math.floor(Date.now() / 1000));
const rewardsQuote = collectRewardsQuote(
whirlpool.data,
position.data,
lowerTick,
upperTick,
currentUnixTimestamp,
getCurrentTransferFee(rewardMints[0], currentEpoch.epoch),
getCurrentTransferFee(rewardMints[1], currentEpoch.epoch),
getCurrentTransferFee(rewardMints[2], currentEpoch.epoch),
);
const requiredMints: Set<Address> = new Set();
if (
quote.liquidityDelta > 0n ||
feesQuote.feeOwedA > 0n ||
feesQuote.feeOwedB > 0n
) {
requiredMints.add(whirlpool.data.tokenMintA);
requiredMints.add(whirlpool.data.tokenMintB);
}
for (let i = 0; i < rewardsQuote.rewards.length; i++) {
if (rewardsQuote.rewards[i].rewardsOwed > 0n) {
requiredMints.add(whirlpool.data.rewardInfos[i].mint);
}
}
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(
rpc,
authority,
Array.from(requiredMints),
);
const instructions: IInstruction[] = [];
instructions.push(...createInstructions);
if (quote.liquidityDelta > 0n) {
instructions.push(
getDecreaseLiquidityV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tickArrayLower: lowerTickArrayAddress,
tickArrayUpper: upperTickArrayAddress,
liquidityAmount: quote.liquidityDelta,
tokenMinA: quote.tokenMinA,
tokenMinB: quote.tokenMinB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
}
if (feesQuote.feeOwedA > 0n || feesQuote.feeOwedB > 0n) {
instructions.push(
getCollectFeesV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
}
for (let i = 0; i < rewardsQuote.rewards.length; i++) {
if (rewardsQuote.rewards[i].rewardsOwed === 0n) {
continue;
}
const rewardMint = rewardMints[i];
assert(rewardMint.exists, `Reward mint ${i} not found`);
instructions.push(
getCollectRewardV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
rewardOwnerAccount: tokenAccountAddresses[rewardMint.address],
rewardVault: whirlpool.data.rewardInfos[i].vault,
rewardIndex: i,
rewardMint: rewardMint.address,
rewardTokenProgram: rewardMint.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
}
switch (positionMint.programAddress) {
case TOKEN_PROGRAM_ADDRESS:
instructions.push(
getClosePositionInstruction({
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
positionMint: positionMintAddress,
receiver: authority.address,
}),
);
break;
case TOKEN_2022_PROGRAM_ADDRESS:
instructions.push(
getClosePositionWithTokenExtensionsInstruction({
positionAuthority: authority,
position: positionAddress[0],
positionTokenAccount,
positionMint: positionMintAddress,
receiver: authority.address,
token2022Program: TOKEN_2022_PROGRAM_ADDRESS,
}),
);
break;
default:
throw new Error("Invalid token program");
}
instructions.push(...cleanupInstructions);
return {
instructions,
quote,
feesQuote,
rewardsQuote,
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/swap.ts
|
import type {
Account,
Address,
GetAccountInfoApi,
GetEpochInfoApi,
GetMinimumBalanceForRentExemptionApi,
GetMultipleAccountsApi,
IInstruction,
Rpc,
TransactionSigner,
} from "@solana/web3.js";
import { AccountRole, lamports } from "@solana/web3.js";
import { FUNDER, SLIPPAGE_TOLERANCE_BPS } from "./config";
import type {
ExactInSwapQuote,
ExactOutSwapQuote,
TickArrayFacade,
TransferFee,
} from "@orca-so/whirlpools-core";
import {
_TICK_ARRAY_SIZE,
getTickArrayStartTickIndex,
swapQuoteByInputToken,
swapQuoteByOutputToken,
} from "@orca-so/whirlpools-core";
import type { Whirlpool } from "@orca-so/whirlpools-client";
import {
AccountsType,
fetchAllMaybeTickArray,
fetchWhirlpool,
getOracleAddress,
getSwapV2Instruction,
getTickArrayAddress,
} from "@orca-so/whirlpools-client";
import {
getCurrentTransferFee,
prepareTokenAccountsInstructions,
} from "./token";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import { fetchAllMint } from "@solana-program/token-2022";
// TODO: allow specify number as well as bigint
// TODO: transfer hook
/**
* Parameters for an exact input swap.
*/
export type ExactInParams = {
/** The exact amount of input tokens to be swapped. */
inputAmount: bigint;
};
/**
* Parameters for an exact output swap.
*/
export type ExactOutParams = {
/** The exact amount of output tokens to be received from the swap. */
outputAmount: bigint;
};
/**
* Swap parameters, either for an exact input or exact output swap.
*/
export type SwapParams = (ExactInParams | ExactOutParams) & {
/** The mint address of the token being swapped. */
mint: Address;
};
/**
* Swap quote that corresponds to the type of swap being executed (either input or output swap).
*
* @template T - The type of swap (input or output).
*/
export type SwapQuote<T extends SwapParams> = T extends ExactInParams
? ExactInSwapQuote
: ExactOutSwapQuote;
/**
* Instructions and quote for executing a swap.
*
* @template T - The type of swap (input or output).
*/
export type SwapInstructions<T extends SwapParams> = {
/** The list of instructions needed to perform the swap. */
instructions: IInstruction[];
/** The swap quote, which includes information about the amounts involved in the swap. */
quote: SwapQuote<T>;
};
function createUninitializedTickArray(
address: Address,
startTickIndex: number,
programAddress: Address,
): Account<TickArrayFacade> {
return {
address,
data: {
startTickIndex,
ticks: Array(_TICK_ARRAY_SIZE()).fill({
initialized: false,
liquidityNet: 0n,
liquidityGross: 0n,
feeGrowthOutsideA: 0n,
feeGrowthOutsideB: 0n,
rewardGrowthsOutside: [0n, 0n, 0n],
}),
},
executable: false,
lamports: lamports(0n),
programAddress,
};
}
async function fetchTickArrayOrDefault(
rpc: Rpc<GetMultipleAccountsApi>,
whirlpool: Account<Whirlpool>,
): Promise<Account<TickArrayFacade>[]> {
const tickArrayStartIndex = getTickArrayStartTickIndex(
whirlpool.data.tickCurrentIndex,
whirlpool.data.tickSpacing,
);
const offset = whirlpool.data.tickSpacing * _TICK_ARRAY_SIZE();
const tickArrayIndexes = [
tickArrayStartIndex,
tickArrayStartIndex + offset,
tickArrayStartIndex + offset * 2,
tickArrayStartIndex - offset,
tickArrayStartIndex - offset * 2,
];
const tickArrayAddresses = await Promise.all(
tickArrayIndexes.map((startIndex) =>
getTickArrayAddress(whirlpool.address, startIndex).then((x) => x[0]),
),
);
const maybeTickArrays = await fetchAllMaybeTickArray(rpc, tickArrayAddresses);
const tickArrays: Account<TickArrayFacade>[] = [];
for (let i = 0; i < maybeTickArrays.length; i++) {
const maybeTickArray = maybeTickArrays[i];
if (maybeTickArray.exists) {
tickArrays.push(maybeTickArray);
} else {
tickArrays.push(
createUninitializedTickArray(
tickArrayAddresses[i],
tickArrayIndexes[i],
whirlpool.programAddress,
),
);
}
}
return tickArrays;
}
function getSwapQuote<T extends SwapParams>(
params: T,
whirlpool: Whirlpool,
transferFeeA: TransferFee | undefined,
transferFeeB: TransferFee | undefined,
tickArrays: TickArrayFacade[],
specifiedTokenA: boolean,
slippageToleranceBps: number,
): SwapQuote<T> {
if ("inputAmount" in params) {
return swapQuoteByInputToken(
params.inputAmount,
specifiedTokenA,
slippageToleranceBps,
whirlpool,
tickArrays,
transferFeeA,
transferFeeB,
) as SwapQuote<T>;
}
return swapQuoteByOutputToken(
params.outputAmount,
specifiedTokenA,
slippageToleranceBps,
whirlpool,
tickArrays,
transferFeeA,
transferFeeB,
) as SwapQuote<T>;
}
/**
* Generates the instructions necessary to execute a token swap in an Orca Whirlpool.
* It handles both exact input and exact output swaps, fetching the required accounts, tick arrays, and determining the swap quote.
*
* @template T - The type of swap (exact input or output).
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {T} params - The swap parameters, specifying either the input or output amount and the mint address of the token being swapped.
* @param {Address} poolAddress - The address of the Whirlpool against which the swap will be made.
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The maximum acceptable slippage tolerance for the swap, in basis points (BPS).
* @param {TransactionSigner} [signer=FUNDER] - The wallet or signer executing the swap.
* @returns {Promise<SwapInstructions<T>>} - A promise that resolves to an object containing the swap instructions and the swap quote.
*
* @example
* import { setWhirlpoolsConfig, swapInstructions } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
* import { loadWallet } from './utils';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await loadWallet(); // CAUTION: This wallet is not persistent.
* const whirlpoolAddress = address("3KBZiL2g8C7tiJ32hTv5v3KM7aK9htpqTw4cTXz1HvPt");
* const mintAddress = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k");
* const inputAmount = 1_000_000n;
*
* const { instructions, quote } = await swapInstructions(
* devnetRpc,
* { inputAmount, mint: mintAddress },
* whirlpoolAddress,
* 100,
* wallet
* );
*
* console.log(`Quote estimated token out: ${quote.tokenEstOut}`);
* console.log(`Number of instructions:, ${instructions.length}`);
*/
export async function swapInstructions<T extends SwapParams>(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
params: T,
poolAddress: Address,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
signer: TransactionSigner = FUNDER,
): Promise<SwapInstructions<T>> {
const whirlpool = await fetchWhirlpool(rpc, poolAddress);
const [tokenA, tokenB] = await fetchAllMint(rpc, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
]);
const specifiedTokenA = params.mint === whirlpool.data.tokenMintA;
const specifiedInput = "inputAmount" in params;
const tickArrays = await fetchTickArrayOrDefault(rpc, whirlpool);
const oracleAddress = await getOracleAddress(whirlpool.address).then(
(x) => x[0],
);
const currentEpoch = await rpc.getEpochInfo().send();
const transferFeeA = getCurrentTransferFee(tokenA, currentEpoch.epoch);
const transferFeeB = getCurrentTransferFee(tokenB, currentEpoch.epoch);
const quote = getSwapQuote<T>(
params,
whirlpool.data,
transferFeeA,
transferFeeB,
tickArrays.map((x) => x.data),
specifiedTokenA,
slippageToleranceBps,
);
const maxInAmount = "tokenIn" in quote ? quote.tokenIn : quote.tokenMaxIn;
const aToB = specifiedTokenA === specifiedInput;
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(rpc, signer, {
[whirlpool.data.tokenMintA]: aToB ? maxInAmount : 0n,
[whirlpool.data.tokenMintB]: aToB ? 0n : maxInAmount,
});
const instructions: IInstruction[] = [];
instructions.push(...createInstructions);
const specifiedAmount =
"inputAmount" in params ? params.inputAmount : params.outputAmount;
const otherAmountThreshold =
"tokenMaxIn" in quote ? quote.tokenMaxIn : quote.tokenMinOut;
const swapInstruction = getSwapV2Instruction({
tokenProgramA: tokenA.programAddress,
tokenProgramB: tokenB.programAddress,
memoProgram: MEMO_PROGRAM_ADDRESS,
tokenAuthority: signer,
whirlpool: whirlpool.address,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tickArray0: tickArrays[0].address,
tickArray1: tickArrays[1].address,
tickArray2: tickArrays[2].address,
amount: specifiedAmount,
otherAmountThreshold,
sqrtPriceLimit: 0,
amountSpecifiedIsInput: specifiedInput,
aToB,
oracle: oracleAddress,
remainingAccountsInfo: {
slices: [
{ accountsType: AccountsType.SupplementalTickArrays, length: 2 },
],
},
});
swapInstruction.accounts.push(
{ address: tickArrays[3].address, role: AccountRole.WRITABLE },
{ address: tickArrays[4].address, role: AccountRole.WRITABLE },
);
instructions.push(swapInstruction);
instructions.push(...cleanupInstructions);
return {
quote,
instructions,
};
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/index.ts
|
export * from "./config";
export * from "./createPool";
export * from "./decreaseLiquidity";
export * from "./harvest";
export * from "./increaseLiquidity";
export * from "./pool";
export * from "./position";
export * from "./swap";
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/config.ts
|
import { getWhirlpoolsConfigExtensionAddress } from "@orca-so/whirlpools-client";
import type { Address, TransactionSigner } from "@solana/web3.js";
import { address, createNoopSigner, isAddress } from "@solana/web3.js";
/**
* The default (null) address.
*/
export const DEFAULT_ADDRESS = address("11111111111111111111111111111111");
/**
* The WhirlpoolsConfig addresses for various networks.
*/
export const DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES = {
solanaMainnet: address("2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ"),
solanaDevnet: address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR"),
eclipseMainnet: address("FVG4oDbGv16hqTUbovjyGmtYikn6UBEnazz6RVDMEFwv"),
eclipseTestnet: address("FPydDjRdZu9sT7HVd6ANhfjh85KLq21Pefr5YWWMRPFp"),
};
/**
* The default WhirlpoolsConfigExtension address.
*/
export const DEFAULT_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS = address(
"777H5H3Tp9U11uRVRzFwM8BinfiakbaLT8vQpeuhvEiH",
);
/**
* The WhirlpoolsConfig address.
*/
export let WHIRLPOOLS_CONFIG_ADDRESS: Address =
DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES.solanaMainnet;
/**
* The WhirlpoolsConfigExtension address.
*/
export let WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS: Address =
DEFAULT_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS;
/**
* Updates the WhirlpoolsConfig and WhirlpoolsConfigExtension addresses.
*
* @param {Address | keyof typeof NETWORK_ADDRESSES} config - A WhirlpoolsConfig address or a network name.
* @returns {Promise<void>} - Resolves when the addresses have been updated.
*/
export async function setWhirlpoolsConfig(
config: Address | keyof typeof DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES,
): Promise<void> {
if (isAddress(config)) {
WHIRLPOOLS_CONFIG_ADDRESS = config;
} else {
WHIRLPOOLS_CONFIG_ADDRESS =
DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES[
config as keyof typeof DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES
];
}
WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS =
await getWhirlpoolsConfigExtensionAddress(WHIRLPOOLS_CONFIG_ADDRESS).then(
(x) => x[0],
);
}
/**
* The tick spacing for the Splash pools.
*/
export const SPLASH_POOL_TICK_SPACING = 32896;
/**
* The default funder for transactions. No explicit funder specified.
*/
export const DEFAULT_FUNDER: TransactionSigner =
createNoopSigner(DEFAULT_ADDRESS);
/**
* The currently selected funder for transactions.
*/
export let FUNDER: TransactionSigner = DEFAULT_FUNDER;
/**
* Sets the default funder for transactions.
*
* @param {TransactionSigner | Address | null} funder - The funder to be set as default, either as an address or a transaction signer.
*/
export function setDefaultFunder(
funder: TransactionSigner | Address | null,
): void {
if (typeof funder === "string") {
FUNDER = createNoopSigner(funder);
} else {
FUNDER = funder ?? createNoopSigner(DEFAULT_ADDRESS);
}
}
/**
* The default slippage tolerance, expressed in basis points. Value of 100 is equivalent to 1%.
*/
export const DEFAULT_SLIPPAGE_TOLERANCE_BPS = 100;
/**
* The currently selected slippage tolerance, expressed in basis points. Value of 100 is equivalent to 1%.
*/
export let SLIPPAGE_TOLERANCE_BPS = DEFAULT_SLIPPAGE_TOLERANCE_BPS;
/**
* Sets the default slippage tolerance for transactions.
*
* @param {number} slippageToleranceBps - The slippage tolerance, expressed basis points. Value of 100 is equivalent to 1%.
*/
export function setDefaultSlippageToleranceBps(
slippageToleranceBps: number,
): void {
SLIPPAGE_TOLERANCE_BPS = Math.floor(slippageToleranceBps);
}
/**
* Defines the strategy for handling Native Mint wrapping in a transaction.
*
* - **Keypair**:
* Creates an auxiliary token account using a keypair.
* Optionally adds funds to the account.
* Closes it at the end of the transaction.
*
* - **Seed**:
* Functions similarly to Keypair, but uses a seed account instead.
*
* - **ATA**:
* Treats the native balance and associated token account (ATA) for `NATIVE_MINT` as one.
* Will create the ATA if it doesn't exist.
* Optionally adds funds to the account.
* Closes it at the end of the transaction if it did not exist before.
*
* - **None**:
* Uses or creates the ATA without performing any Native Mint wrapping or unwrapping.
*/
export type NativeMintWrappingStrategy = "keypair" | "seed" | "ata" | "none";
/**
* The default native mint wrapping strategy.
*/
export const DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY: NativeMintWrappingStrategy =
"keypair";
/**
* The currently selected native mint wrapping strategy.
*/
export let NATIVE_MINT_WRAPPING_STRATEGY: NativeMintWrappingStrategy =
DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY;
/**
* Sets the native mint wrapping strategy.
*
* @param {NativeMintWrappingStrategy} strategy - The native mint wrapping strategy.
*/
export function setNativeMintWrappingStrategy(
strategy: NativeMintWrappingStrategy,
): void {
NATIVE_MINT_WRAPPING_STRATEGY = strategy;
}
/**
* Resets the configuration to its default state.
*
* @returns {Promise<void>} - Resolves when the configuration has been reset.
*/
export function resetConfiguration() {
WHIRLPOOLS_CONFIG_ADDRESS = DEFAULT_WHIRLPOOLS_CONFIG_ADDRESSES.solanaMainnet;
WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS =
DEFAULT_WHIRLPOOLS_CONFIG_EXTENSION_ADDRESS;
FUNDER = DEFAULT_FUNDER;
SLIPPAGE_TOLERANCE_BPS = DEFAULT_SLIPPAGE_TOLERANCE_BPS;
NATIVE_MINT_WRAPPING_STRATEGY = DEFAULT_NATIVE_MINT_WRAPPING_STRATEGY;
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/increaseLiquidity.ts
|
import type { Whirlpool } from "@orca-so/whirlpools-client";
import {
fetchAllMaybeTickArray,
fetchPosition,
fetchWhirlpool,
getIncreaseLiquidityV2Instruction,
getInitializeTickArrayInstruction,
getOpenPositionWithTokenExtensionsInstruction,
getPositionAddress,
getTickArrayAddress,
getTickArraySize,
} from "@orca-so/whirlpools-client";
import type {
IncreaseLiquidityQuote,
TransferFee,
} from "@orca-so/whirlpools-core";
import {
_MAX_TICK_INDEX,
_MIN_TICK_INDEX,
getFullRangeTickIndexes,
getTickArrayStartTickIndex,
increaseLiquidityQuote,
increaseLiquidityQuoteA,
increaseLiquidityQuoteB,
priceToTickIndex,
getInitializableTickIndex,
orderTickIndexes,
} from "@orca-so/whirlpools-core";
import type {
Account,
Address,
GetAccountInfoApi,
GetEpochInfoApi,
GetMinimumBalanceForRentExemptionApi,
GetMultipleAccountsApi,
IInstruction,
Lamports,
Rpc,
TransactionSigner,
} from "@solana/web3.js";
import { address, generateKeyPairSigner, lamports } from "@solana/web3.js";
import { fetchSysvarRent } from "@solana/sysvars";
import {
DEFAULT_ADDRESS,
FUNDER,
SLIPPAGE_TOLERANCE_BPS,
SPLASH_POOL_TICK_SPACING,
} from "./config";
import {
ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
findAssociatedTokenPda,
} from "@solana-program/token";
import {
getCurrentTransferFee,
prepareTokenAccountsInstructions,
} from "./token";
import type { Mint } from "@solana-program/token-2022";
import {
fetchAllMint,
TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import assert from "assert";
import { calculateMinimumBalanceForRentExemption } from "./sysvar";
// TODO: allow specify number as well as bigint
// TODO: transfer hook
/**
* Represents the parameters for increasing liquidity.
* You must choose only one of the properties (`liquidity`, `tokenA`, or `tokenB`).
* The SDK will compute the other two based on the input provided.
*/
export type IncreaseLiquidityQuoteParam =
| {
/** The amount of liquidity to increase. */
liquidity: bigint;
}
| {
/** The amount of Token A to add. */
tokenA: bigint;
}
| {
/** The amount of Token B to add. */
tokenB: bigint;
};
/**
* Represents the instructions and quote for increasing liquidity in a position.
*/
export type IncreaseLiquidityInstructions = {
/** The quote object with details about the increase in liquidity, including the liquidity delta, estimated tokens, and maximum token amounts based on slippage tolerance. */
quote: IncreaseLiquidityQuote;
/** List of Solana transaction instructions to execute. */
instructions: IInstruction[];
};
function getIncreaseLiquidityQuote(
param: IncreaseLiquidityQuoteParam,
pool: Whirlpool,
tickLowerIndex: number,
tickUpperIndex: number,
slippageToleranceBps: number,
transferFeeA: TransferFee | undefined,
transferFeeB: TransferFee | undefined,
): IncreaseLiquidityQuote {
if ("liquidity" in param) {
return increaseLiquidityQuote(
param.liquidity,
slippageToleranceBps,
pool.sqrtPrice,
tickLowerIndex,
tickUpperIndex,
transferFeeA,
transferFeeB,
);
} else if ("tokenA" in param) {
return increaseLiquidityQuoteA(
param.tokenA,
slippageToleranceBps,
pool.sqrtPrice,
tickLowerIndex,
tickUpperIndex,
transferFeeA,
transferFeeB,
);
} else {
return increaseLiquidityQuoteB(
param.tokenB,
slippageToleranceBps,
pool.sqrtPrice,
tickLowerIndex,
tickUpperIndex,
transferFeeA,
transferFeeB,
);
}
}
/**
* Generates instructions to increase liquidity for an existing position.
*
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {Address} positionMintAddress - The mint address of the NFT that represents the position.
* @param {IncreaseLiquidityQuoteParam} param - The parameters for adding liquidity. Can specify liquidity, Token A, or Token B amounts.
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The maximum acceptable slippage, in basis points (BPS).
* @param {TransactionSigner} [authority=FUNDER] - The account that authorizes the transaction.
* @returns {Promise<IncreaseLiquidityInstructions>} A promise that resolves to an object containing instructions, quote, position mint address, and initialization costs for increasing liquidity.
*
* @example
* import { increaseLiquidityInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { createSolanaRpc, devnet, address } from '@solana/web3.js';
* import { loadWallet } from './utils';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await loadWallet();
* const positionMint = address("HqoV7Qv27REUtmd9UKSJGGmCRNx3531t33bDG1BUfo9K");
* const param = { tokenA: 10n };
* const { quote, instructions } = await increaseLiquidityInstructions(
* devnetRpc,
* positionMint,
* param,
* 100,
* wallet
* );
*
* console.log(`Quote token max B: ${quote.tokenEstB}`);
*/
export async function increaseLiquidityInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
positionMintAddress: Address,
param: IncreaseLiquidityQuoteParam,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
authority: TransactionSigner = FUNDER,
): Promise<IncreaseLiquidityInstructions> {
assert(
authority.address !== DEFAULT_ADDRESS,
"Either supply the authority or set the default funder",
);
const positionAddress = await getPositionAddress(positionMintAddress);
const position = await fetchPosition(rpc, positionAddress[0]);
const whirlpool = await fetchWhirlpool(rpc, position.data.whirlpool);
const currentEpoch = await rpc.getEpochInfo().send();
const [mintA, mintB, positionMint] = await fetchAllMint(rpc, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
positionMintAddress,
]);
const transferFeeA = getCurrentTransferFee(mintA, currentEpoch.epoch);
const transferFeeB = getCurrentTransferFee(mintB, currentEpoch.epoch);
const quote = getIncreaseLiquidityQuote(
param,
whirlpool.data,
position.data.tickLowerIndex,
position.data.tickUpperIndex,
slippageToleranceBps,
transferFeeA,
transferFeeB,
);
const instructions: IInstruction[] = [];
const lowerTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickLowerIndex,
whirlpool.data.tickSpacing,
);
const upperTickArrayStartIndex = getTickArrayStartTickIndex(
position.data.tickUpperIndex,
whirlpool.data.tickSpacing,
);
const [positionTokenAccount, tickArrayLower, tickArrayUpper] =
await Promise.all([
findAssociatedTokenPda({
owner: authority.address,
mint: positionMintAddress,
tokenProgram: positionMint.programAddress,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool.address, lowerTickArrayStartIndex).then(
(x) => x[0],
),
getTickArrayAddress(whirlpool.address, upperTickArrayStartIndex).then(
(x) => x[0],
),
]);
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(rpc, authority, {
[whirlpool.data.tokenMintA]: quote.tokenMaxA,
[whirlpool.data.tokenMintB]: quote.tokenMaxB,
});
instructions.push(...createInstructions);
// Since position exists tick arrays must also already exist
instructions.push(
getIncreaseLiquidityV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: authority,
position: position.address,
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
tickArrayLower,
tickArrayUpper,
liquidityAmount: quote.liquidityDelta,
tokenMaxA: quote.tokenMaxA,
tokenMaxB: quote.tokenMaxB,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
instructions.push(...cleanupInstructions);
return {
quote,
instructions,
};
}
/**
* Represents the instructions and quote for opening a position.
* Extends IncreaseLiquidityInstructions with additional fields for position initialization.
*/
export type OpenPositionInstructions = IncreaseLiquidityInstructions & {
/** The initialization cost for opening the position in lamports. */
initializationCost: Lamports;
/** The mint address of the position NFT. */
positionMint: Address;
};
async function internalOpenPositionInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
whirlpool: Account<Whirlpool>,
param: IncreaseLiquidityQuoteParam,
lowerTickIndex: number,
upperTickIndex: number,
mintA: Account<Mint>,
mintB: Account<Mint>,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
funder: TransactionSigner = FUNDER,
): Promise<OpenPositionInstructions> {
assert(
funder.address !== DEFAULT_ADDRESS,
"Either supply a funder or set the default funder",
);
const instructions: IInstruction[] = [];
const rent = await fetchSysvarRent(rpc);
let nonRefundableRent: bigint = 0n;
const tickRange = orderTickIndexes(lowerTickIndex, upperTickIndex);
const initializableLowerTickIndex = getInitializableTickIndex(
tickRange.tickLowerIndex,
whirlpool.data.tickSpacing,
false,
);
const initializableUpperTickIndex = getInitializableTickIndex(
tickRange.tickUpperIndex,
whirlpool.data.tickSpacing,
true,
);
const currentEpoch = await rpc.getEpochInfo().send();
const transferFeeA = getCurrentTransferFee(mintA, currentEpoch.epoch);
const transferFeeB = getCurrentTransferFee(mintB, currentEpoch.epoch);
const quote = getIncreaseLiquidityQuote(
param,
whirlpool.data,
initializableLowerTickIndex,
initializableUpperTickIndex,
slippageToleranceBps,
transferFeeA,
transferFeeB,
);
const positionMint = await generateKeyPairSigner();
const lowerTickArrayIndex = getTickArrayStartTickIndex(
initializableLowerTickIndex,
whirlpool.data.tickSpacing,
);
const upperTickArrayIndex = getTickArrayStartTickIndex(
initializableUpperTickIndex,
whirlpool.data.tickSpacing,
);
const [
positionAddress,
positionTokenAccount,
lowerTickArrayAddress,
upperTickArrayAddress,
] = await Promise.all([
getPositionAddress(positionMint.address),
findAssociatedTokenPda({
owner: funder.address,
mint: positionMint.address,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
}).then((x) => x[0]),
getTickArrayAddress(whirlpool.address, lowerTickArrayIndex).then(
(x) => x[0],
),
getTickArrayAddress(whirlpool.address, upperTickArrayIndex).then(
(x) => x[0],
),
]);
const { createInstructions, cleanupInstructions, tokenAccountAddresses } =
await prepareTokenAccountsInstructions(rpc, funder, {
[whirlpool.data.tokenMintA]: quote.tokenMaxA,
[whirlpool.data.tokenMintB]: quote.tokenMaxB,
});
instructions.push(...createInstructions);
const [lowerTickArray, upperTickArray] = await fetchAllMaybeTickArray(rpc, [
lowerTickArrayAddress,
upperTickArrayAddress,
]);
if (!lowerTickArray.exists) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool.address,
funder,
tickArray: lowerTickArrayAddress,
startTickIndex: lowerTickArrayIndex,
}),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getTickArraySize(),
);
}
if (!upperTickArray.exists && lowerTickArrayIndex !== upperTickArrayIndex) {
instructions.push(
getInitializeTickArrayInstruction({
whirlpool: whirlpool.address,
funder,
tickArray: upperTickArrayAddress,
startTickIndex: upperTickArrayIndex,
}),
);
nonRefundableRent += calculateMinimumBalanceForRentExemption(
rent,
getTickArraySize(),
);
}
instructions.push(
getOpenPositionWithTokenExtensionsInstruction({
funder,
owner: funder.address,
position: positionAddress[0],
positionMint,
positionTokenAccount,
whirlpool: whirlpool.address,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,
tickLowerIndex: initializableLowerTickIndex,
tickUpperIndex: initializableUpperTickIndex,
token2022Program: TOKEN_2022_PROGRAM_ADDRESS,
metadataUpdateAuth: address(
"3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr",
),
withTokenMetadataExtension: true,
}),
);
instructions.push(
getIncreaseLiquidityV2Instruction({
whirlpool: whirlpool.address,
positionAuthority: funder,
position: positionAddress[0],
positionTokenAccount,
tokenOwnerAccountA: tokenAccountAddresses[whirlpool.data.tokenMintA],
tokenOwnerAccountB: tokenAccountAddresses[whirlpool.data.tokenMintB],
tokenVaultA: whirlpool.data.tokenVaultA,
tokenVaultB: whirlpool.data.tokenVaultB,
tokenMintA: whirlpool.data.tokenMintA,
tokenMintB: whirlpool.data.tokenMintB,
tokenProgramA: mintA.programAddress,
tokenProgramB: mintB.programAddress,
tickArrayLower: lowerTickArrayAddress,
tickArrayUpper: upperTickArrayAddress,
liquidityAmount: quote.liquidityDelta,
tokenMaxA: quote.tokenMaxA,
tokenMaxB: quote.tokenMaxB,
memoProgram: MEMO_PROGRAM_ADDRESS,
remainingAccountsInfo: null,
}),
);
instructions.push(...cleanupInstructions);
return {
instructions,
quote,
positionMint: positionMint.address,
initializationCost: lamports(nonRefundableRent),
};
}
/**
* Opens a full-range position for a pool, typically used for Splash Pools or other full-range liquidity provisioning.
*
* @param {SolanaRpc} rpc - The Solana RPC client.
* @param {Address} poolAddress - The address of the liquidity pool.
* @param {IncreaseLiquidityQuoteParam} param - The parameters for adding liquidity, where one of `liquidity`, `tokenA`, or `tokenB` must be specified. The SDK will compute the others.
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The maximum acceptable slippage, in basis points (BPS).
* @param {TransactionSigner} [funder=FUNDER] - The account funding the transaction.
* @returns {Promise<OpenPositionInstructions>} A promise that resolves to an object containing the instructions, quote, position mint address, and initialization costs for increasing liquidity.
*
* @example
* import { openFullRangePositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent.
*
* const whirlpoolAddress = address("POOL_ADDRESS");
*
* const param = { tokenA: 1_000_000n };
*
* const { quote, instructions, initializationCost, positionMint } = await openFullRangePositionInstructions(
* devnetRpc,
* whirlpoolAddress,
* param,
* 100,
* wallet
* );
*/
export async function openFullRangePositionInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
poolAddress: Address,
param: IncreaseLiquidityQuoteParam,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
funder: TransactionSigner = FUNDER,
): Promise<OpenPositionInstructions> {
const whirlpool = await fetchWhirlpool(rpc, poolAddress);
const tickRange = getFullRangeTickIndexes(whirlpool.data.tickSpacing);
const [mintA, mintB] = await fetchAllMint(rpc, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
]);
return internalOpenPositionInstructions(
rpc,
whirlpool,
param,
tickRange.tickLowerIndex,
tickRange.tickUpperIndex,
mintA,
mintB,
slippageToleranceBps,
funder,
);
}
/**
* Opens a new position in a concentrated liquidity pool within a specific price range.
* This function allows you to provide liquidity for the specified range of prices and adjust liquidity parameters accordingly.
*
* **Note:** This function cannot be used with Splash Pools.
*
* @param {SolanaRpc} rpc - A Solana RPC client used to interact with the blockchain.
* @param {Address} poolAddress - The address of the liquidity pool where the position will be opened.
* @param {IncreaseLiquidityQuoteParam} param - The parameters for increasing liquidity, where you must choose one (`liquidity`, `tokenA`, or `tokenB`). The SDK will compute the other two.
* @param {number} lowerPrice - The lower bound of the price range for the position.
* @param {number} upperPrice - The upper bound of the price range for the position.
* @param {number} [slippageToleranceBps=SLIPPAGE_TOLERANCE_BPS] - The slippage tolerance for adding liquidity, in basis points (BPS).
* @param {TransactionSigner} [funder=FUNDER] - The account funding the transaction.
*
* @returns {Promise<OpenPositionInstructions>} A promise that resolves to an object containing instructions, quote, position mint address, and initialization costs for increasing liquidity.
*
* @example
* import { openPositionInstructions, setWhirlpoolsConfig } from '@orca-so/whirlpools';
* import { generateKeyPairSigner, createSolanaRpc, devnet, address } from '@solana/web3.js';
*
* await setWhirlpoolsConfig('solanaDevnet');
* const devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));
* const wallet = await generateKeyPairSigner(); // CAUTION: This wallet is not persistent.
*
* const whirlpoolAddress = address("POOL_ADDRESS");
*
* const param = { tokenA: 1_000_000n };
* const lowerPrice = 0.00005;
* const upperPrice = 0.00015;
*
* const { quote, instructions, initializationCost, positionMint } = await openPositionInstructions(
* devnetRpc,
* whirlpoolAddress,
* param,
* lowerPrice,
* upperPrice,
* 100,
* wallet
* );
*/
export async function openPositionInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi &
GetEpochInfoApi
>,
poolAddress: Address,
param: IncreaseLiquidityQuoteParam,
lowerPrice: number,
upperPrice: number,
slippageToleranceBps: number = SLIPPAGE_TOLERANCE_BPS,
funder: TransactionSigner = FUNDER,
): Promise<OpenPositionInstructions> {
const whirlpool = await fetchWhirlpool(rpc, poolAddress);
assert(
whirlpool.data.tickSpacing !== SPLASH_POOL_TICK_SPACING,
"Splash pools only support full range positions",
);
const [mintA, mintB] = await fetchAllMint(rpc, [
whirlpool.data.tokenMintA,
whirlpool.data.tokenMintB,
]);
const decimalsA = mintA.data.decimals;
const decimalsB = mintB.data.decimals;
const lowerTickIndex = priceToTickIndex(lowerPrice, decimalsA, decimalsB);
const upperTickIndex = priceToTickIndex(upperPrice, decimalsA, decimalsB);
return internalOpenPositionInstructions(
rpc,
whirlpool,
param,
lowerTickIndex,
upperTickIndex,
mintA,
mintB,
slippageToleranceBps,
funder,
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/token.ts
|
import {
fetchAllMaybeToken,
fetchAllMint,
findAssociatedTokenPda,
getCloseAccountInstruction,
getCreateAssociatedTokenInstruction,
getInitializeAccount3Instruction,
getSyncNativeInstruction,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import type {
Account,
Address,
GetAccountInfoApi,
GetMinimumBalanceForRentExemptionApi,
GetMultipleAccountsApi,
IInstruction,
MaybeAccount,
Rpc,
TransactionSigner,
} from "@solana/web3.js";
import {
address,
generateKeyPairSigner,
getAddressDecoder,
getAddressEncoder,
lamports,
} from "@solana/web3.js";
import { NATIVE_MINT_WRAPPING_STRATEGY } from "./config";
import {
getCreateAccountInstruction,
getCreateAccountWithSeedInstruction,
getTransferSolInstruction,
} from "@solana-program/system";
import { getTokenSize } from "@solana-program/token";
import { getTokenSize as getTokenSizeWithExtensions } from "@solana-program/token-2022";
import type { ExtensionArgs, Mint } from "@solana-program/token-2022";
import type { TransferFee } from "@orca-so/whirlpools-core";
import assert from "assert";
// This file is not exported through the barrel file
/** The public key for the native mint (SOL) */
export const NATIVE_MINT = address(
"So11111111111111111111111111111111111111112",
);
/**
* Represents the instructions and associated addresses for preparing token accounts during a transaction.
*/
type TokenAccountInstructions = {
/** A list of instructions required to create the necessary token accounts. */
createInstructions: IInstruction[];
/** A list of instructions to clean up (e.g., close) token accounts after the transaction is complete. */
cleanupInstructions: IInstruction[];
/** A mapping of mint addresses to their respective token account addresses. */
tokenAccountAddresses: Record<Address, Address>;
};
function mintFilter(x: Address) {
if (
NATIVE_MINT_WRAPPING_STRATEGY === "none" ||
NATIVE_MINT_WRAPPING_STRATEGY === "ata"
) {
return true;
}
return x != NATIVE_MINT;
}
/**
*
* Prepare token acounts required for a transaction. This will create
* ATAs for the supplied mints.
*
* The NATIVE_MINT is a special case where this function will optionally wrap/unwrap
* Native Mint based on the NATIVE_MINT_WRAPPING_STRATEGY.
*
* @param rpc
* @param owner the owner to create token accounts for
* @param spec the mints (and amounts) required in the token accounts
* @returns Instructions and addresses for the required token accounts
*/
export async function prepareTokenAccountsInstructions(
rpc: Rpc<
GetAccountInfoApi &
GetMultipleAccountsApi &
GetMinimumBalanceForRentExemptionApi
>,
owner: TransactionSigner,
spec: Address[] | Record<Address, bigint | number>,
): Promise<TokenAccountInstructions> {
const mintAddresses = Array.isArray(spec)
? spec
: (Object.keys(spec) as Address[]);
const nativeMintIndex = mintAddresses.indexOf(NATIVE_MINT);
const hasNativeMint = nativeMintIndex !== -1;
const mints = await fetchAllMint(rpc, mintAddresses.filter(mintFilter));
const tokenAddresses = await Promise.all(
mints.map((mint) =>
findAssociatedTokenPda({
owner: owner.address,
mint: mint.address,
tokenProgram: mint.programAddress,
}).then((x) => x[0]),
),
);
const tokenAccounts = await fetchAllMaybeToken(rpc, tokenAddresses);
const tokenAccountAddresses: Record<Address, Address> = {};
const createInstructions: IInstruction[] = [];
const cleanupInstructions: IInstruction[] = [];
for (let i = 0; i < mints.length; i++) {
const mint = mints[i];
const tokenAccount = tokenAccounts[i];
tokenAccountAddresses[mint.address] = tokenAccount.address;
if (tokenAccount.exists) {
continue;
}
createInstructions.push(
getCreateAssociatedTokenInstruction({
payer: owner,
owner: owner.address,
ata: tokenAccount.address,
mint: mint.address,
tokenProgram: mint.programAddress,
}),
);
}
if (!Array.isArray(spec)) {
for (let i = 0; i < mints.length; i++) {
const mint = mints[i];
if (
mint.address === NATIVE_MINT &&
NATIVE_MINT_WRAPPING_STRATEGY !== "none"
) {
continue;
}
const tokenAccount = tokenAccounts[i];
const existingBalance = tokenAccount.exists
? tokenAccount.data.amount
: 0n;
assert(
BigInt(spec[mint.address]) <= existingBalance,
`Token account for ${mint.address} does not have the required balance`,
);
}
}
if (hasNativeMint && NATIVE_MINT_WRAPPING_STRATEGY === "keypair") {
const keypair = await generateKeyPairSigner();
const space = getTokenSize();
let amount = await rpc
.getMinimumBalanceForRentExemption(BigInt(space))
.send();
if (!Array.isArray(spec)) {
amount = lamports(amount + BigInt(spec[NATIVE_MINT]));
}
createInstructions.push(
getCreateAccountInstruction({
payer: owner,
newAccount: keypair,
lamports: amount,
space,
programAddress: TOKEN_PROGRAM_ADDRESS,
}),
getInitializeAccount3Instruction({
account: keypair.address,
mint: NATIVE_MINT,
owner: owner.address,
}),
);
cleanupInstructions.push(
getCloseAccountInstruction({
account: keypair.address,
owner,
destination: owner.address,
}),
);
tokenAccountAddresses[NATIVE_MINT] = keypair.address;
}
if (hasNativeMint && NATIVE_MINT_WRAPPING_STRATEGY === "seed") {
const space = getTokenSize();
let amount = await rpc
.getMinimumBalanceForRentExemption(BigInt(space))
.send();
if (!Array.isArray(spec)) {
amount = lamports(amount + BigInt(spec[NATIVE_MINT]));
}
// Generating secure seed takes longer and is not really needed here.
// With date, it should only create collisions if the same owner
// creates multiple accounts at exactly the same time (in ms)
const seed = Date.now().toString();
const buffer = await crypto.subtle.digest(
"SHA-256",
Buffer.concat([
Buffer.from(getAddressEncoder().encode(owner.address)),
Buffer.from(seed),
Buffer.from(getAddressEncoder().encode(TOKEN_PROGRAM_ADDRESS)),
]),
);
tokenAccountAddresses[NATIVE_MINT] = getAddressDecoder().decode(
new Uint8Array(buffer),
);
createInstructions.push(
getCreateAccountWithSeedInstruction({
payer: owner,
newAccount: tokenAccountAddresses[NATIVE_MINT],
base: owner.address,
baseAccount: owner,
seed: seed,
space,
amount,
programAddress: TOKEN_PROGRAM_ADDRESS,
}),
getInitializeAccount3Instruction({
account: tokenAccountAddresses[NATIVE_MINT],
mint: NATIVE_MINT,
owner: owner.address,
}),
);
cleanupInstructions.push(
getCloseAccountInstruction({
account: tokenAccountAddresses[NATIVE_MINT],
owner,
destination: owner.address,
}),
);
}
if (hasNativeMint && NATIVE_MINT_WRAPPING_STRATEGY === "ata") {
const account = tokenAccounts[nativeMintIndex];
const existingBalance = account.exists ? account.data.amount : 0n;
if (!Array.isArray(spec) && existingBalance < BigInt(spec[NATIVE_MINT])) {
createInstructions.push(
getTransferSolInstruction({
source: owner,
destination: tokenAccountAddresses[NATIVE_MINT],
amount: BigInt(spec[NATIVE_MINT]) - existingBalance,
}),
getSyncNativeInstruction({
account: tokenAccountAddresses[NATIVE_MINT],
}),
);
}
if (!account.exists) {
cleanupInstructions.push(
getCloseAccountInstruction({
account: account.address,
owner,
destination: owner.address,
}),
);
}
}
return {
createInstructions,
cleanupInstructions,
tokenAccountAddresses,
};
}
/**
* Retrieves the current transfer fee configuration for a given token mint based on the current epoch.
*
* This function checks the mint's transfer fee configuration and returns the appropriate fee
* structure (older or newer) depending on the current epoch. If no transfer fee configuration is found,
* it returns `undefined`.
*
* @param {Mint} mint - The mint account of the token, which may include transfer fee extensions.
* @param {bigint} currentEpoch - The current epoch to determine the applicable transfer fee.
*
* @returns {TransferFee | undefined} - The transfer fee configuration for the given mint, or `undefined` if no transfer fee is configured.
*/
export function getCurrentTransferFee(
mint: MaybeAccount<Mint> | Account<Mint> | null,
currentEpoch: bigint,
): TransferFee | undefined {
if (
mint == null ||
("exists" in mint && !mint.exists) ||
mint.data.extensions.__option === "None"
) {
return undefined;
}
const feeConfig = mint.data.extensions.value.find(
(x) => x.__kind === "TransferFeeConfig",
);
if (feeConfig == null) {
return undefined;
}
const transferFee =
currentEpoch >= feeConfig.newerTransferFee.epoch
? feeConfig.newerTransferFee
: feeConfig.olderTransferFee;
return {
feeBps: transferFee.transferFeeBasisPoints,
maxFee: transferFee.maximumFee,
};
}
/**
* Builds the required account extensions for a given mint. This should only be used
* for non-ATA token accounts since ATA accounts should also add the ImmutableOwner extension.
*
* https://github.com/solana-labs/solana-program-library/blob/3844bfac50990c1aa4dfb30f244f8c13178fc3fa/token/program-2022/src/extension/mod.rs#L1276
*
* @param {Mint} mint - The mint account to build extensions for.
* @returns {ExtensionArgs[]} An array of extension arguments.
*/
export function getAccountExtensions(mint: Mint): ExtensionArgs[] {
if (mint.extensions.__option === "None") {
return [];
}
const extensions: ExtensionArgs[] = [];
for (const extension of mint.extensions.value) {
switch (extension.__kind) {
case "TransferFeeConfig":
extensions.push({
__kind: "TransferFeeAmount",
withheldAmount: 0n,
});
break;
case "NonTransferable":
extensions.push({
__kind: "NonTransferableAccount",
});
break;
case "TransferHook":
extensions.push({
__kind: "TransferHookAccount",
transferring: false,
});
break;
}
}
return extensions;
}
/**
* Orders two mints by canonical byte order.
*
* @param {Address} mint1
* @param {Address} mint2
* @returns {[Address, Address]} [mint1, mint2] if mint1 should come first, [mint2, mint1] otherwise
*/
export function orderMints(mint1: Address, mint2: Address): [Address, Address] {
const encoder = getAddressEncoder();
const mint1Bytes = new Uint8Array(encoder.encode(mint1));
const mint2Bytes = new Uint8Array(encoder.encode(mint2));
return Buffer.compare(mint1Bytes, mint2Bytes) < 0
? [mint1, mint2]
: [mint2, mint1];
}
/**
* Returns the token size for a given mint account.
*
* @param {Account<Mint>} mint - The mint account to get the token size for.
* @returns {number} The token size for the given mint account.
*/
export function getTokenSizeForMint(mint: Account<Mint>): number {
const extensions = getAccountExtensions(mint.data);
return extensions.length === 0
? getTokenSize()
: getTokenSizeWithExtensions(extensions);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool
|
solana_public_repos/orca-so/whirlpools/ts-sdk/whirlpool/src/sysvar.ts
|
import type { SysvarRent } from "@solana/sysvars";
/**
* The overhead storage size for accounts.
*/
const ACCOUNT_STORAGE_OVERHEAD = 128;
/**
* Calculates the minimum balance required for rent exemption for a given account size.
*
* @param {Rpc} rpc - The Solana RPC client to fetch sysvar rent data.
* @param {number} dataSize - The size of the account data in bytes.
* @returns {bigint} The minimum balance required for rent exemption in lamports.
*/
export function calculateMinimumBalanceForRentExemption(
rent: SysvarRent,
dataSize: number,
): bigint {
const dataSizeForRent = BigInt(dataSize + ACCOUNT_STORAGE_OVERHEAD);
const rentLamportsPerYear = rent.lamportsPerByteYear * dataSizeForRent;
const minimumBalance = rentLamportsPerYear * BigInt(rent.exemptionThreshold);
return minimumBalance;
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/codama.js
|
import { createFromRoot } from "codama";
import { renderVisitor } from "@codama/renderers-js";
import { rootNodeFromAnchor } from "@codama/nodes-from-anchor";
import { readFileSync } from "fs";
const idl = JSON.parse(readFileSync("../../target/idl/whirlpool.json", "utf8"));
const node = rootNodeFromAnchor(idl);
const visitor = renderVisitor("./src/generated");
// IDL generated with anchor 0.29 does not have the address field so we have to add it manually
const codama = createFromRoot({
...node,
program: {
...node.program,
publicKey: "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc",
},
});
codama.accept(visitor);
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/README.md
|
# Orca Whirlpools Client SDK
## Overview
This package provides developers with low-level functionalities for interacting with the Whirlpool Program on Solana. It serves as a foundational tool that allows developers to manage and integrate detailed operations into their Typescript projects, particularly those related to Orca's Whirlpool Program. While a high-level SDK is available for easier integration, [@orca-so/whirlpools](https://www.npmjs.com/package/@orca-so/whirlpools), this package offers more granular control for advanced use cases.
> **Note:** This SDK uses Solana Web3.js SDK v2. It is not compatible with the widely used v1.x.x version.
## Key Features
- **Codama Client**: The package includes a set of generated client code based on the Whirlpool Program IDL. This ensures all the necessary program information is easily accessible in a structured format and handles all decoding and encoding of instructions and account data, making it much easier to interact with the program.
- **GPA (Get Program Accounts) Filters**: This feature contains utilities to add filters to program accounts, allowing developers to fetch program account data more selectively and efficiently.
- **PDA (Program Derived Addresses) Utilities**: This feature contains utility functions that help derive Program Derived Addresses (PDAs) for accounts within the Whirlpool Program, simplifying address generation for developers.
## Installation
You can install the package via npm:
```bash
npm install @orca-so/whirlpools-client
```
## Usage
Here are some basic examples of how to use the package.
### Fetching Whirlpool Accounts with Filters
The following example demonstrates how to fetch Whirlpools accounts based on specific filters, using the GPA utilities:
```tsx
import { createSolanaRpc, address, devnet } from '@solana/web3.js';
import { fetchAllWhirlpoolWithFilter, whirlpoolTokenMintAFilter } from "@orca-so/whirlpools-client";
const rpc = createSolanaRpc(devnet("https://api.devnet.solana.com"));
const tokenMintA = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //DevUSDC
const filter = whirlpoolTokenMintAFilter(tokenMintA);
const accounts = await fetchAllWhirlpoolWithFilter(rpc, filter);
console.log(accounts);
```
### Deriving a PDA
To derive a PDA for a Whirlpool account, you can use the `getWhirlpoolAddress` PDA utility.
```tsx
import { getWhirlpoolAddress } from "@orca-so/whirlpools-client";
import { address } from '@solana/web3.js';
const whirlpoolConfigAddress = address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR");
const tokenMintA = address("So11111111111111111111111111111111111111112"); //wSOL
const tokenMintB = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); //DevUSDC
const tickSpacing = 64;
const whirlpoolPda = await getWhirlpoolAddress(
whirlpoolConfigAddress,
tokenMintA,
tokenMintB,
tickSpacing,
);
console.log(whirlpoolPda);
```
### Example: Initialize Pool Instruction
The following example demonstrates how to create an InitializePool instruction using the Codama-IDL autogenerated code:
```tsx
import { getInitializePoolV2Instruction, getTokenBadgeAddress, getWhirlpoolAddress, getFeeTierAddress } from "@orca-so/whirlpools-client";
import { address, generateKeyPairSigner } from '@solana/web3.js';
const whirlpoolConfigAddress = address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR");
const tokenMintA = address("So11111111111111111111111111111111111111112"); // wSOL
const tokenMintB = address("BRjpCHtyQLNCo8gqRUr8jtdAj5AjPYQaoqbvcZiHok1k"); // DevUSDC
const tokenBadgeA = await getTokenBadgeAddress(whirlpoolConfigAddress, tokenMintA)
const tokenBadgeB = await getTokenBadgeAddress(whirlpoolConfigAddress, tokenMintB)
const wallet = await generateKeyPairSigner(); // CAUTION: this wallet is not persistent
const tickSpacing = 8;
const whirlpool = await getWhirlpoolAddress(whirlpoolConfigAddress, tokenMintA, tokenMintB, tickSpacing);
const tokenVaultA = await generateKeyPairSigner();
const tokenVaultB = await generateKeyPairSigner();
const feeTier = await getFeeTierAddress(whirlpoolConfigAddress, tickSpacing);
const tokenProgramA = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const tokenProgramB = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const initialSqrtPrice = BigInt(7459106261056563200n);
const initializePoolInstruction = getInitializePoolV2Instruction({
whirlpoolsConfig: whirlpoolConfigAddress,
tokenMintA,
tokenMintB,
tokenBadgeA,
tokenBadgeB,
funder: wallet,
whirlpool,
tokenVaultA,
tokenVaultB,
feeTier,
whirlpoolBump: 1,
tickSpacing,
tokenProgramA,
tokenProgramB,
initialSqrtPrice
});
console.log(initializePoolInstruction);
```
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/package.json
|
{
"name": "@orca-so/whirlpools-client",
"version": "0.0.1",
"description": "Typescript client to interact with Orca's on-chain Whirlpool program.",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
"import": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"require": "./dist/index.cjs"
}
},
"sideEffects": false,
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "node ./codama.js && tsup src/index.ts --format cjs,esm --dts --sourcemap",
"test": "vitest run tests",
"clean": "rimraf dist src/generated"
},
"peerDependencies": {
"@solana/web3.js": "^2.0.0"
},
"devDependencies": {
"@codama/nodes-from-anchor": "^1.0.0",
"@codama/renderers-js": "^1.0.1",
"@orca-so/whirlpools-program": "*",
"@solana/web3.js": "^2.0.0",
"codama": "^1.0.0",
"typescript": "^5.7.2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/orca-so/whirlpools.git"
},
"license": "Apache-2.0",
"keywords": [
"solana",
"crypto",
"defi",
"dex",
"amm"
],
"author": "team@orca.so",
"bugs": {
"url": "https://github.com/orca-so/whirlpools/issues"
},
"homepage": "https://orca.so"
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/typedoc.json
|
{
"entryPoints": ["./src/index.ts"]
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/tsconfig.json
|
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"include": ["./src/**/*.ts"]
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/tests/pda.test.ts
|
import { address } from "@solana/web3.js";
import assert from "assert";
import { getFeeTierAddress } from "../src/pda/feeTier";
import { getOracleAddress } from "../src/pda/oracle";
import { getPositionAddress } from "../src/pda/position";
import {
getBundledPositionAddress,
getPositionBundleAddress,
} from "../src/pda/positionBundle";
import { getTickArrayAddress } from "../src/pda/tickArray";
import { getTokenBadgeAddress } from "../src/pda/tokenBadge";
import { getWhirlpoolAddress } from "../src/pda/whirlpool";
import { getWhirlpoolsConfigExtensionAddress } from "../src/pda/whirlpoolsConfigExtension";
import { describe, it } from "vitest";
const TEST_WHIRLPOOLS_CONFIG_ADDRESS = address(
"2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ",
);
const TEST_POSITION_MINT_ADDRESS = address(
"6sf6fSK6tTubFA2LMCeTzt4c6DeNVyA6WpDDgtWs7a5p",
);
const TEST_WHIRLPOOL_ADDRESS = address(
"2kJmUjxWBwL2NGPBV2PiA5hWtmLCqcKY6reQgkrPtaeS",
);
const TEST_TOKEN_MINT_ADDRESS = address(
"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo",
);
const TEST_NATIVE_MINT_ADDRESS = address(
"So11111111111111111111111111111111111111112",
);
describe("derive program accounts", () => {
it("FeeTier", async () => {
const address = await getFeeTierAddress(TEST_WHIRLPOOLS_CONFIG_ADDRESS, 1);
assert.strictEqual(
address[0],
"62dSkn5ktwY1PoKPNMArZA4bZsvyemuknWUnnQ2ATTuN",
);
});
it("Oracle", async () => {
const address = await getOracleAddress(TEST_WHIRLPOOL_ADDRESS);
assert.strictEqual(
address[0],
"821SHenpVGYY7BCXUzNhs8Xi4grG557fqRw4wzgaPQcS",
);
});
it("Position", async () => {
const address = await getPositionAddress(TEST_POSITION_MINT_ADDRESS);
assert.strictEqual(
address[0],
"2EtH4ZZStW8Ffh2CbbW4baekdtWgPLcBXfYQ6FRmMVsq",
);
});
it("PositionBundle", async () => {
const address = await getPositionBundleAddress(TEST_POSITION_MINT_ADDRESS);
assert.strictEqual(
address[0],
"At1QvbnANV6imkdNkfB4h1XsY4jbTzPAmScgjLCnM7jy",
);
});
it("BundledPosition", async () => {
const address = await getBundledPositionAddress(
TEST_POSITION_MINT_ADDRESS,
0,
);
assert.strictEqual(
address[0],
"9Zj8oWYVQdBCtqMn9Z3YyGo8o7hVXLEUZ5x5no5ykVm6",
);
});
it("TickArray", async () => {
const address = await getTickArrayAddress(TEST_WHIRLPOOL_ADDRESS, 0);
assert.strictEqual(
address[0],
"8PhPzk7n4wU98Z6XCbVtPai2LtXSxYnfjkmgWuoAU8Zy",
);
});
it("TokenBadge", async () => {
const address = await getTokenBadgeAddress(
TEST_WHIRLPOOLS_CONFIG_ADDRESS,
TEST_TOKEN_MINT_ADDRESS,
);
assert.strictEqual(
address[0],
"HX5iftnCxhtu11ys3ZuWbvUqo7cyPYaVNZBrLL67Hrbm",
);
});
it("Whirlpool", async () => {
const address = await getWhirlpoolAddress(
TEST_WHIRLPOOLS_CONFIG_ADDRESS,
TEST_NATIVE_MINT_ADDRESS,
TEST_TOKEN_MINT_ADDRESS,
2,
);
assert.strictEqual(
address[0],
"JDQ9GDphXV5ENDrAQtRFvT98m3JwsVJJk8BYHoX8uTAg",
);
});
it("WhilrpoolsConfigExtension", async () => {
const address = await getWhirlpoolsConfigExtensionAddress(
TEST_WHIRLPOOLS_CONFIG_ADDRESS,
);
assert.strictEqual(
address[0],
"777H5H3Tp9U11uRVRzFwM8BinfiakbaLT8vQpeuhvEiH",
);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/tests/gpa.test.ts
|
import { describe, it, beforeEach, afterEach, vi } from "vitest";
import assert from "assert";
import type { FeeTierArgs } from "../src/generated/accounts/feeTier";
import { getFeeTierEncoder } from "../src/generated/accounts/feeTier";
import type {
Address,
GetProgramAccountsMemcmpFilter,
ReadonlyUint8Array,
} from "@solana/web3.js";
import {
createDefaultRpcTransport,
createSolanaRpcFromTransport,
getAddressDecoder,
getBase58Encoder,
} from "@solana/web3.js";
import {
feeTierFeeRateFilter,
feeTierTickSpacingFilter,
feeTierWhirlpoolsConfigFilter,
fetchAllFeeTierWithFilter,
} from "../src/gpa/feeTier";
import type { PositionArgs } from "../src/generated/accounts/position";
import { getPositionEncoder } from "../src/generated/accounts/position";
import {
fetchAllPositionWithFilter,
positionMintFilter,
positionTickLowerIndexFilter,
positionTickUpperIndexFilter,
positionWhirlpoolFilter,
} from "../src/gpa/position";
import type { PositionBundleArgs } from "../src/generated/accounts/positionBundle";
import { getPositionBundleEncoder } from "../src/generated/accounts/positionBundle";
import {
fetchAllPositionBundleWithFilter,
positionBundleMintFilter,
} from "../src/gpa/positionBundle";
import type { TickArrayArgs } from "../src/generated/accounts/tickArray";
import { getTickArrayEncoder } from "../src/generated/accounts/tickArray";
import {
fetchAllTickArrayWithFilter,
tickArrayStartTickIndexFilter,
tickArrayWhirlpoolFilter,
} from "../src/gpa/tickArray";
import type { TickArgs } from "../src/generated/types/tick";
import type { TokenBadgeArgs } from "../src/generated/accounts/tokenBadge";
import { getTokenBadgeEncoder } from "../src/generated/accounts/tokenBadge";
import {
fetchAllTokenBadgeWithFilter,
tokenBadgeTokenMintFilter,
tokenBadgeWhirlpoolsConfigFilter,
} from "../src/gpa/tokenBadge";
import type { WhirlpoolArgs } from "../src/generated/accounts/whirlpool";
import { getWhirlpoolEncoder } from "../src/generated/accounts/whirlpool";
import {
fetchAllWhirlpoolWithFilter,
whirlpoolFeeRateFilter,
whirlpoolProtocolFeeRateFilter,
whirlpoolRewardMint1Filter,
whirlpoolRewardMint2Filter,
whirlpoolRewardMint3Filter,
whirlpoolRewardVault1Filter,
whirlpoolRewardVault2Filter,
whirlpoolRewardVault3Filter,
whirlpoolTickSpacingFilter,
whirlpoolTokenMintAFilter,
whirlpoolTokenMintBFilter,
whirlpoolTokenVaultAFilter,
whirlpoolTokenVaultBFilter,
whirlpoolWhirlpoolConfigFilter,
} from "../src/gpa/whirlpool";
import type { WhirlpoolsConfigArgs } from "../src/generated/accounts/whirlpoolsConfig";
import { getWhirlpoolsConfigEncoder } from "../src/generated/accounts/whirlpoolsConfig";
import {
fetchAllWhirlpoolsConfigWithFilter,
whirlpoolsConfigCollectProtocolFeesAuthorityFilter,
whirlpoolsConfigDefaultProtocolFeeRateFilter,
whirlpoolsConfigFeeAuthorityFilter,
whirlpoolsConfigRewardEmissionsSuperAuthorityFilter,
} from "../src/gpa/whirlpoolsConfig";
import type { WhirlpoolsConfigExtensionArgs } from "../src/generated/accounts/whirlpoolsConfigExtension";
import { getWhirlpoolsConfigExtensionEncoder } from "../src/generated/accounts/whirlpoolsConfigExtension";
import {
fetchAllWhirlpoolsConfigExtensionWithFilter,
whirlpoolsConfigExtensionConfigExtensionAuthorityFilter,
whirlpoolsConfigExtensionConfigTokenBadgeAuthorityFilter,
whirlpoolsConfigExtensionWhirlpoolsConfigFilter,
} from "../src/gpa/whirlpoolsConfigExtension";
import { fetchDecodedProgramAccounts } from "../src/gpa/utils";
describe("get program account memcmp filters", () => {
const mockRpc = createSolanaRpcFromTransport(
createDefaultRpcTransport({ url: "" }),
);
const addresses: Address[] = [...Array(25).keys()].map((i) => {
const bytes = Array.from({ length: 32 }, () => i);
return getAddressDecoder().decode(new Uint8Array(bytes));
});
beforeEach(() => {
vi.mock("../src/gpa/utils", () => ({
fetchDecodedProgramAccounts: vi.fn().mockResolvedValue([]),
}));
});
afterEach(() => {
vi.restoreAllMocks();
});
function assertFilters(data: ReadonlyUint8Array) {
const mockFetch = vi.mocked(fetchDecodedProgramAccounts);
const filters = mockFetch.mock
.calls[0][2] as GetProgramAccountsMemcmpFilter[];
for (const filter of filters) {
const offset = Number(filter.memcmp.offset);
const actual = getBase58Encoder().encode(filter.memcmp.bytes);
const expected = data.subarray(offset, offset + actual.length);
assert.deepStrictEqual(actual, expected);
}
}
it("FeeTier", async () => {
const feeTierStruct: FeeTierArgs = {
whirlpoolsConfig: addresses[0],
tickSpacing: 1234,
defaultFeeRate: 4321,
};
await fetchAllFeeTierWithFilter(
mockRpc,
feeTierWhirlpoolsConfigFilter(feeTierStruct.whirlpoolsConfig),
feeTierTickSpacingFilter(feeTierStruct.tickSpacing),
feeTierFeeRateFilter(feeTierStruct.defaultFeeRate),
);
const data = getFeeTierEncoder().encode(feeTierStruct);
assertFilters(data);
});
it("Position", async () => {
const positionStruct: PositionArgs = {
whirlpool: addresses[0],
positionMint: addresses[1],
liquidity: 1234,
tickLowerIndex: 5678,
tickUpperIndex: 9012,
feeGrowthCheckpointA: 3456,
feeOwedA: 7890,
feeGrowthCheckpointB: 2345,
feeOwedB: 6789,
rewardInfos: [
{ growthInsideCheckpoint: 9876, amountOwed: 5432 },
{ growthInsideCheckpoint: 8765, amountOwed: 4321 },
{ growthInsideCheckpoint: 7654, amountOwed: 3210 },
],
};
await fetchAllPositionWithFilter(
mockRpc,
positionWhirlpoolFilter(positionStruct.whirlpool),
positionMintFilter(positionStruct.positionMint),
positionTickLowerIndexFilter(positionStruct.tickLowerIndex),
positionTickUpperIndexFilter(positionStruct.tickUpperIndex),
);
const data = getPositionEncoder().encode(positionStruct);
assertFilters(data);
});
it("PositionBundle", async () => {
const positionBundleStruct: PositionBundleArgs = {
positionBundleMint: addresses[0],
positionBitmap: new Uint8Array(88),
};
await fetchAllPositionBundleWithFilter(
mockRpc,
positionBundleMintFilter(positionBundleStruct.positionBundleMint),
);
const data = getPositionBundleEncoder().encode(positionBundleStruct);
assertFilters(data);
});
it("TickArray", async () => {
const tickStruct: TickArgs = {
initialized: true,
liquidityNet: 1234,
liquidityGross: 5678,
feeGrowthOutsideA: 9012,
feeGrowthOutsideB: 3456,
rewardGrowthsOutside: [1234, 5678, 9012],
};
const tickArrayStruct: TickArrayArgs = {
startTickIndex: 1234,
ticks: Array(88).fill(tickStruct),
whirlpool: addresses[0],
};
await fetchAllTickArrayWithFilter(
mockRpc,
tickArrayStartTickIndexFilter(tickArrayStruct.startTickIndex),
tickArrayWhirlpoolFilter(tickArrayStruct.whirlpool),
);
const data = getTickArrayEncoder().encode(tickArrayStruct);
assertFilters(data);
});
it("TokenBadge", async () => {
const tokenBadgeStruct: TokenBadgeArgs = {
whirlpoolsConfig: addresses[0],
tokenMint: addresses[1],
};
await fetchAllTokenBadgeWithFilter(
mockRpc,
tokenBadgeWhirlpoolsConfigFilter(tokenBadgeStruct.whirlpoolsConfig),
tokenBadgeTokenMintFilter(tokenBadgeStruct.tokenMint),
);
const data = getTokenBadgeEncoder().encode(tokenBadgeStruct);
assertFilters(data);
});
it("Whirlpool", async () => {
const whirlpoolStruct: WhirlpoolArgs = {
whirlpoolsConfig: addresses[0],
whirlpoolBump: [0],
tickSpacing: 1234,
tickSpacingSeed: [1, 2],
feeRate: 4321,
protocolFeeRate: 5678,
liquidity: 9012,
sqrtPrice: 3456,
tickCurrentIndex: 7890,
protocolFeeOwedA: 2345,
protocolFeeOwedB: 6789,
tokenMintA: addresses[1],
tokenVaultA: addresses[2],
feeGrowthGlobalA: 9876,
tokenMintB: addresses[3],
tokenVaultB: addresses[4],
feeGrowthGlobalB: 5432,
rewardLastUpdatedTimestamp: 2109,
rewardInfos: [
{
mint: addresses[5],
vault: addresses[6],
authority: addresses[7],
emissionsPerSecondX64: 8514,
growthGlobalX64: 2841,
},
{
mint: addresses[8],
vault: addresses[9],
authority: addresses[10],
emissionsPerSecondX64: 5815,
growthGlobalX64: 1185,
},
{
mint: addresses[11],
vault: addresses[12],
authority: addresses[13],
emissionsPerSecondX64: 1821,
growthGlobalX64: 1256,
},
],
};
await fetchAllWhirlpoolWithFilter(
mockRpc,
whirlpoolWhirlpoolConfigFilter(whirlpoolStruct.whirlpoolsConfig),
whirlpoolTickSpacingFilter(whirlpoolStruct.tickSpacing),
whirlpoolFeeRateFilter(whirlpoolStruct.feeRate),
whirlpoolProtocolFeeRateFilter(whirlpoolStruct.protocolFeeRate),
whirlpoolTokenMintAFilter(whirlpoolStruct.tokenMintA),
whirlpoolTokenVaultAFilter(whirlpoolStruct.tokenVaultA),
whirlpoolTokenMintBFilter(whirlpoolStruct.tokenMintB),
whirlpoolTokenVaultBFilter(whirlpoolStruct.tokenVaultB),
whirlpoolRewardMint1Filter(whirlpoolStruct.rewardInfos[0].mint),
whirlpoolRewardVault1Filter(whirlpoolStruct.rewardInfos[0].vault),
whirlpoolRewardMint2Filter(whirlpoolStruct.rewardInfos[1].mint),
whirlpoolRewardVault2Filter(whirlpoolStruct.rewardInfos[1].vault),
whirlpoolRewardMint3Filter(whirlpoolStruct.rewardInfos[2].mint),
whirlpoolRewardVault3Filter(whirlpoolStruct.rewardInfos[2].vault),
);
const data = getWhirlpoolEncoder().encode(whirlpoolStruct);
assertFilters(data);
});
it("WhirlpoolsConfig", async () => {
const whirlpoolsConfigStruct: WhirlpoolsConfigArgs = {
feeAuthority: addresses[0],
collectProtocolFeesAuthority: addresses[1],
rewardEmissionsSuperAuthority: addresses[2],
defaultProtocolFeeRate: 1234,
};
await fetchAllWhirlpoolsConfigWithFilter(
mockRpc,
whirlpoolsConfigFeeAuthorityFilter(whirlpoolsConfigStruct.feeAuthority),
whirlpoolsConfigCollectProtocolFeesAuthorityFilter(
whirlpoolsConfigStruct.collectProtocolFeesAuthority,
),
whirlpoolsConfigRewardEmissionsSuperAuthorityFilter(
whirlpoolsConfigStruct.rewardEmissionsSuperAuthority,
),
whirlpoolsConfigDefaultProtocolFeeRateFilter(
whirlpoolsConfigStruct.defaultProtocolFeeRate,
),
);
const data = getWhirlpoolsConfigEncoder().encode(whirlpoolsConfigStruct);
assertFilters(data);
});
it("WhirlpoolsConfigExtension", async () => {
const whirlpoolsConfigExtensionStruct: WhirlpoolsConfigExtensionArgs = {
whirlpoolsConfig: addresses[0],
configExtensionAuthority: addresses[1],
tokenBadgeAuthority: addresses[2],
};
await fetchAllWhirlpoolsConfigExtensionWithFilter(
mockRpc,
whirlpoolsConfigExtensionWhirlpoolsConfigFilter(
whirlpoolsConfigExtensionStruct.whirlpoolsConfig,
),
whirlpoolsConfigExtensionConfigExtensionAuthorityFilter(
whirlpoolsConfigExtensionStruct.configExtensionAuthority,
),
whirlpoolsConfigExtensionConfigTokenBadgeAuthorityFilter(
whirlpoolsConfigExtensionStruct.tokenBadgeAuthority,
),
);
const data = getWhirlpoolsConfigExtensionEncoder().encode(
whirlpoolsConfigExtensionStruct,
);
assertFilters(data);
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/index.ts
|
export * from "./generated";
export * from "./gpa";
export * from "./pda";
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/whirlpoolsConfig.ts
|
import type {
GetProgramAccountsMemcmpFilter,
Address,
Account,
GetProgramAccountsApi,
Rpc,
} from "@solana/web3.js";
import {
getBase58Decoder,
getAddressEncoder,
getU16Encoder,
} from "@solana/web3.js";
import type { WhirlpoolsConfig } from "../generated/accounts/whirlpoolsConfig";
import {
WHIRLPOOLS_CONFIG_DISCRIMINATOR,
getWhirlpoolsConfigDecoder,
} from "../generated/accounts/whirlpoolsConfig";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type WhirlpoolsConfigFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function whirlpoolsConfigFeeAuthorityFilter(
feeAuthority: Address,
): WhirlpoolsConfigFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(feeAuthority),
),
encoding: "base58",
},
} as WhirlpoolsConfigFilter;
}
export function whirlpoolsConfigCollectProtocolFeesAuthorityFilter(
collectProtocolFeesAuthority: Address,
): WhirlpoolsConfigFilter {
return {
memcmp: {
offset: 40n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(collectProtocolFeesAuthority),
),
encoding: "base58",
},
} as WhirlpoolsConfigFilter;
}
export function whirlpoolsConfigRewardEmissionsSuperAuthorityFilter(
rewardEmissionsSuperAuthority: Address,
): WhirlpoolsConfigFilter {
return {
memcmp: {
offset: 72n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(rewardEmissionsSuperAuthority),
),
encoding: "base58",
},
} as WhirlpoolsConfigFilter;
}
export function whirlpoolsConfigDefaultProtocolFeeRateFilter(
defaultFeeRate: number,
): WhirlpoolsConfigFilter {
return {
memcmp: {
offset: 104n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(defaultFeeRate)),
encoding: "base58",
},
} as WhirlpoolsConfigFilter;
}
export async function fetchAllWhirlpoolsConfigWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: WhirlpoolsConfigFilter[]
): Promise<Account<WhirlpoolsConfig>[]> {
const discriminator = getBase58Decoder().decode(
WHIRLPOOLS_CONFIG_DISCRIMINATOR,
);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getWhirlpoolsConfigDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/positionBundle.ts
|
import type {
Account,
Address,
GetProgramAccountsApi,
GetProgramAccountsMemcmpFilter,
Rpc,
} from "@solana/web3.js";
import { getAddressEncoder, getBase58Decoder } from "@solana/web3.js";
import type { PositionBundle } from "../generated/accounts/positionBundle";
import {
POSITION_BUNDLE_DISCRIMINATOR,
getPositionBundleDecoder,
} from "../generated/accounts/positionBundle";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type PositionBundleFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function positionBundleMintFilter(
address: Address,
): PositionBundleFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as PositionBundleFilter;
}
export async function fetchAllPositionBundleWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: PositionBundleFilter[]
): Promise<Account<PositionBundle>[]> {
const discriminator = getBase58Decoder().decode(
POSITION_BUNDLE_DISCRIMINATOR,
);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getPositionBundleDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/tickArray.ts
|
import type {
Account,
Address,
GetProgramAccountsApi,
GetProgramAccountsMemcmpFilter,
Rpc,
} from "@solana/web3.js";
import {
getAddressEncoder,
getBase58Decoder,
getI32Encoder,
} from "@solana/web3.js";
import type { TickArray } from "../generated/accounts/tickArray";
import {
TICK_ARRAY_DISCRIMINATOR,
getTickArrayDecoder,
} from "../generated/accounts/tickArray";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type TickArrayFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function tickArrayStartTickIndexFilter(
startTickIndex: number,
): TickArrayFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getI32Encoder().encode(startTickIndex)),
encoding: "base58",
},
} as TickArrayFilter;
}
export function tickArrayWhirlpoolFilter(address: Address): TickArrayFilter {
return {
memcmp: {
offset: 9956n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as TickArrayFilter;
}
export async function fetchAllTickArrayWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: TickArrayFilter[]
): Promise<Account<TickArray>[]> {
const discriminator = getBase58Decoder().decode(TICK_ARRAY_DISCRIMINATOR);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getTickArrayDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/whirlpool.ts
|
import type {
Account,
Address,
GetProgramAccountsApi,
GetProgramAccountsMemcmpFilter,
Rpc,
} from "@solana/web3.js";
import {
getAddressEncoder,
getBase58Decoder,
getU16Encoder,
} from "@solana/web3.js";
import type { Whirlpool } from "../generated/accounts/whirlpool";
import {
WHIRLPOOL_DISCRIMINATOR,
getWhirlpoolDecoder,
} from "../generated/accounts/whirlpool";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type WhirlpoolFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function whirlpoolWhirlpoolConfigFilter(
address: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolTickSpacingFilter(
tickSpacing: number,
): WhirlpoolFilter {
return {
memcmp: {
offset: 41n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(tickSpacing)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolFeeRateFilter(
defaultFeeRate: number,
): WhirlpoolFilter {
return {
memcmp: {
offset: 45n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(defaultFeeRate)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolProtocolFeeRateFilter(
protocolFeeRate: number,
): WhirlpoolFilter {
return {
memcmp: {
offset: 47n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(protocolFeeRate)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolTokenMintAFilter(
tokenMintA: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 101n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(tokenMintA)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolTokenVaultAFilter(
tokenVaultA: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 133n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(tokenVaultA)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolTokenMintBFilter(
tokenMintB: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 181n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(tokenMintB)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolTokenVaultBFilter(
tokenVaultB: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 213n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(tokenVaultB)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardMint1Filter(
rewardMint1: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 269n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(rewardMint1)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardVault1Filter(
rewardVault1: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 301n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(rewardVault1),
),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardMint2Filter(
rewardMint2: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 397n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(rewardMint2)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardVault2Filter(
rewardVault2: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 429n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(rewardVault2),
),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardMint3Filter(
rewardMint3: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 525n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(rewardMint3)),
encoding: "base58",
},
} as WhirlpoolFilter;
}
export function whirlpoolRewardVault3Filter(
rewardVault3: Address,
): WhirlpoolFilter {
return {
memcmp: {
offset: 557n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(rewardVault3),
),
encoding: "base58",
},
} as WhirlpoolFilter;
}
/**
* Fetches all Whirlpool accounts with the specified filters.
*
* This function fetches all Whirlpool accounts from the blockchain that match the specified filters.
* It uses the Whirlpool discriminator to identify Whirlpool accounts and applies additional filters
* provided as arguments.
*
* @param {Rpc<GetProgramAccountsApi>} rpc - The Solana RPC client to fetch program accounts.
* @param {...WhirlpoolFilter[]} filters - The filters to apply when fetching Whirlpool accounts.
* @returns {Promise<Account<Whirlpool>[]>} A promise that resolves to an array of Whirlpool accounts.
*
* @example
* import { address, createSolanaRpc, devnet } from "@solana/web3.js";
* import { fetchAllWhirlpoolWithFilter, whirlpoolWhirlpoolConfigFilter } from "@orca-so/whirlpools-client";
*
* const rpcDevnet = createSolanaRpc(devnet("https://api.devnet.solana.com"));
* const WHIRLPOOLS_CONFIG_ADDRESS_DEVNET = address("FcrweFY1G9HJAHG5inkGB6pKg1HZ6x9UC2WioAfWrGkR");
* const whirlpools = await fetchAllWhirlpoolWithFilter(rpcDevnet, whirlpoolWhirlpoolConfigFilter(WHIRLPOOLS_CONFIG_ADDRESS_DEVNET));
*/
export async function fetchAllWhirlpoolWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: WhirlpoolFilter[]
): Promise<Account<Whirlpool>[]> {
const discriminator = getBase58Decoder().decode(WHIRLPOOL_DISCRIMINATOR);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getWhirlpoolDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/feeTier.ts
|
import type {
Account,
Address,
GetProgramAccountsApi,
GetProgramAccountsMemcmpFilter,
Rpc,
} from "@solana/web3.js";
import {
getAddressEncoder,
getBase58Decoder,
getU16Encoder,
} from "@solana/web3.js";
import type { FeeTier } from "../generated/accounts/feeTier";
import {
FEE_TIER_DISCRIMINATOR,
getFeeTierDecoder,
} from "../generated/accounts/feeTier";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
type FeeTierFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function feeTierWhirlpoolsConfigFilter(address: Address): FeeTierFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as FeeTierFilter;
}
export function feeTierTickSpacingFilter(tickSpacing: number): FeeTierFilter {
return {
memcmp: {
offset: 40n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(tickSpacing)),
encoding: "base58",
},
} as FeeTierFilter;
}
export function feeTierFeeRateFilter(defaultFeeRate: number): FeeTierFilter {
return {
memcmp: {
offset: 42n,
bytes: getBase58Decoder().decode(getU16Encoder().encode(defaultFeeRate)),
encoding: "base58",
},
} as FeeTierFilter;
}
export async function fetchAllFeeTierWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: FeeTierFilter[]
): Promise<Account<FeeTier>[]> {
const discriminator = getBase58Decoder().decode(FEE_TIER_DISCRIMINATOR);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getFeeTierDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/position.ts
|
import type {
GetProgramAccountsMemcmpFilter,
Account,
GetProgramAccountsApi,
Rpc,
Address,
} from "@solana/web3.js";
import {
getBase58Decoder,
getAddressEncoder,
getI32Encoder,
} from "@solana/web3.js";
import type { Position } from "../generated/accounts/position";
import {
POSITION_DISCRIMINATOR,
getPositionDecoder,
} from "../generated/accounts/position";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
type PositionFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function positionWhirlpoolFilter(address: Address): PositionFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as PositionFilter;
}
export function positionMintFilter(address: Address): PositionFilter {
return {
memcmp: {
offset: 40n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as PositionFilter;
}
export function positionTickLowerIndexFilter(
tickLowerIndex: number,
): PositionFilter {
return {
memcmp: {
offset: 88n,
bytes: getBase58Decoder().decode(getI32Encoder().encode(tickLowerIndex)),
encoding: "base58",
},
} as PositionFilter;
}
export function positionTickUpperIndexFilter(
tickUpperIndex: number,
): PositionFilter {
return {
memcmp: {
offset: 92n,
bytes: getBase58Decoder().decode(getI32Encoder().encode(tickUpperIndex)),
encoding: "base58",
},
} as PositionFilter;
}
export async function fetchAllPositionWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: PositionFilter[]
): Promise<Account<Position>[]> {
const discriminator = getBase58Decoder().decode(POSITION_DISCRIMINATOR);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getPositionDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/utils.ts
|
import type {
Account,
Address,
GetProgramAccountsApi,
GetProgramAccountsMemcmpFilter,
Rpc,
VariableSizeDecoder,
} from "@solana/web3.js";
import { getBase64Encoder } from "@solana/web3.js";
export async function fetchDecodedProgramAccounts<T extends object>(
rpc: Rpc<GetProgramAccountsApi>,
programAddress: Address,
filters: GetProgramAccountsMemcmpFilter[],
decoder: VariableSizeDecoder<T>,
): Promise<Account<T>[]> {
const accountInfos = await rpc
.getProgramAccounts(programAddress, {
encoding: "base64",
filters,
})
.send();
const encoder = getBase64Encoder();
const datas = accountInfos.map((x) => encoder.encode(x.account.data[0]));
const decoded = datas.map((x) => decoder.decode(x));
return decoded.map((data, i) => ({
...accountInfos[i].account,
address: accountInfos[i].pubkey,
programAddress: programAddress,
data,
}));
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/tokenBadge.ts
|
import type {
GetProgramAccountsMemcmpFilter,
Address,
Account,
GetProgramAccountsApi,
Rpc,
} from "@solana/web3.js";
import { getBase58Decoder, getAddressEncoder } from "@solana/web3.js";
import type { TokenBadge } from "../generated/accounts/tokenBadge";
import {
TOKEN_BADGE_DISCRIMINATOR,
getTokenBadgeDecoder,
} from "../generated/accounts/tokenBadge";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type TokenBadgeFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function tokenBadgeWhirlpoolsConfigFilter(
address: Address,
): TokenBadgeFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as TokenBadgeFilter;
}
export function tokenBadgeTokenMintFilter(address: Address): TokenBadgeFilter {
return {
memcmp: {
offset: 40n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as TokenBadgeFilter;
}
export async function fetchAllTokenBadgeWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: TokenBadgeFilter[]
): Promise<Account<TokenBadge>[]> {
const discriminator = getBase58Decoder().decode(TOKEN_BADGE_DISCRIMINATOR);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getTokenBadgeDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/index.ts
|
export * from "./feeTier";
export * from "./position";
export * from "./positionBundle";
export * from "./tickArray";
export * from "./tokenBadge";
export * from "./whirlpool";
export * from "./whirlpoolsConfig";
export * from "./whirlpoolsConfigExtension";
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/gpa/whirlpoolsConfigExtension.ts
|
import type {
GetProgramAccountsMemcmpFilter,
Address,
Account,
GetProgramAccountsApi,
Rpc,
} from "@solana/web3.js";
import { getBase58Decoder, getAddressEncoder } from "@solana/web3.js";
import type { WhirlpoolsConfigExtension } from "../generated/accounts/whirlpoolsConfigExtension";
import {
WHIRLPOOLS_CONFIG_EXTENSION_DISCRIMINATOR,
getWhirlpoolsConfigExtensionDecoder,
} from "../generated/accounts/whirlpoolsConfigExtension";
import { fetchDecodedProgramAccounts } from "./utils";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export type WhirlpoolsConfigExtensionFilter = GetProgramAccountsMemcmpFilter & {
readonly __kind: unique symbol;
};
export function whirlpoolsConfigExtensionWhirlpoolsConfigFilter(
address: Address,
): WhirlpoolsConfigExtensionFilter {
return {
memcmp: {
offset: 8n,
bytes: getBase58Decoder().decode(getAddressEncoder().encode(address)),
encoding: "base58",
},
} as WhirlpoolsConfigExtensionFilter;
}
export function whirlpoolsConfigExtensionConfigExtensionAuthorityFilter(
configExtensionAuthority: Address,
): WhirlpoolsConfigExtensionFilter {
return {
memcmp: {
offset: 40n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(configExtensionAuthority),
),
encoding: "base58",
},
} as WhirlpoolsConfigExtensionFilter;
}
export function whirlpoolsConfigExtensionConfigTokenBadgeAuthorityFilter(
configTokenBadgeAuthority: Address,
): WhirlpoolsConfigExtensionFilter {
return {
memcmp: {
offset: 72n,
bytes: getBase58Decoder().decode(
getAddressEncoder().encode(configTokenBadgeAuthority),
),
encoding: "base58",
},
} as WhirlpoolsConfigExtensionFilter;
}
export async function fetchAllWhirlpoolsConfigExtensionWithFilter(
rpc: Rpc<GetProgramAccountsApi>,
...filters: WhirlpoolsConfigExtensionFilter[]
): Promise<Account<WhirlpoolsConfigExtension>[]> {
const discriminator = getBase58Decoder().decode(
WHIRLPOOLS_CONFIG_EXTENSION_DISCRIMINATOR,
);
const discriminatorFilter: GetProgramAccountsMemcmpFilter = {
memcmp: {
offset: 0n,
bytes: discriminator,
encoding: "base58",
},
};
return fetchDecodedProgramAccounts(
rpc,
WHIRLPOOL_PROGRAM_ADDRESS,
[discriminatorFilter, ...filters],
getWhirlpoolsConfigExtensionDecoder(),
);
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/positionBundle.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getPositionBundleAddress(
positionBundleMint: Address,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: ["position_bundle", getAddressEncoder().encode(positionBundleMint)],
});
}
export async function getBundledPositionAddress(
positionBundleAddress: Address,
bundleIndex: number,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: [
"bundled_position",
getAddressEncoder().encode(positionBundleAddress),
Buffer.from(bundleIndex.toString()),
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/tickArray.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getTickArrayAddress(
whirlpool: Address,
startTickIndex: number,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: [
"tick_array",
getAddressEncoder().encode(whirlpool),
`${startTickIndex}`,
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/whirlpool.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import {
getAddressEncoder,
getProgramDerivedAddress,
getU16Encoder,
} from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getWhirlpoolAddress(
whirlpoolsConfig: Address,
tokenMintA: Address,
tokenMintB: Address,
tickSpacing: number,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: [
"whirlpool",
getAddressEncoder().encode(whirlpoolsConfig),
getAddressEncoder().encode(tokenMintA),
getAddressEncoder().encode(tokenMintB),
getU16Encoder().encode(tickSpacing),
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/oracle.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getOracleAddress(
whirlpool: Address,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: ["oracle", getAddressEncoder().encode(whirlpool)],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/feeTier.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import {
getAddressEncoder,
getProgramDerivedAddress,
getU16Encoder,
} from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getFeeTierAddress(
whirlpoolsConfig: Address,
tickSpacing: number,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: [
"fee_tier",
getAddressEncoder().encode(whirlpoolsConfig),
getU16Encoder().encode(tickSpacing),
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/position.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getPositionAddress(
positionMint: Address,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: ["position", getAddressEncoder().encode(positionMint)],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/tokenBadge.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getTokenBadgeAddress(
whirlpoolsConfig: Address,
tokenMint: Address,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: [
"token_badge",
getAddressEncoder().encode(whirlpoolsConfig),
getAddressEncoder().encode(tokenMint),
],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/index.ts
|
export * from "./feeTier";
export * from "./oracle";
export * from "./position";
export * from "./positionBundle";
export * from "./tickArray";
export * from "./tokenBadge";
export * from "./whirlpool";
export * from "./whirlpoolsConfigExtension";
| 0
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src
|
solana_public_repos/orca-so/whirlpools/ts-sdk/client/src/pda/whirlpoolsConfigExtension.ts
|
import type { Address, ProgramDerivedAddress } from "@solana/web3.js";
import { getAddressEncoder, getProgramDerivedAddress } from "@solana/web3.js";
import { WHIRLPOOL_PROGRAM_ADDRESS } from "../generated/programs/whirlpool";
export async function getWhirlpoolsConfigExtensionAddress(
configAddress: Address,
): Promise<ProgramDerivedAddress> {
return await getProgramDerivedAddress({
programAddress: WHIRLPOOL_PROGRAM_ADDRESS,
seeds: ["config_extension", getAddressEncoder().encode(configAddress)],
});
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/Cargo.toml
|
[package]
name = "orca_whirlpools_core"
version = "0.1.0"
description = "Orca's core rust package."
include = ["src/*"]
documentation = "https://orca-so.github.io/whirlpools/"
homepage = "https://orca.so"
repository = "https://github.com/orca-so/whirlpools"
license = "Apache-2.0"
keywords = ["solana", "crypto", "defi", "dex", "amm"]
authors = ["team@orca.so"]
edition = "2021"
[features]
default = ["floats"]
wasm = ["dep:wasm-bindgen", "dep:serde", "dep:serde-big-array", "dep:serde-wasm-bindgen", "dep:js-sys", "dep:tsify"]
floats = ["dep:libm"]
[dependencies]
ethnum = { version = "^1.1" }
libm = { version = "^0.1", optional = true }
orca_whirlpools_macros = { path = "../macros" }
wasm-bindgen = { version = "^0.2", optional = true }
serde = { version = "^1.0", features = ["derive"], optional = true }
serde-big-array = { version = "^0.5", optional = true }
serde-wasm-bindgen = { version = "^0.6", optional = true }
js-sys = { version = "^0.3", optional = true }
tsify = { version = "^0.4", features = ["js"], optional = true }
[dev-dependencies]
approx = { version = "^0" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/README.md
|
# Orca Whirlpools Core SDK
This package provides developers with advanced functionalities for interacting with the Whirlpool Program on Solana. The Core SDK offers convenient methods for math calculations, quotes, and other utilities, making it easier to manage complex liquidity and swap operations within Rust projects. It serves as the foundation for the High-Level SDK, providing key building blocks that enable developers to perform sophisticated actions while maintaining control over core details.
## Key Features
- **Math Library**: Contains a variety of functions for math operations related to bundles, positions, prices, ticks, and tokens, including calculations such as determining position status or price conversions.
- **Quote Library**: Provides utility functions for generating quotes, such as increasing liquidity, collecting fees or rewards, and swapping, enabling precise and optimized decision-making in liquidity management.
## Installation
```bash
cargo add orca_whirlpools_core
```
## Usage
Here are some basic examples of how to use the package:
### Math Example
The following example demonstrates how to use the `is_position_in_range` function to determine whether a position is currently in range.
```rust
use orca_whirlpools_core::is_position_in_range;
fn main() {
let current_sqrt_price = 7448043534253661173u128;
let tick_index_1 = -18304;
let tick_index_2 = -17956;
let in_range = is_position_in_range(current_sqrt_price.into(), tick_index_1, tick_index_2);
println!("Position in range? {:?}", in_range);
}
```
Expected output:
```
Position in range? true
```
### Adjust Liquidity Quote Example
The following example demonstrates how to use the increase_liquidity_quote_a function to calculate a quote for increasing liquidity given a token A amount.
```rust
use orca_whirlpools_core::increase_liquidity_quote_a;
use orca_whirlpools_core::TransferFee;
fn main() {
let token_amount_a = 1000000000u64;
let slippage_tolerance_bps = 100u16;
let current_sqrt_price = 7437568627975669726u128;
let tick_index_1 = -18568;
let tick_index_2 = -17668;
let transfer_fee_a = Some(TransferFee::new(200));
let transfer_fee_b = None;
let quote = increase_liquidity_quote_a(
token_amount_a,
slippage_tolerance_bps,
current_sqrt_price.into(),
tick_index_1,
tick_index_2,
transfer_fee_a,
transfer_fee_b,
).unwrap();
println!("{:?}", quote);
}
```
Expected output:
```
IncreaseLiquidityQuote {
liquidity_delta: 16011047470,
token_est_a: 1000000000,
token_est_b: 127889169,
token_max_a: 1010000000,
token_max_b: 129168061,
}
```
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/package.json
|
{
"name": "@orca-so/whirlpools-rust-core",
"version": "0.0.1",
"scripts": {
"build": "cargo build -p orca_whirlpools_core",
"test": "cargo test -p orca_whirlpools_core --lib",
"format": "cargo clippy --fix --allow-dirty --allow-staged && cargo fmt",
"lint": "cargo clippy && cargo fmt --check",
"clean": "cargo clean -p orca_whirlpools_core"
},
"devDependencies": {
"@orca-so/whirlpools-rust-macros": "*"
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/lib.rs
|
// FIXME: disable std for non-test builds to decrease wasm binary size.
// There is currently something in tsify that prevents this:
// https://github.com/madonoharu/tsify/issues/56
// #![cfg_attr(not(test), no_std)]
#![allow(clippy::useless_conversion)]
mod constants;
mod math;
mod quote;
mod types;
pub use constants::*;
pub use math::*;
pub use quote::*;
pub use types::*;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/swap.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct ExactInSwapQuote {
pub token_in: u64,
pub token_est_out: u64,
pub token_min_out: u64,
pub trade_fee: u64,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct ExactOutSwapQuote {
pub token_out: u64,
pub token_est_in: u64,
pub token_max_in: u64,
pub trade_fee: u64,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/u128.rs
|
// While `wasm_expose` doesn't automatically convert rust `u128` to js `bigint`, we have
// to proxy it through an opaque type that we define here. This is a workaround until
// `wasm_bindgen` supports `u128` abi conversion natively.
#[cfg(not(feature = "wasm"))]
pub type U128 = u128;
#[cfg(feature = "wasm")]
use core::fmt::{Debug, Formatter, Result};
#[cfg(feature = "wasm")]
use ethnum::U256;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg(feature = "wasm")]
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "bigint")]
pub type U128;
}
#[cfg(feature = "wasm")]
impl Debug for U128 {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "{:?}", JsValue::from(self))
}
}
#[cfg(feature = "wasm")]
impl From<U128> for u128 {
fn from(value: U128) -> u128 {
JsValue::from(value).try_into().unwrap_or(0)
}
}
#[cfg(feature = "wasm")]
impl From<U128> for U256 {
fn from(value: U128) -> U256 {
let u_128: u128 = value.into();
<U256>::from(u_128)
}
}
#[cfg(feature = "wasm")]
impl From<u128> for U128 {
fn from(value: u128) -> U128 {
JsValue::from(value).unchecked_into()
}
}
#[cfg(feature = "wasm")]
impl PartialEq<u128> for U128 {
fn eq(&self, other: &u128) -> bool {
self == &(*other).into()
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/token.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct TransferFee {
pub fee_bps: u16,
pub max_fee: u64,
}
impl TransferFee {
pub fn new(fee_bps: u16) -> Self {
Self {
fee_bps,
max_fee: u64::MAX,
}
}
pub fn new_with_max(fee_bps: u16, max_fee: u64) -> Self {
Self { fee_bps, max_fee }
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/tick_array.rs
|
use crate::types::TickArrayFacade;
#[cfg(not(feature = "wasm"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TickArrays {
One(TickArrayFacade),
Two(TickArrayFacade, TickArrayFacade),
Three(TickArrayFacade, TickArrayFacade, TickArrayFacade),
Four(
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
),
Five(
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
),
Six(
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
TickArrayFacade,
),
}
#[cfg(feature = "wasm")]
use core::fmt::{Debug, Formatter, Result as FmtResult};
#[cfg(feature = "wasm")]
use js_sys::Array;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg(feature = "wasm")]
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(typescript_type = "TickArrayFacade[]")]
pub type TickArrays;
}
#[cfg(feature = "wasm")]
impl Debug for TickArrays {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, "{:?}", JsValue::from(self))
}
}
#[cfg(feature = "wasm")]
impl From<TickArrays> for [Option<TickArrayFacade>; 6] {
fn from(val: TickArrays) -> Self {
let val = JsValue::from(val);
if !val.is_array() {
return [None, None, None, None, None, None];
}
let array: Array = val.unchecked_into();
let mut result = [None, None, None, None, None, None];
for (i, item) in array.iter().enumerate() {
if let Ok(item) = serde_wasm_bindgen::from_value(item) {
result[i] = Some(item);
}
}
result
}
}
#[cfg(not(feature = "wasm"))]
impl From<TickArrays> for [Option<TickArrayFacade>; 6] {
fn from(val: TickArrays) -> Self {
match val {
TickArrays::One(tick_array) => [Some(tick_array), None, None, None, None, None],
TickArrays::Two(tick_array_1, tick_array_2) => [
Some(tick_array_1),
Some(tick_array_2),
None,
None,
None,
None,
],
TickArrays::Three(tick_array_1, tick_array_2, tick_array_3) => [
Some(tick_array_1),
Some(tick_array_2),
Some(tick_array_3),
None,
None,
None,
],
TickArrays::Four(tick_array_1, tick_array_2, tick_array_3, tick_array_4) => [
Some(tick_array_1),
Some(tick_array_2),
Some(tick_array_3),
Some(tick_array_4),
None,
None,
],
TickArrays::Five(
tick_array_1,
tick_array_2,
tick_array_3,
tick_array_4,
tick_array_5,
) => [
Some(tick_array_1),
Some(tick_array_2),
Some(tick_array_3),
Some(tick_array_4),
Some(tick_array_5),
None,
],
TickArrays::Six(
tick_array_1,
tick_array_2,
tick_array_3,
tick_array_4,
tick_array_5,
tick_array_6,
) => [
Some(tick_array_1),
Some(tick_array_2),
Some(tick_array_3),
Some(tick_array_4),
Some(tick_array_5),
Some(tick_array_6),
],
}
}
}
#[cfg(not(feature = "wasm"))]
impl From<TickArrayFacade> for TickArrays {
fn from(val: TickArrayFacade) -> Self {
TickArrays::One(val)
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 1]> for TickArrays {
fn from(val: [TickArrayFacade; 1]) -> Self {
TickArrays::One(val[0])
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 2]> for TickArrays {
fn from(val: [TickArrayFacade; 2]) -> Self {
TickArrays::Two(val[0], val[1])
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 3]> for TickArrays {
fn from(val: [TickArrayFacade; 3]) -> Self {
TickArrays::Three(val[0], val[1], val[2])
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 4]> for TickArrays {
fn from(val: [TickArrayFacade; 4]) -> Self {
TickArrays::Four(val[0], val[1], val[2], val[3])
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 5]> for TickArrays {
fn from(val: [TickArrayFacade; 5]) -> Self {
TickArrays::Five(val[0], val[1], val[2], val[3], val[4])
}
}
#[cfg(not(feature = "wasm"))]
impl From<[TickArrayFacade; 6]> for TickArrays {
fn from(val: [TickArrayFacade; 6]) -> Self {
TickArrays::Six(val[0], val[1], val[2], val[3], val[4], val[5])
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/liquidity.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct DecreaseLiquidityQuote {
pub liquidity_delta: u128,
pub token_est_a: u64,
pub token_est_b: u64,
pub token_min_a: u64,
pub token_min_b: u64,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct IncreaseLiquidityQuote {
pub liquidity_delta: u128,
pub token_est_a: u64,
pub token_est_b: u64,
pub token_max_a: u64,
pub token_max_b: u64,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/fees.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct CollectFeesQuote {
pub fee_owed_a: u64,
pub fee_owed_b: u64,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/mod.rs
|
mod fees;
mod liquidity;
mod pool;
mod position;
mod rewards;
mod swap;
mod tick;
mod tick_array;
mod token;
mod u128;
#[cfg(feature = "wasm")]
mod u64;
pub use fees::*;
pub use liquidity::*;
pub use pool::*;
pub use position::*;
pub use rewards::*;
pub use swap::*;
pub use tick::*;
pub use tick_array::*;
pub use token::*;
pub use u128::*;
#[cfg(feature = "wasm")]
pub use u64::*;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/pool.rs
|
#![allow(non_snake_case)]
use crate::NUM_REWARDS;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct WhirlpoolFacade {
pub tick_spacing: u16,
pub fee_rate: u16,
pub protocol_fee_rate: u16,
pub liquidity: u128,
pub sqrt_price: u128,
pub tick_current_index: i32,
pub fee_growth_global_a: u128,
pub fee_growth_global_b: u128,
pub reward_last_updated_timestamp: u64,
#[cfg_attr(feature = "wasm", tsify(type = "WhirlpoolRewardInfoFacade[]"))]
pub reward_infos: [WhirlpoolRewardInfoFacade; NUM_REWARDS],
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct WhirlpoolRewardInfoFacade {
pub emissions_per_second_x64: u128,
pub growth_global_x64: u128,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/u64.rs
|
use serde::Serializer;
// Serialize a u64 as a u128. This is so that we can use u64 value in rust
// but serialize as a bigint in wasm.
pub fn u64_serialize<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u128(*value as u128)
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/position.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::NUM_REWARDS;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct PositionRatio {
pub ratio_a: u16,
pub ratio_b: u16,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub enum PositionStatus {
PriceInRange,
PriceBelowRange,
PriceAboveRange,
Invalid,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct PositionFacade {
pub liquidity: u128,
pub tick_lower_index: i32,
pub tick_upper_index: i32,
pub fee_growth_checkpoint_a: u128,
pub fee_owed_a: u64,
pub fee_growth_checkpoint_b: u128,
pub fee_owed_b: u64,
#[cfg_attr(feature = "wasm", tsify(type = "PositionRewardInfoFacade[]"))]
pub reward_infos: [PositionRewardInfoFacade; NUM_REWARDS],
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct PositionRewardInfoFacade {
pub growth_inside_checkpoint: u128,
pub amount_owed: u64,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/rewards.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::NUM_REWARDS;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct CollectRewardsQuote {
pub rewards: [CollectRewardQuote; NUM_REWARDS],
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct CollectRewardQuote {
pub rewards_owed: u64,
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/types/tick.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use serde_big_array::BigArray;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::TICK_ARRAY_SIZE;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct TickRange {
pub tick_lower_index: i32,
pub tick_upper_index: i32,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct TickFacade {
pub initialized: bool,
pub liquidity_net: i128,
pub liquidity_gross: u128,
pub fee_growth_outside_a: u128,
pub fee_growth_outside_b: u128,
#[cfg_attr(feature = "wasm", tsify(type = "bigint[]"))]
pub reward_growths_outside: [u128; 3],
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct TickArrayFacade {
pub start_tick_index: i32,
#[cfg_attr(feature = "wasm", serde(with = "BigArray"))]
pub ticks: [TickFacade; TICK_ARRAY_SIZE],
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/quote/swap.rs
|
use crate::{
sqrt_price_to_tick_index, tick_index_to_sqrt_price, try_apply_swap_fee, try_apply_transfer_fee,
try_get_amount_delta_a, try_get_amount_delta_b, try_get_max_amount_with_slippage_tolerance,
try_get_min_amount_with_slippage_tolerance, try_get_next_sqrt_price_from_a,
try_get_next_sqrt_price_from_b, try_reverse_apply_swap_fee, try_reverse_apply_transfer_fee,
CoreError, ExactInSwapQuote, ExactOutSwapQuote, TickArraySequence, TickArrays, TickFacade,
TransferFee, WhirlpoolFacade, AMOUNT_EXCEEDS_MAX_U64, ARITHMETIC_OVERFLOW,
INVALID_SQRT_PRICE_LIMIT_DIRECTION, MAX_SQRT_PRICE, MIN_SQRT_PRICE,
SQRT_PRICE_LIMIT_OUT_OF_BOUNDS, ZERO_TRADABLE_AMOUNT,
};
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// Computes the exact input or output amount for a swap transaction.
///
/// # Arguments
/// - `token_in`: The input token amount.
/// - `specified_token_a`: If `true`, the input token is token A. Otherwise, it is token B.
/// - `slippage_tolerance`: The slippage tolerance in basis points.
/// - `whirlpool`: The whirlpool state.
/// - `tick_arrays`: The tick arrays needed for the swap.
/// - `transfer_fee_a`: The transfer fee for token A.
/// - `transfer_fee_b`: The transfer fee for token B.
///
/// # Returns
/// The exact input or output amount for the swap transaction.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn swap_quote_by_input_token(
token_in: u64,
specified_token_a: bool,
slippage_tolerance_bps: u16,
whirlpool: WhirlpoolFacade,
tick_arrays: TickArrays,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<ExactInSwapQuote, CoreError> {
let (transfer_fee_in, transfer_fee_out) = if specified_token_a {
(transfer_fee_a, transfer_fee_b)
} else {
(transfer_fee_b, transfer_fee_a)
};
let token_in_after_fee =
try_apply_transfer_fee(token_in.into(), transfer_fee_in.unwrap_or_default())?;
let tick_sequence = TickArraySequence::new(tick_arrays.into(), whirlpool.tick_spacing)?;
let swap_result = compute_swap(
token_in_after_fee.into(),
0,
whirlpool,
tick_sequence,
specified_token_a,
true,
0,
)?;
let (token_in_after_fees, token_est_out_before_fee) = if specified_token_a {
(swap_result.token_a, swap_result.token_b)
} else {
(swap_result.token_b, swap_result.token_a)
};
let token_in =
try_reverse_apply_transfer_fee(token_in_after_fees, transfer_fee_in.unwrap_or_default())?;
let token_est_out = try_apply_transfer_fee(
token_est_out_before_fee,
transfer_fee_out.unwrap_or_default(),
)?;
let token_min_out =
try_get_min_amount_with_slippage_tolerance(token_est_out, slippage_tolerance_bps)?;
Ok(ExactInSwapQuote {
token_in,
token_est_out,
token_min_out,
trade_fee: swap_result.trade_fee,
})
}
/// Computes the exact input or output amount for a swap transaction.
///
/// # Arguments
/// - `token_out`: The output token amount.
/// - `specified_token_a`: If `true`, the output token is token A. Otherwise, it is token B.
/// - `slippage_tolerance`: The slippage tolerance in basis points.
/// - `whirlpool`: The whirlpool state.
/// - `tick_arrays`: The tick arrays needed for the swap.
/// - `transfer_fee_a`: The transfer fee for token A.
/// - `transfer_fee_b`: The transfer fee for token B.
///
/// # Returns
/// The exact input or output amount for the swap transaction.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn swap_quote_by_output_token(
token_out: u64,
specified_token_a: bool,
slippage_tolerance_bps: u16,
whirlpool: WhirlpoolFacade,
tick_arrays: TickArrays,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<ExactOutSwapQuote, CoreError> {
let (transfer_fee_in, transfer_fee_out) = if specified_token_a {
(transfer_fee_b, transfer_fee_a)
} else {
(transfer_fee_a, transfer_fee_b)
};
let token_out_before_fee =
try_reverse_apply_transfer_fee(token_out, transfer_fee_out.unwrap_or_default())?;
let tick_sequence = TickArraySequence::new(tick_arrays.into(), whirlpool.tick_spacing)?;
let swap_result = compute_swap(
token_out_before_fee.into(),
0,
whirlpool,
tick_sequence,
!specified_token_a,
false,
0,
)?;
let (token_out_before_fee, token_est_in_after_fee) = if specified_token_a {
(swap_result.token_a, swap_result.token_b)
} else {
(swap_result.token_b, swap_result.token_a)
};
let token_out =
try_apply_transfer_fee(token_out_before_fee, transfer_fee_out.unwrap_or_default())?;
let token_est_in = try_reverse_apply_transfer_fee(
token_est_in_after_fee,
transfer_fee_in.unwrap_or_default(),
)?;
let token_max_in =
try_get_max_amount_with_slippage_tolerance(token_est_in, slippage_tolerance_bps)?;
Ok(ExactOutSwapQuote {
token_out,
token_est_in,
token_max_in,
trade_fee: swap_result.trade_fee,
})
}
pub struct SwapResult {
pub token_a: u64,
pub token_b: u64,
pub trade_fee: u64,
}
/// Computes the amounts of tokens A and B based on the current Whirlpool state and tick sequence.
///
/// # Arguments
/// - `token_amount`: The input or output amount specified for the swap. Must be non-zero.
/// - `sqrt_price_limit`: The price limit for the swap represented as a square root.
/// If set to `0`, it defaults to the minimum or maximum sqrt price based on the direction of the swap.
/// - `whirlpool`: The current state of the Whirlpool AMM, including liquidity, price, and tick information.
/// - `tick_sequence`: A sequence of ticks used to determine price levels during the swap process.
/// - `a_to_b`: Indicates the direction of the swap:
/// - `true`: Swap from token A to token B.
/// - `false`: Swap from token B to token A.
/// - `specified_input`: Determines if the input amount is specified:
/// - `true`: `token_amount` represents the input amount.
/// - `false`: `token_amount` represents the output amount.
/// - `_timestamp`: A placeholder for future full swap logic, currently ignored.
///
/// # Returns
/// A `Result` containing a `SwapResult` struct if the swap is successful, or an `ErrorCode` if the computation fails.
/// # Notes
/// - This function doesn't take into account slippage tolerance.
/// - This function doesn't take into account transfer fee extension.
pub fn compute_swap<const SIZE: usize>(
token_amount: u64,
sqrt_price_limit: u128,
whirlpool: WhirlpoolFacade,
tick_sequence: TickArraySequence<SIZE>,
a_to_b: bool,
specified_input: bool,
_timestamp: u64, // currently ignored but needed for full swap logic
) -> Result<SwapResult, CoreError> {
let sqrt_price_limit = if sqrt_price_limit == 0 {
if a_to_b {
MIN_SQRT_PRICE
} else {
MAX_SQRT_PRICE
}
} else {
sqrt_price_limit
};
if !(MIN_SQRT_PRICE..=MAX_SQRT_PRICE).contains(&sqrt_price_limit) {
return Err(SQRT_PRICE_LIMIT_OUT_OF_BOUNDS);
}
if a_to_b && sqrt_price_limit > whirlpool.sqrt_price
|| !a_to_b && sqrt_price_limit < whirlpool.sqrt_price
{
return Err(INVALID_SQRT_PRICE_LIMIT_DIRECTION);
}
if token_amount == 0 {
return Err(ZERO_TRADABLE_AMOUNT);
}
let mut amount_remaining = token_amount;
let mut amount_calculated = 0u64;
let mut current_sqrt_price = whirlpool.sqrt_price;
let mut current_tick_index = whirlpool.tick_current_index;
let mut current_liquidity = whirlpool.liquidity;
let mut trade_fee = 0u64;
while amount_remaining > 0 && sqrt_price_limit != current_sqrt_price {
let (next_tick, next_tick_index) = if a_to_b {
tick_sequence.prev_initialized_tick(current_tick_index)?
} else {
tick_sequence.next_initialized_tick(current_tick_index)?
};
let next_tick_sqrt_price: u128 = tick_index_to_sqrt_price(next_tick_index.into()).into();
let target_sqrt_price = if a_to_b {
next_tick_sqrt_price.max(sqrt_price_limit)
} else {
next_tick_sqrt_price.min(sqrt_price_limit)
};
let step_quote = compute_swap_step(
amount_remaining,
whirlpool.fee_rate,
current_liquidity,
current_sqrt_price,
target_sqrt_price,
a_to_b,
specified_input,
)?;
trade_fee += step_quote.fee_amount;
if specified_input {
amount_remaining = amount_remaining
.checked_sub(step_quote.amount_in)
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_sub(step_quote.fee_amount)
.ok_or(ARITHMETIC_OVERFLOW)?;
amount_calculated = amount_calculated
.checked_add(step_quote.amount_out)
.ok_or(ARITHMETIC_OVERFLOW)?;
} else {
amount_remaining = amount_remaining
.checked_sub(step_quote.amount_out)
.ok_or(ARITHMETIC_OVERFLOW)?;
amount_calculated = amount_calculated
.checked_add(step_quote.amount_in)
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_add(step_quote.fee_amount)
.ok_or(ARITHMETIC_OVERFLOW)?;
}
if step_quote.next_sqrt_price == next_tick_sqrt_price {
current_liquidity = get_next_liquidity(current_liquidity, next_tick, a_to_b);
current_tick_index = if a_to_b {
next_tick_index - 1
} else {
next_tick_index
}
} else if step_quote.next_sqrt_price != current_sqrt_price {
current_tick_index = sqrt_price_to_tick_index(step_quote.next_sqrt_price.into()).into();
}
current_sqrt_price = step_quote.next_sqrt_price;
}
let swapped_amount = token_amount - amount_remaining;
let token_a = if a_to_b == specified_input {
swapped_amount
} else {
amount_calculated
};
let token_b = if a_to_b == specified_input {
amount_calculated
} else {
swapped_amount
};
Ok(SwapResult {
token_a,
token_b,
trade_fee,
})
}
// Private functions
fn get_next_liquidity(
current_liquidity: u128,
next_tick: Option<&TickFacade>,
a_to_b: bool,
) -> u128 {
let liquidity_net = next_tick.map(|tick| tick.liquidity_net).unwrap_or(0);
let liquidity_net_unsigned = liquidity_net.unsigned_abs();
if a_to_b {
if liquidity_net < 0 {
current_liquidity + liquidity_net_unsigned
} else {
current_liquidity - liquidity_net_unsigned
}
} else if liquidity_net < 0 {
current_liquidity - liquidity_net_unsigned
} else {
current_liquidity + liquidity_net_unsigned
}
}
struct SwapStepQuote {
amount_in: u64,
amount_out: u64,
next_sqrt_price: u128,
fee_amount: u64,
}
fn compute_swap_step(
amount_remaining: u64,
fee_rate: u16,
current_liquidity: u128,
current_sqrt_price: u128,
target_sqrt_price: u128,
a_to_b: bool,
specified_input: bool,
) -> Result<SwapStepQuote, CoreError> {
// Any error that is not AMOUNT_EXCEEDS_MAX_U64 is not recoverable
let initial_amount_fixed_delta = try_get_amount_fixed_delta(
current_sqrt_price,
target_sqrt_price,
current_liquidity,
a_to_b,
specified_input,
);
let is_initial_amount_fixed_overflow =
initial_amount_fixed_delta == Err(AMOUNT_EXCEEDS_MAX_U64);
let amount_calculated = if specified_input {
try_apply_swap_fee(amount_remaining.into(), fee_rate)?
} else {
amount_remaining
};
let next_sqrt_price =
if !is_initial_amount_fixed_overflow && initial_amount_fixed_delta? <= amount_calculated {
target_sqrt_price
} else {
try_get_next_sqrt_price(
current_sqrt_price,
current_liquidity,
amount_calculated,
a_to_b,
specified_input,
)?
};
let is_max_swap = next_sqrt_price == target_sqrt_price;
let amount_unfixed_delta = try_get_amount_unfixed_delta(
current_sqrt_price,
next_sqrt_price,
current_liquidity,
a_to_b,
specified_input,
)?;
// If the swap is not at the max, we need to readjust the amount of the fixed token we are using
let amount_fixed_delta = if !is_max_swap || is_initial_amount_fixed_overflow {
try_get_amount_fixed_delta(
current_sqrt_price,
next_sqrt_price,
current_liquidity,
a_to_b,
specified_input,
)?
} else {
initial_amount_fixed_delta?
};
let (amount_in, mut amount_out) = if specified_input {
(amount_fixed_delta, amount_unfixed_delta)
} else {
(amount_unfixed_delta, amount_fixed_delta)
};
// Cap output amount if using output
if !specified_input && amount_out > amount_remaining {
amount_out = amount_remaining;
}
let fee_amount = if specified_input && !is_max_swap {
amount_remaining - amount_in
} else {
let pre_fee_amount = try_reverse_apply_swap_fee(amount_in.into(), fee_rate)?;
pre_fee_amount - amount_in
};
Ok(SwapStepQuote {
amount_in,
amount_out,
next_sqrt_price,
fee_amount,
})
}
fn try_get_amount_fixed_delta(
current_sqrt_price: u128,
target_sqrt_price: u128,
current_liquidity: u128,
a_to_b: bool,
specified_input: bool,
) -> Result<u64, CoreError> {
if a_to_b == specified_input {
try_get_amount_delta_a(
current_sqrt_price.into(),
target_sqrt_price.into(),
current_liquidity.into(),
specified_input,
)
} else {
try_get_amount_delta_b(
current_sqrt_price.into(),
target_sqrt_price.into(),
current_liquidity.into(),
specified_input,
)
}
}
fn try_get_amount_unfixed_delta(
current_sqrt_price: u128,
target_sqrt_price: u128,
current_liquidity: u128,
a_to_b: bool,
specified_input: bool,
) -> Result<u64, CoreError> {
if specified_input == a_to_b {
try_get_amount_delta_b(
current_sqrt_price.into(),
target_sqrt_price.into(),
current_liquidity.into(),
!specified_input,
)
} else {
try_get_amount_delta_a(
current_sqrt_price.into(),
target_sqrt_price.into(),
current_liquidity.into(),
!specified_input,
)
}
}
fn try_get_next_sqrt_price(
current_sqrt_price: u128,
current_liquidity: u128,
amount_calculated: u64,
a_to_b: bool,
specified_input: bool,
) -> Result<u128, CoreError> {
if specified_input == a_to_b {
try_get_next_sqrt_price_from_a(
current_sqrt_price.into(),
current_liquidity.into(),
amount_calculated.into(),
specified_input,
)
.map(|x| x.into())
} else {
try_get_next_sqrt_price_from_b(
current_sqrt_price.into(),
current_liquidity.into(),
amount_calculated.into(),
specified_input,
)
.map(|x| x.into())
}
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use crate::{TickArrayFacade, TICK_ARRAY_SIZE};
use super::*;
fn test_whirlpool(sqrt_price: u128, sufficient_liq: bool) -> WhirlpoolFacade {
let tick_current_index = sqrt_price_to_tick_index(sqrt_price);
let liquidity = if sufficient_liq { 100000000 } else { 265000 };
WhirlpoolFacade {
tick_current_index,
fee_rate: 3000,
liquidity,
sqrt_price,
tick_spacing: 2,
..WhirlpoolFacade::default()
}
}
fn test_tick(positive: bool) -> TickFacade {
let liquidity_net = if positive { 1000 } else { -1000 };
TickFacade {
initialized: true,
liquidity_net,
..TickFacade::default()
}
}
fn test_tick_array(start_tick_index: i32) -> TickArrayFacade {
let positive_liq_net = start_tick_index < 0;
TickArrayFacade {
start_tick_index,
ticks: [test_tick(positive_liq_net); TICK_ARRAY_SIZE],
}
}
fn test_tick_arrays() -> TickArrays {
[
test_tick_array(0),
test_tick_array(176),
test_tick_array(352),
test_tick_array(-176),
test_tick_array(-352),
]
.into()
}
#[test]
fn test_exact_in_a_to_b_simple() {
let result = swap_quote_by_input_token(
1000,
true,
1000,
test_whirlpool(1 << 64, true),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_in, 1000);
assert_eq!(result.token_est_out, 996);
assert_eq!(result.token_min_out, 896);
assert_eq!(result.trade_fee, 3);
}
#[test]
fn test_exact_in_a_to_b() {
let result = swap_quote_by_input_token(
1000,
true,
1000,
test_whirlpool(1 << 64, false),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_in, 1000);
assert_eq!(result.token_est_out, 920);
assert_eq!(result.token_min_out, 828);
assert_eq!(result.trade_fee, 38);
}
#[test]
fn test_exact_in_b_to_a_simple() {
let result = swap_quote_by_input_token(
1000,
false,
1000,
test_whirlpool(1 << 64, true),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_in, 1000);
assert_eq!(result.token_est_out, 996);
assert_eq!(result.token_min_out, 896);
assert_eq!(result.trade_fee, 3);
}
#[test]
fn test_exact_in_b_to_a() {
let result = swap_quote_by_input_token(
1000,
false,
1000,
test_whirlpool(1 << 64, false),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_in, 1000);
assert_eq!(result.token_est_out, 918);
assert_eq!(result.token_min_out, 826);
assert_eq!(result.trade_fee, 39);
}
#[test]
fn test_exact_out_a_to_b_simple() {
let result = swap_quote_by_output_token(
1000,
false,
1000,
test_whirlpool(1 << 64, true),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_out, 1000);
assert_eq!(result.token_est_in, 1005);
assert_eq!(result.token_max_in, 1106);
assert_eq!(result.trade_fee, 4);
}
#[test]
fn test_exact_out_a_to_b() {
let result = swap_quote_by_output_token(
1000,
false,
1000,
test_whirlpool(1 << 64, false),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_out, 1000);
assert_eq!(result.token_est_in, 1088);
assert_eq!(result.token_max_in, 1197);
assert_eq!(result.trade_fee, 42);
}
#[test]
fn test_exact_out_b_to_a_simple() {
let result = swap_quote_by_output_token(
1000,
true,
1000,
test_whirlpool(1 << 64, true),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_out, 1000);
assert_eq!(result.token_est_in, 1005);
assert_eq!(result.token_max_in, 1106);
assert_eq!(result.trade_fee, 4);
}
#[test]
fn test_exact_out_b_to_a() {
let result = swap_quote_by_output_token(
1000,
true,
1000,
test_whirlpool(1 << 64, false),
test_tick_arrays(),
None,
None,
)
.unwrap();
assert_eq!(result.token_out, 1000);
assert_eq!(result.token_est_in, 1088);
assert_eq!(result.token_max_in, 1197);
assert_eq!(result.trade_fee, 42);
}
// TODO: add more complex tests that
// * only fill partially
// * transfer fee
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/quote/liquidity.rs
|
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use ethnum::U256;
use crate::{
order_tick_indexes, position_status, tick_index_to_sqrt_price, try_apply_transfer_fee,
try_get_max_amount_with_slippage_tolerance, try_get_min_amount_with_slippage_tolerance,
try_reverse_apply_transfer_fee, CoreError, DecreaseLiquidityQuote, IncreaseLiquidityQuote,
PositionStatus, TransferFee, AMOUNT_EXCEEDS_MAX_U64, ARITHMETIC_OVERFLOW, U128,
};
/// Calculate the quote for decreasing liquidity
///
/// # Parameters
/// - `liquidity_delta` - The amount of liquidity to decrease
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - A DecreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn decrease_liquidity_quote(
liquidity_delta: U128,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<DecreaseLiquidityQuote, CoreError> {
let liquidity_delta: u128 = liquidity_delta.into();
if liquidity_delta == 0 {
return Ok(DecreaseLiquidityQuote::default());
}
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let current_sqrt_price: u128 = current_sqrt_price.into();
let (token_est_before_fees_a, token_est_before_fees_b) =
try_get_token_estimates_from_liquidity(
liquidity_delta,
current_sqrt_price,
tick_range.tick_lower_index,
tick_range.tick_upper_index,
false,
)?;
let token_est_a =
try_apply_transfer_fee(token_est_before_fees_a, transfer_fee_a.unwrap_or_default())?;
let token_est_b =
try_apply_transfer_fee(token_est_before_fees_b, transfer_fee_b.unwrap_or_default())?;
let token_min_a =
try_get_min_amount_with_slippage_tolerance(token_est_a, slippage_tolerance_bps)?;
let token_min_b =
try_get_min_amount_with_slippage_tolerance(token_est_b, slippage_tolerance_bps)?;
Ok(DecreaseLiquidityQuote {
liquidity_delta,
token_est_a,
token_est_b,
token_min_a,
token_min_b,
})
}
/// Calculate the quote for decreasing liquidity given a token a amount
///
/// # Parameters
/// - `token_amount_a` - The amount of token a to decrease
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - A DecreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn decrease_liquidity_quote_a(
token_amount_a: u64,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<DecreaseLiquidityQuote, CoreError> {
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let token_delta_a =
try_reverse_apply_transfer_fee(token_amount_a, transfer_fee_a.unwrap_or_default())?;
if token_delta_a == 0 {
return Ok(DecreaseLiquidityQuote::default());
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let sqrt_price_lower: u128 = tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let sqrt_price_upper: u128 = tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
let position_status = position_status(
current_sqrt_price.into(),
tick_range.tick_lower_index,
tick_range.tick_upper_index,
);
let liquidity: u128 = match position_status {
PositionStatus::PriceBelowRange => {
try_get_liquidity_from_a(token_delta_a, sqrt_price_lower, sqrt_price_upper)?
}
PositionStatus::Invalid | PositionStatus::PriceAboveRange => 0,
PositionStatus::PriceInRange => {
try_get_liquidity_from_a(token_delta_a, current_sqrt_price, sqrt_price_upper)?
}
};
decrease_liquidity_quote(
liquidity.into(),
slippage_tolerance_bps,
current_sqrt_price.into(),
tick_index_1,
tick_index_2,
transfer_fee_a,
transfer_fee_b,
)
}
/// Calculate the quote for decreasing liquidity given a token b amount
///
/// # Parameters
/// - `token_amount_b` - The amount of token b to decrease
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - A DecreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn decrease_liquidity_quote_b(
token_amount_b: u64,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<DecreaseLiquidityQuote, CoreError> {
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let token_delta_b =
try_reverse_apply_transfer_fee(token_amount_b, transfer_fee_b.unwrap_or_default())?;
if token_delta_b == 0 {
return Ok(DecreaseLiquidityQuote::default());
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let sqrt_price_lower: u128 = tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let sqrt_price_upper: u128 = tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
let position_status = position_status(
current_sqrt_price.into(),
tick_range.tick_lower_index,
tick_range.tick_upper_index,
);
let liquidity: u128 = match position_status {
PositionStatus::Invalid | PositionStatus::PriceBelowRange => 0,
PositionStatus::PriceAboveRange => {
try_get_liquidity_from_b(token_delta_b, sqrt_price_lower, sqrt_price_upper)?
}
PositionStatus::PriceInRange => {
try_get_liquidity_from_b(token_delta_b, sqrt_price_lower, current_sqrt_price)?
}
};
decrease_liquidity_quote(
liquidity.into(),
slippage_tolerance_bps,
current_sqrt_price.into(),
tick_index_1,
tick_index_2,
transfer_fee_a,
transfer_fee_b,
)
}
/// Calculate the quote for increasing liquidity
///
/// # Parameters
/// - `liquidity_delta` - The amount of liquidity to increase
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - An IncreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn increase_liquidity_quote(
liquidity_delta: U128,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<IncreaseLiquidityQuote, CoreError> {
let liquidity_delta: u128 = liquidity_delta.into();
if liquidity_delta == 0 {
return Ok(IncreaseLiquidityQuote::default());
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let (token_est_before_fees_a, token_est_before_fees_b) =
try_get_token_estimates_from_liquidity(
liquidity_delta,
current_sqrt_price,
tick_range.tick_lower_index,
tick_range.tick_upper_index,
true,
)?;
let token_est_a = try_reverse_apply_transfer_fee(
token_est_before_fees_a,
transfer_fee_a.unwrap_or_default(),
)?;
let token_est_b = try_reverse_apply_transfer_fee(
token_est_before_fees_b,
transfer_fee_b.unwrap_or_default(),
)?;
let token_max_a =
try_get_max_amount_with_slippage_tolerance(token_est_a, slippage_tolerance_bps)?;
let token_max_b =
try_get_max_amount_with_slippage_tolerance(token_est_b, slippage_tolerance_bps)?;
Ok(IncreaseLiquidityQuote {
liquidity_delta,
token_est_a,
token_est_b,
token_max_a,
token_max_b,
})
}
/// Calculate the quote for increasing liquidity given a token a amount
///
/// # Parameters
/// - `token_amount_a` - The amount of token a to increase
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - An IncreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn increase_liquidity_quote_a(
token_amount_a: u64,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<IncreaseLiquidityQuote, CoreError> {
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let token_delta_a = try_apply_transfer_fee(token_amount_a, transfer_fee_a.unwrap_or_default())?;
if token_delta_a == 0 {
return Ok(IncreaseLiquidityQuote::default());
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let sqrt_price_lower: u128 = tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let sqrt_price_upper: u128 = tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
let position_status = position_status(current_sqrt_price.into(), tick_index_1, tick_index_2);
let liquidity: u128 = match position_status {
PositionStatus::PriceBelowRange => {
try_get_liquidity_from_a(token_delta_a, sqrt_price_lower, sqrt_price_upper)?
}
PositionStatus::Invalid | PositionStatus::PriceAboveRange => 0,
PositionStatus::PriceInRange => {
try_get_liquidity_from_a(token_delta_a, current_sqrt_price, sqrt_price_upper)?
}
};
increase_liquidity_quote(
liquidity.into(),
slippage_tolerance_bps,
current_sqrt_price.into(),
tick_index_1,
tick_index_2,
transfer_fee_a,
transfer_fee_b,
)
}
/// Calculate the quote for increasing liquidity given a token b amount
///
/// # Parameters
/// - `token_amount_b` - The amount of token b to increase
/// - `slippage_tolerance` - The slippage tolerance in bps
/// - `current_sqrt_price` - The current sqrt price of the pool
/// - `tick_index_1` - The first tick index of the position
/// - `tick_index_2` - The second tick index of the position
/// - `transfer_fee_a` - The transfer fee for token A in bps
/// - `transfer_fee_b` - The transfer fee for token B in bps
///
/// # Returns
/// - An IncreaseLiquidityQuote struct containing the estimated token amounts
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn increase_liquidity_quote_b(
token_amount_b: u64,
slippage_tolerance_bps: u16,
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<IncreaseLiquidityQuote, CoreError> {
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let token_delta_b = try_apply_transfer_fee(token_amount_b, transfer_fee_b.unwrap_or_default())?;
if token_delta_b == 0 {
return Ok(IncreaseLiquidityQuote::default());
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let sqrt_price_lower: u128 = tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let sqrt_price_upper: u128 = tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
let position_status = position_status(current_sqrt_price.into(), tick_index_1, tick_index_2);
let liquidity: u128 = match position_status {
PositionStatus::Invalid | PositionStatus::PriceBelowRange => 0,
PositionStatus::PriceAboveRange => {
try_get_liquidity_from_b(token_delta_b, sqrt_price_lower, sqrt_price_upper)?
}
PositionStatus::PriceInRange => {
try_get_liquidity_from_b(token_delta_b, sqrt_price_lower, current_sqrt_price)?
}
};
increase_liquidity_quote(
liquidity.into(),
slippage_tolerance_bps,
current_sqrt_price.into(),
tick_index_1,
tick_index_2,
transfer_fee_a,
transfer_fee_b,
)
}
// Private functions
fn try_get_liquidity_from_a(
token_delta_a: u64,
sqrt_price_lower: u128,
sqrt_price_upper: u128,
) -> Result<u128, CoreError> {
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let mul: U256 = <U256>::from(token_delta_a)
.checked_mul(sqrt_price_lower.into())
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_mul(sqrt_price_upper.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let result: U256 = (mul / sqrt_price_diff) >> 64;
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
fn try_get_token_a_from_liquidity(
liquidity_delta: u128,
sqrt_price_lower: u128,
sqrt_price_upper: u128,
round_up: bool,
) -> Result<u64, CoreError> {
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let numerator: U256 = <U256>::from(liquidity_delta)
.checked_mul(sqrt_price_diff.into())
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let denominator = <U256>::from(sqrt_price_upper)
.checked_mul(<U256>::from(sqrt_price_lower))
.ok_or(ARITHMETIC_OVERFLOW)?;
let quotient = numerator / denominator;
let remainder = numerator % denominator;
if round_up && remainder != 0 {
(quotient + 1)
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
} else {
quotient.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
}
fn try_get_liquidity_from_b(
token_delta_b: u64,
sqrt_price_lower: u128,
sqrt_price_upper: u128,
) -> Result<u128, CoreError> {
let numerator: U256 = <U256>::from(token_delta_b)
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let result = numerator / <U256>::from(sqrt_price_diff);
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
fn try_get_token_b_from_liquidity(
liquidity_delta: u128,
sqrt_price_lower: u128,
sqrt_price_upper: u128,
round_up: bool,
) -> Result<u64, CoreError> {
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let mul: U256 = <U256>::from(liquidity_delta)
.checked_mul(sqrt_price_diff.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let result: U256 = mul >> 64;
if round_up && mul & <U256>::from(u64::MAX) > 0 {
(result + 1).try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
} else {
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
}
fn try_get_token_estimates_from_liquidity(
liquidity_delta: u128,
current_sqrt_price: u128,
tick_lower_index: i32,
tick_upper_index: i32,
round_up: bool,
) -> Result<(u64, u64), CoreError> {
if liquidity_delta == 0 {
return Ok((0, 0));
}
let sqrt_price_lower = tick_index_to_sqrt_price(tick_lower_index).into();
let sqrt_price_upper = tick_index_to_sqrt_price(tick_upper_index).into();
let position_status = position_status(
current_sqrt_price.into(),
tick_lower_index,
tick_upper_index,
);
match position_status {
PositionStatus::PriceBelowRange => {
let token_a = try_get_token_a_from_liquidity(
liquidity_delta,
sqrt_price_lower,
sqrt_price_upper,
round_up,
)?;
Ok((token_a, 0))
}
PositionStatus::PriceInRange => {
let token_a = try_get_token_a_from_liquidity(
liquidity_delta,
current_sqrt_price,
sqrt_price_upper,
round_up,
)?;
let token_b = try_get_token_b_from_liquidity(
liquidity_delta,
sqrt_price_lower,
current_sqrt_price,
round_up,
)?;
Ok((token_a, token_b))
}
PositionStatus::PriceAboveRange => {
let token_b = try_get_token_b_from_liquidity(
liquidity_delta,
sqrt_price_lower,
sqrt_price_upper,
round_up,
)?;
Ok((0, token_b))
}
PositionStatus::Invalid => Ok((0, 0)),
}
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
#[test]
fn test_decrease_liquidity_quote() {
// Below range
let result =
decrease_liquidity_quote(1000000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 999);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 989);
assert_eq!(result.token_min_b, 0);
// in range
let result =
decrease_liquidity_quote(1000000, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 499);
assert_eq!(result.token_est_b, 499);
assert_eq!(result.token_min_a, 494);
assert_eq!(result.token_min_b, 494);
// Above range
let result =
decrease_liquidity_quote(1000000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 999);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 989);
// zero liquidity
let result =
decrease_liquidity_quote(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_decrease_liquidity_quote_a() {
// Below range
let result =
decrease_liquidity_quote_a(1000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000049);
assert_eq!(result.token_est_a, 999);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 989);
assert_eq!(result.token_min_b, 0);
// in range
let result =
decrease_liquidity_quote_a(500, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000300);
assert_eq!(result.token_est_a, 499);
assert_eq!(result.token_est_b, 499);
assert_eq!(result.token_min_a, 494);
assert_eq!(result.token_min_b, 494);
// Above range
let result =
decrease_liquidity_quote_a(1000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
// zero liquidity
let result =
decrease_liquidity_quote_a(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_decrease_liquidity_quote_b() {
// Below range
let result =
decrease_liquidity_quote_b(1000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
// in range
let result =
decrease_liquidity_quote_b(500, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000300);
assert_eq!(result.token_est_a, 499);
assert_eq!(result.token_est_b, 499);
assert_eq!(result.token_min_a, 494);
assert_eq!(result.token_min_b, 494);
// Above range
let result =
decrease_liquidity_quote_b(1000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000049);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 999);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 989);
// zero liquidity
let result =
decrease_liquidity_quote_b(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_increase_liquidity_quote() {
// Below range
let result =
increase_liquidity_quote(1000000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 1000);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 1010);
assert_eq!(result.token_max_b, 0);
// in range
let result =
increase_liquidity_quote(1000000, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 500);
assert_eq!(result.token_est_b, 500);
assert_eq!(result.token_max_a, 505);
assert_eq!(result.token_max_b, 505);
// Above range
let result =
increase_liquidity_quote(1000000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 1000);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 1010);
// zero liquidity
let result =
increase_liquidity_quote(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
#[test]
fn test_increase_liquidity_quote_a() {
// Below range
let result =
increase_liquidity_quote_a(1000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000049);
assert_eq!(result.token_est_a, 1000);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 1010);
assert_eq!(result.token_max_b, 0);
// in range
let result =
increase_liquidity_quote_a(500, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000300);
assert_eq!(result.token_est_a, 500);
assert_eq!(result.token_est_b, 500);
assert_eq!(result.token_max_a, 505);
assert_eq!(result.token_max_b, 505);
// Above range
let result =
increase_liquidity_quote_a(1000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
// zero liquidity
let result =
increase_liquidity_quote_a(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
#[test]
fn test_increase_liquidity_quote_b() {
// Below range
let result =
increase_liquidity_quote_b(1000, 100, 18354745142194483561, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
// in range
let result =
increase_liquidity_quote_b(500, 100, 18446744073709551616, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000300);
assert_eq!(result.token_est_a, 500);
assert_eq!(result.token_est_b, 500);
assert_eq!(result.token_max_a, 505);
assert_eq!(result.token_max_b, 505);
// Above range
let result =
increase_liquidity_quote_b(1000, 100, 18539204128674405812, -10, 10, None, None)
.unwrap();
assert_eq!(result.liquidity_delta, 1000049);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 1000);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 1010);
// zero liquidity
let result =
increase_liquidity_quote_b(0, 100, 18446744073709551616, -10, 10, None, None).unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
#[test]
fn test_decrease_liquidity_quote_with_fee() {
// Below range
let result = decrease_liquidity_quote(
1000000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 799);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 791);
assert_eq!(result.token_min_b, 0);
// in range
let result = decrease_liquidity_quote(
1000000,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 399);
assert_eq!(result.token_est_b, 449);
assert_eq!(result.token_min_a, 395);
assert_eq!(result.token_min_b, 444);
// Above range
let result = decrease_liquidity_quote(
1000000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 899);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 890);
// zero liquidity
let result = decrease_liquidity_quote(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_decrease_liquidity_quote_a_with_fee() {
// Below range
let result = decrease_liquidity_quote_a(
1000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1250062);
assert_eq!(result.token_est_a, 999);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 989);
assert_eq!(result.token_min_b, 0);
// in range
let result = decrease_liquidity_quote_a(
500,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1250375);
assert_eq!(result.token_est_a, 499);
assert_eq!(result.token_est_b, 561);
assert_eq!(result.token_min_a, 494);
assert_eq!(result.token_min_b, 555);
// Above range
let result = decrease_liquidity_quote_a(
1000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
// zero liquidity
let result = decrease_liquidity_quote_a(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_decrease_liquidity_quote_b_with_fee() {
// Below range
let result = decrease_liquidity_quote_b(
1000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
// in range
let result = decrease_liquidity_quote_b(
500,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1112333);
assert_eq!(result.token_est_a, 444);
assert_eq!(result.token_est_b, 499);
assert_eq!(result.token_min_a, 439);
assert_eq!(result.token_min_b, 494);
// Above range
let result = decrease_liquidity_quote_b(
1000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1112055);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 999);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 989);
// zero liquidity
let result = decrease_liquidity_quote_b(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_min_a, 0);
assert_eq!(result.token_min_b, 0);
}
#[test]
fn test_increase_liquidity_quote_with_fee() {
// Below range
let result = increase_liquidity_quote(
1000000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 1250);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 1263);
assert_eq!(result.token_max_b, 0);
// in range
let result = increase_liquidity_quote(
1000000,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 625);
assert_eq!(result.token_est_b, 556);
assert_eq!(result.token_max_a, 632);
assert_eq!(result.token_max_b, 562);
// Above range
let result = increase_liquidity_quote(
1000000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 1000000);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 1112);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 1124);
// zero liquidity
let result = increase_liquidity_quote(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
#[test]
fn test_increase_liquidity_quote_a_with_fee() {
// Below range
let result = increase_liquidity_quote_a(
1000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 800039);
assert_eq!(result.token_est_a, 1000);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 1010);
assert_eq!(result.token_max_b, 0);
// in range
let result = increase_liquidity_quote_a(
500,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 800240);
assert_eq!(result.token_est_a, 500);
assert_eq!(result.token_est_b, 445);
assert_eq!(result.token_max_a, 505);
assert_eq!(result.token_max_b, 450);
// Above range
let result = increase_liquidity_quote_a(
1000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
// zero liquidity
let result = increase_liquidity_quote_a(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
#[test]
fn test_increase_liquidity_quote_b_with_fee() {
// Below range
let result = increase_liquidity_quote_b(
1000,
100,
18354745142194483561,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
// in range
let result = increase_liquidity_quote_b(
500,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 900270);
assert_eq!(result.token_est_a, 563);
assert_eq!(result.token_est_b, 500);
assert_eq!(result.token_max_a, 569);
assert_eq!(result.token_max_b, 505);
// Above range
let result = increase_liquidity_quote_b(
1000,
100,
18539204128674405812,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 900044);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 1000);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 1010);
// zero liquidity
let result = increase_liquidity_quote_b(
0,
100,
18446744073709551616,
-10,
10,
Some(TransferFee::new(2000)),
Some(TransferFee::new(1000)),
)
.unwrap();
assert_eq!(result.liquidity_delta, 0);
assert_eq!(result.token_est_a, 0);
assert_eq!(result.token_est_b, 0);
assert_eq!(result.token_max_a, 0);
assert_eq!(result.token_max_b, 0);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/quote/fees.rs
|
use ethnum::U256;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::{
try_apply_transfer_fee, CollectFeesQuote, CoreError, PositionFacade, TickFacade, TransferFee,
WhirlpoolFacade, AMOUNT_EXCEEDS_MAX_U64, ARITHMETIC_OVERFLOW,
};
/// Calculate fees owed for a position
///
/// # Paramters
/// - `whirlpool`: The whirlpool state
/// - `position`: The position state
/// - `tick_lower`: The lower tick state
/// - `tick_upper`: The upper tick state
/// - `transfer_fee_a`: The transfer fee for token A
/// - `transfer_fee_b`: The transfer fee for token B
///
/// # Returns
/// - `CollectFeesQuote`: The fees owed for token A and token B
#[allow(clippy::too_many_arguments)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn collect_fees_quote(
whirlpool: WhirlpoolFacade,
position: PositionFacade,
tick_lower: TickFacade,
tick_upper: TickFacade,
transfer_fee_a: Option<TransferFee>,
transfer_fee_b: Option<TransferFee>,
) -> Result<CollectFeesQuote, CoreError> {
let mut fee_growth_below_a: u128 = tick_lower.fee_growth_outside_a;
let mut fee_growth_above_a: u128 = tick_upper.fee_growth_outside_a;
let mut fee_growth_below_b: u128 = tick_lower.fee_growth_outside_b;
let mut fee_growth_above_b: u128 = tick_upper.fee_growth_outside_b;
if whirlpool.tick_current_index < position.tick_lower_index {
fee_growth_below_a = whirlpool
.fee_growth_global_a
.wrapping_sub(fee_growth_below_a);
fee_growth_below_b = whirlpool
.fee_growth_global_b
.wrapping_sub(fee_growth_below_b);
}
if whirlpool.tick_current_index >= position.tick_upper_index {
fee_growth_above_a = whirlpool
.fee_growth_global_a
.wrapping_sub(fee_growth_above_a);
fee_growth_above_b = whirlpool
.fee_growth_global_b
.wrapping_sub(fee_growth_above_b);
}
let fee_growth_inside_a = whirlpool
.fee_growth_global_a
.wrapping_sub(fee_growth_below_a)
.wrapping_sub(fee_growth_above_a);
let fee_growth_inside_b = whirlpool
.fee_growth_global_b
.wrapping_sub(fee_growth_below_b)
.wrapping_sub(fee_growth_above_b);
let fee_owed_delta_a: U256 = <U256>::from(fee_growth_inside_a)
.wrapping_sub(position.fee_growth_checkpoint_a.into())
.checked_mul(position.liquidity.into())
.ok_or(ARITHMETIC_OVERFLOW)?
>> 64;
let fee_owed_delta_b: U256 = <U256>::from(fee_growth_inside_b)
.wrapping_sub(position.fee_growth_checkpoint_b.into())
.checked_mul(position.liquidity.into())
.ok_or(ARITHMETIC_OVERFLOW)?
>> 64;
let fee_owed_delta_a: u64 = fee_owed_delta_a
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)?;
let fee_owed_delta_b: u64 = fee_owed_delta_b
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)?;
let withdrawable_fee_a = position.fee_owed_a + fee_owed_delta_a;
let withdrawable_fee_b = position.fee_owed_b + fee_owed_delta_b;
let fee_owed_a =
try_apply_transfer_fee(withdrawable_fee_a, transfer_fee_a.unwrap_or_default())?;
let fee_owed_b =
try_apply_transfer_fee(withdrawable_fee_b, transfer_fee_b.unwrap_or_default())?;
Ok(CollectFeesQuote {
fee_owed_a,
fee_owed_b,
})
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
fn test_whirlpool(tick_index: i32) -> WhirlpoolFacade {
WhirlpoolFacade {
tick_current_index: tick_index,
fee_growth_global_a: 800,
fee_growth_global_b: 1000,
..WhirlpoolFacade::default()
}
}
fn test_position() -> PositionFacade {
PositionFacade {
liquidity: 10000000000000000000,
tick_lower_index: 5,
tick_upper_index: 10,
fee_growth_checkpoint_a: 0,
fee_owed_a: 400,
fee_growth_checkpoint_b: 0,
fee_owed_b: 600,
..PositionFacade::default()
}
}
fn test_tick() -> TickFacade {
TickFacade {
fee_growth_outside_a: 50,
fee_growth_outside_b: 20,
..TickFacade::default()
}
}
#[test]
fn test_collect_out_of_range_lower() {
let result = collect_fees_quote(
test_whirlpool(0),
test_position(),
test_tick(),
test_tick(),
None,
None,
)
.unwrap();
assert_eq!(result.fee_owed_a, 400);
assert_eq!(result.fee_owed_b, 600);
}
#[test]
fn test_in_range() {
let result = collect_fees_quote(
test_whirlpool(7),
test_position(),
test_tick(),
test_tick(),
None,
None,
)
.unwrap();
assert_eq!(result.fee_owed_a, 779);
assert_eq!(result.fee_owed_b, 1120);
}
#[test]
fn test_collect_out_of_range_upper() {
let result = collect_fees_quote(
test_whirlpool(15),
test_position(),
test_tick(),
test_tick(),
None,
None,
)
.unwrap();
assert_eq!(result.fee_owed_a, 400);
assert_eq!(result.fee_owed_b, 600);
}
#[test]
fn test_collect_on_range_lower() {
let result = collect_fees_quote(
test_whirlpool(5),
test_position(),
test_tick(),
test_tick(),
None,
None,
)
.unwrap();
assert_eq!(result.fee_owed_a, 779);
assert_eq!(result.fee_owed_b, 1120);
}
#[test]
fn test_collect_on_upper() {
let result = collect_fees_quote(
test_whirlpool(10),
test_position(),
test_tick(),
test_tick(),
None,
None,
)
.unwrap();
assert_eq!(result.fee_owed_a, 400);
assert_eq!(result.fee_owed_b, 600);
}
#[test]
fn test_collect_transfer_fee() {
let result = collect_fees_quote(
test_whirlpool(7),
test_position(),
test_tick(),
test_tick(),
Some(TransferFee::new(2000)),
Some(TransferFee::new(5000)),
)
.unwrap();
assert_eq!(result.fee_owed_a, 623);
assert_eq!(result.fee_owed_b, 560);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/quote/mod.rs
|
mod fees;
mod liquidity;
mod rewards;
mod swap;
pub use fees::*;
pub use liquidity::*;
pub use rewards::*;
pub use swap::*;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/quote/rewards.rs
|
use ethnum::U256;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::{
try_apply_transfer_fee, CollectRewardQuote, CollectRewardsQuote, CoreError, PositionFacade,
TickFacade, TransferFee, WhirlpoolFacade, AMOUNT_EXCEEDS_MAX_U64, ARITHMETIC_OVERFLOW,
NUM_REWARDS,
};
/// Calculate rewards owed for a position
///
/// # Paramters
/// - `whirlpool`: The whirlpool state
/// - `position`: The position state
/// - `tick_lower`: The lower tick state
/// - `tick_upper`: The upper tick state
/// - `current_timestamp`: The current timestamp
/// - `transfer_fee_1`: The transfer fee for token 1
/// - `transfer_fee_2`: The transfer fee for token 2
/// - `transfer_fee_3`: The transfer fee for token 3
///
/// # Returns
/// - `CollectRewardsQuote`: The rewards owed for the 3 reward tokens.
#[allow(clippy::too_many_arguments)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn collect_rewards_quote(
whirlpool: WhirlpoolFacade,
position: PositionFacade,
tick_lower: TickFacade,
tick_upper: TickFacade,
current_timestamp: u64,
transfer_fee_1: Option<TransferFee>,
transfer_fee_2: Option<TransferFee>,
transfer_fee_3: Option<TransferFee>,
) -> Result<CollectRewardsQuote, CoreError> {
let timestamp_delta = current_timestamp - whirlpool.reward_last_updated_timestamp;
let transfer_fees = [transfer_fee_1, transfer_fee_2, transfer_fee_3];
let mut reward_quotes: [CollectRewardQuote; NUM_REWARDS] =
[CollectRewardQuote::default(); NUM_REWARDS];
for i in 0..NUM_REWARDS {
let mut reward_growth: u128 = whirlpool.reward_infos[i].growth_global_x64;
if whirlpool.liquidity != 0 {
let reward_growth_delta = whirlpool.reward_infos[i]
.emissions_per_second_x64
.checked_mul(timestamp_delta as u128)
.ok_or(ARITHMETIC_OVERFLOW)?
/ whirlpool.liquidity;
reward_growth += <u128>::try_from(reward_growth_delta).unwrap();
}
let mut reward_growth_below = tick_lower.reward_growths_outside[i];
let mut reward_growth_above = tick_upper.reward_growths_outside[i];
if whirlpool.tick_current_index < position.tick_lower_index {
reward_growth_below = reward_growth.wrapping_sub(reward_growth_below);
}
if whirlpool.tick_current_index >= position.tick_upper_index {
reward_growth_above = reward_growth.wrapping_sub(reward_growth_above);
}
let reward_growth_inside = reward_growth
.wrapping_sub(reward_growth_below)
.wrapping_sub(reward_growth_above);
let reward_growth_delta: u64 = <U256>::from(reward_growth_inside)
.wrapping_sub(position.reward_infos[i].growth_inside_checkpoint.into())
.checked_mul(position.liquidity.into())
.ok_or(ARITHMETIC_OVERFLOW)?
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)?;
let withdrawable_reward = position.reward_infos[i].amount_owed + reward_growth_delta;
let rewards_owed =
try_apply_transfer_fee(withdrawable_reward, transfer_fees[i].unwrap_or_default())?;
reward_quotes[i] = CollectRewardQuote { rewards_owed }
}
Ok(CollectRewardsQuote {
rewards: reward_quotes,
})
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use crate::{PositionRewardInfoFacade, WhirlpoolRewardInfoFacade};
use super::*;
fn test_whirlpool(tick_current_index: i32) -> WhirlpoolFacade {
WhirlpoolFacade {
tick_current_index,
reward_last_updated_timestamp: 0,
reward_infos: [
WhirlpoolRewardInfoFacade {
growth_global_x64: 500,
emissions_per_second_x64: 1,
},
WhirlpoolRewardInfoFacade {
growth_global_x64: 600,
emissions_per_second_x64: 2,
},
WhirlpoolRewardInfoFacade {
growth_global_x64: 700,
emissions_per_second_x64: 3,
},
],
liquidity: 50,
..WhirlpoolFacade::default()
}
}
fn test_position() -> PositionFacade {
PositionFacade {
liquidity: 50,
tick_lower_index: 5,
tick_upper_index: 10,
reward_infos: [
PositionRewardInfoFacade {
growth_inside_checkpoint: 0,
amount_owed: 100,
},
PositionRewardInfoFacade {
growth_inside_checkpoint: 0,
amount_owed: 200,
},
PositionRewardInfoFacade {
growth_inside_checkpoint: 0,
amount_owed: 300,
},
],
..PositionFacade::default()
}
}
fn test_tick() -> TickFacade {
TickFacade {
reward_growths_outside: [10, 20, 30],
..TickFacade::default()
}
}
#[test]
fn test_collect_rewards_below_range() {
let quote = collect_rewards_quote(
test_whirlpool(0),
test_position(),
test_tick(),
test_tick(),
10,
None,
None,
None,
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(100));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(200));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(300));
}
#[test]
fn test_collect_rewards_in_range() {
let quote = collect_rewards_quote(
test_whirlpool(7),
test_position(),
test_tick(),
test_tick(),
10,
None,
None,
None,
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(24100));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(28200));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(32300));
}
#[test]
fn test_collect_rewards_above_range() {
let quote = collect_rewards_quote(
test_whirlpool(15),
test_position(),
test_tick(),
test_tick(),
10,
None,
None,
None,
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(100));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(200));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(300));
}
#[test]
fn test_collect_rewards_on_range_lower() {
let quote = collect_rewards_quote(
test_whirlpool(5),
test_position(),
test_tick(),
test_tick(),
10,
None,
None,
None,
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(24100));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(28200));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(32300));
}
#[test]
fn test_collect_rewards_on_range_upper() {
let quote = collect_rewards_quote(
test_whirlpool(10),
test_position(),
test_tick(),
test_tick(),
10,
None,
None,
None,
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(100));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(200));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(300));
}
#[test]
fn test_transfer_fee() {
let quote = collect_rewards_quote(
test_whirlpool(7),
test_position(),
test_tick(),
test_tick(),
10,
Some(TransferFee::new(1000)),
Some(TransferFee::new(2000)),
Some(TransferFee::new(3000)),
);
assert_eq!(quote.map(|x| x.rewards[0].rewards_owed), Ok(21690));
assert_eq!(quote.map(|x| x.rewards[1].rewards_owed), Ok(22560));
assert_eq!(quote.map(|x| x.rewards[2].rewards_owed), Ok(22610));
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/swap.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// The denominator of the fee rate value.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const FEE_RATE_DENOMINATOR: u32 = 1_000_000;
// TODO: WASM export (which doesn't work with u128 yet)
/// The minimum sqrt price for a whirlpool.
pub const MIN_SQRT_PRICE: u128 = 4295048016;
/// The maximum sqrt price for a whirlpool.
pub const MAX_SQRT_PRICE: u128 = 79226673515401279992447579055;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/error.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
pub type CoreError = &'static str;
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const TICK_ARRAY_NOT_EVENLY_SPACED: CoreError = "Tick array not evenly spaced";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const TICK_INDEX_OUT_OF_BOUNDS: CoreError = "Tick index out of bounds";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const INVALID_TICK_INDEX: CoreError = "Invalid tick index";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const ARITHMETIC_OVERFLOW: CoreError = "Arithmetic over- or underflow";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const AMOUNT_EXCEEDS_MAX_U64: CoreError = "Amount exceeds max u64";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const SQRT_PRICE_OUT_OF_BOUNDS: CoreError = "Sqrt price out of bounds";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const TICK_SEQUENCE_EMPTY: CoreError = "Tick sequence empty";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const SQRT_PRICE_LIMIT_OUT_OF_BOUNDS: CoreError = "Sqrt price limit out of bounds";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const INVALID_SQRT_PRICE_LIMIT_DIRECTION: CoreError = "Invalid sqrt price limit direction";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const ZERO_TRADABLE_AMOUNT: CoreError = "Zero tradable amount";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const INVALID_TIMESTAMP: CoreError = "Invalid timestamp";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const INVALID_TRANSFER_FEE: CoreError = "Invalid transfer fee";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const INVALID_SLIPPAGE_TOLERANCE: CoreError = "Invalid slippage tolerance";
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const TICK_INDEX_NOT_IN_ARRAY: CoreError = "Tick index not in array";
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/token.rs
|
pub const BPS_DENOMINATOR: u16 = 10000;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/bundle.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// The maximum number of positions in a position bundle.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const POSITION_BUNDLE_SIZE: usize = 256;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/mod.rs
|
mod bundle;
mod error;
mod pool;
mod swap;
mod tick;
mod token;
pub use bundle::*;
pub use error::*;
pub use pool::*;
pub use swap::*;
pub use tick::*;
pub use token::*;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/pool.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// The number of reward tokens in a pool.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const NUM_REWARDS: usize = 3;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/constants/tick.rs
|
#![allow(non_snake_case)]
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// The number of ticks in a tick array.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const TICK_ARRAY_SIZE: usize = 88;
/// Pools with tick spacing above this threshold are considered full range only.
/// This means the program rejects any non-full range positions in these pools.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD: u16 = 32768; // 2^15
/// The minimum tick index.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const MIN_TICK_INDEX: i32 = -443636;
/// The maximum tick index.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub const MAX_TICK_INDEX: i32 = 443636;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/token.rs
|
use crate::{
CoreError, TransferFee, AMOUNT_EXCEEDS_MAX_U64, ARITHMETIC_OVERFLOW, BPS_DENOMINATOR,
FEE_RATE_DENOMINATOR, INVALID_SLIPPAGE_TOLERANCE, INVALID_TRANSFER_FEE, MAX_SQRT_PRICE,
MIN_SQRT_PRICE, SQRT_PRICE_OUT_OF_BOUNDS, U128,
};
use ethnum::U256;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
/// Calculate the amount A delta between two sqrt_prices
///
/// # Parameters
/// - `sqrt_price_1`: The first square root price
/// - `sqrt_price_2`: The second square root price
/// - `liquidity`: The liquidity
/// - `round_up`: Whether to round up or not
///
/// # Returns
/// - `u64`: The amount delta
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_amount_delta_a(
sqrt_price_1: U128,
sqrt_price_2: U128,
liquidity: U128,
round_up: bool,
) -> Result<u64, CoreError> {
let (sqrt_price_lower, sqrt_price_upper) =
order_prices(sqrt_price_1.into(), sqrt_price_2.into());
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let numerator: U256 = <U256>::from(liquidity)
.checked_mul(sqrt_price_diff.into())
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let denominator: U256 = <U256>::from(sqrt_price_lower)
.checked_mul(sqrt_price_upper.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let quotient = numerator / denominator;
let remainder = numerator % denominator;
let result = if round_up && remainder != 0 {
quotient + 1
} else {
quotient
};
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
/// Calculate the amount B delta between two sqrt_prices
///
/// # Parameters
/// - `sqrt_price_1`: The first square root price
/// - `sqrt_price_2`: The second square root price
/// - `liquidity`: The liquidity
/// - `round_up`: Whether to round up or not
///
/// # Returns
/// - `u64`: The amount delta
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_amount_delta_b(
sqrt_price_1: U128,
sqrt_price_2: U128,
liquidity: U128,
round_up: bool,
) -> Result<u64, CoreError> {
let (sqrt_price_lower, sqrt_price_upper) =
order_prices(sqrt_price_1.into(), sqrt_price_2.into());
let sqrt_price_diff = sqrt_price_upper - sqrt_price_lower;
let product: U256 = <U256>::from(liquidity)
.checked_mul(sqrt_price_diff.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let quotient: U256 = product >> 64;
let should_round = round_up && product & <U256>::from(u64::MAX) > 0;
let result = if should_round { quotient + 1 } else { quotient };
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
/// Calculate the next square root price
///
/// # Parameters
/// - `current_sqrt_price`: The current square root price
/// - `current_liquidity`: The current liquidity
/// - `amount`: The amount
/// - `specified_input`: Whether the input is specified
///
/// # Returns
/// - `u128`: The next square root price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_next_sqrt_price_from_a(
current_sqrt_price: U128,
current_liquidity: U128,
amount: u64,
specified_input: bool,
) -> Result<U128, CoreError> {
if amount == 0 {
return Ok(current_sqrt_price);
}
let current_sqrt_price: u128 = current_sqrt_price.into();
let current_liquidity: u128 = current_liquidity.into();
let p = <U256>::from(current_sqrt_price)
.checked_mul(amount.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let numerator = <U256>::from(current_liquidity)
.checked_mul(current_sqrt_price.into())
.ok_or(ARITHMETIC_OVERFLOW)?
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let current_liquidity_shifted = <U256>::from(current_liquidity)
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let denominator = if specified_input {
current_liquidity_shifted + p
} else {
current_liquidity_shifted - p
};
let quotient: U256 = numerator / denominator;
let remainder: U256 = numerator % denominator;
let result = if remainder != 0 {
quotient + 1
} else {
quotient
};
if !(MIN_SQRT_PRICE..=MAX_SQRT_PRICE).contains(&result) {
return Err(SQRT_PRICE_OUT_OF_BOUNDS);
}
Ok(result.as_u128().into())
}
/// Calculate the next square root price
///
/// # Parameters
/// - `current_sqrt_price`: The current square root price
/// - `current_liquidity`: The current liquidity
/// - `amount`: The amount
/// - `specified_input`: Whether the input is specified
///
/// # Returns
/// - `u128`: The next square root price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_next_sqrt_price_from_b(
current_sqrt_price: U128,
current_liquidity: U128,
amount: u64,
specified_input: bool,
) -> Result<U128, CoreError> {
if amount == 0 {
return Ok(current_sqrt_price);
}
let current_sqrt_price = <U256>::from(current_sqrt_price);
let current_liquidity = <U256>::from(current_liquidity);
let amount_shifted = <U256>::from(amount)
.checked_shl(64)
.ok_or(ARITHMETIC_OVERFLOW)?;
let quotient: U256 = amount_shifted / current_liquidity;
let remainder: U256 = amount_shifted % current_liquidity;
let delta = if !specified_input && remainder != 0 {
quotient + 1
} else {
quotient
};
let result = if specified_input {
current_sqrt_price + delta
} else {
current_sqrt_price - delta
};
if !(MIN_SQRT_PRICE..=MAX_SQRT_PRICE).contains(&result) {
return Err(SQRT_PRICE_OUT_OF_BOUNDS);
}
Ok(result.as_u128().into())
}
/// Apply a transfer fee to an amount
/// e.g. You send 10000 amount with 100 fee rate. The fee amount will be 100.
/// So the amount after fee will be 9900.
///
/// # Parameters
/// - `amount`: The amount to apply the fee to
/// - `transfer_fee`: The transfer fee to apply
///
/// # Returns
/// - `u64`: The amount after the fee has been applied
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_apply_transfer_fee(amount: u64, transfer_fee: TransferFee) -> Result<u64, CoreError> {
if transfer_fee.fee_bps > BPS_DENOMINATOR {
return Err(INVALID_TRANSFER_FEE);
}
if transfer_fee.fee_bps == 0 || amount == 0 {
return Ok(amount);
}
let numerator = <u128>::from(amount)
.checked_mul(transfer_fee.fee_bps.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let raw_fee: u64 = numerator
.div_ceil(BPS_DENOMINATOR.into())
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)?;
let fee_amount = raw_fee.min(transfer_fee.max_fee);
Ok(amount - fee_amount)
}
/// Reverse the application of a transfer fee to an amount
/// e.g. You received 9900 amount with 100 fee rate. The fee amount will be 100.
/// So the amount before fee will be 10000.
///
/// # Parameters
/// - `amount`: The amount to reverse the fee from
/// - `transfer_fee`: The transfer fee to reverse
///
/// # Returns
/// - `u64`: The amount before the fee has been applied
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_reverse_apply_transfer_fee(
amount: u64,
transfer_fee: TransferFee,
) -> Result<u64, CoreError> {
if transfer_fee.fee_bps > BPS_DENOMINATOR {
Err(INVALID_TRANSFER_FEE)
} else if transfer_fee.fee_bps == 0 {
Ok(amount)
} else if amount == 0 {
Ok(0)
} else if transfer_fee.fee_bps == BPS_DENOMINATOR {
amount
.checked_add(transfer_fee.max_fee)
.ok_or(AMOUNT_EXCEEDS_MAX_U64)
} else {
let numerator = <u128>::from(amount)
.checked_mul(BPS_DENOMINATOR.into())
.ok_or(ARITHMETIC_OVERFLOW)?;
let denominator = <u128>::from(BPS_DENOMINATOR) - <u128>::from(transfer_fee.fee_bps);
let raw_pre_fee_amount = numerator.div_ceil(denominator);
let fee_amount = raw_pre_fee_amount
.checked_sub(amount.into())
.ok_or(AMOUNT_EXCEEDS_MAX_U64)?;
if fee_amount >= transfer_fee.max_fee as u128 {
amount
.checked_add(transfer_fee.max_fee)
.ok_or(AMOUNT_EXCEEDS_MAX_U64)
} else {
raw_pre_fee_amount
.try_into()
.map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
}
}
/// Get the maximum amount with a slippage tolerance
/// e.g. Your estimated amount you send is 10000 with 100 slippage tolerance. The max you send will be 10100.
///
/// # Parameters
/// - `amount`: The amount to apply the fee to
/// - `slippage_tolerance_bps`: The slippage tolerance in bps (should be in range 0..BPS_DENOMINATOR)
///
/// # Returns
/// - `u64`: The maximum amount
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_max_amount_with_slippage_tolerance(
amount: u64,
slippage_tolerance_bps: u16,
) -> Result<u64, CoreError> {
if slippage_tolerance_bps > BPS_DENOMINATOR {
return Err(INVALID_SLIPPAGE_TOLERANCE);
}
let product = <u128>::from(BPS_DENOMINATOR) + <u128>::from(slippage_tolerance_bps);
let result = try_mul_div(amount, product, BPS_DENOMINATOR.into(), true)?;
Ok(result)
}
/// Get the minimum amount with a slippage tolerance
/// e.g. Your estimated amount you receive is 10000 with 100 slippage tolerance. The min amount you receive will be 9900.
///
/// # Parameters
/// - `amount`: The amount to apply the fee to
/// - `slippage_tolerance_bps`: The slippage tolerance in bps (should be in range 0..BPS_DENOMINATOR)
///
/// # Returns
/// - `u64`: The minimum amount
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_get_min_amount_with_slippage_tolerance(
amount: u64,
slippage_tolerance_bps: u16,
) -> Result<u64, CoreError> {
if slippage_tolerance_bps > BPS_DENOMINATOR {
return Err(INVALID_SLIPPAGE_TOLERANCE);
}
let product = <u128>::from(BPS_DENOMINATOR) - <u128>::from(slippage_tolerance_bps);
let result = try_mul_div(amount, product, BPS_DENOMINATOR.into(), false)?;
Ok(result)
}
/// Apply a swap fee to an amount
/// e.g. You send 10000 amount with 10000 fee rate. The fee amount will be 100.
/// So the amount after fee will be 9900.
///
/// # Parameters
/// - `amount`: The amount to apply the fee to
/// - `fee_rate`: The fee rate to apply denominated in 1e6
///
/// # Returns
/// - `u64`: The amount after the fee has been applied
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_apply_swap_fee(amount: u64, fee_rate: u16) -> Result<u64, CoreError> {
let product = <u128>::from(FEE_RATE_DENOMINATOR) - <u128>::from(fee_rate);
let result = try_mul_div(amount, product, FEE_RATE_DENOMINATOR.into(), false)?;
Ok(result)
}
/// Reverse the application of a swap fee to an amount
/// e.g. You received 9900 amount with 10000 fee rate. The fee amount will be 100.
/// So the amount before fee will be 10000.
///
/// # Parameters
/// - `amount`: The amount to reverse the fee from
/// - `fee_rate`: The fee rate to reverse denominated in 1e6
///
/// # Returns
/// - `u64`: The amount before the fee has been applied
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn try_reverse_apply_swap_fee(amount: u64, fee_rate: u16) -> Result<u64, CoreError> {
let denominator = <u128>::from(FEE_RATE_DENOMINATOR) - <u128>::from(fee_rate);
let result = try_mul_div(amount, FEE_RATE_DENOMINATOR.into(), denominator, true)?;
Ok(result)
}
// Private functions
fn try_mul_div(
amount: u64,
product: u128,
denominator: u128,
round_up: bool,
) -> Result<u64, CoreError> {
if amount == 0 || product == 0 {
return Ok(0);
}
let amount: u128 = amount.into();
let numerator = amount.checked_mul(product).ok_or(ARITHMETIC_OVERFLOW)?;
let quotient = numerator / denominator;
let remainder = numerator % denominator;
let result = if round_up && remainder != 0 {
quotient + 1
} else {
quotient
};
result.try_into().map_err(|_| AMOUNT_EXCEEDS_MAX_U64)
}
fn order_prices(a: u128, b: u128) -> (u128, u128) {
if a < b {
(a, b)
} else {
(b, a)
}
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
#[test]
fn test_get_amount_delta_a() {
assert_eq!(try_get_amount_delta_a(4 << 64, 2 << 64, 4, true), Ok(1));
assert_eq!(try_get_amount_delta_a(4 << 64, 2 << 64, 4, false), Ok(1));
assert_eq!(try_get_amount_delta_a(4 << 64, 4 << 64, 4, true), Ok(0));
assert_eq!(try_get_amount_delta_a(4 << 64, 4 << 64, 4, false), Ok(0));
}
#[test]
fn test_get_amount_delta_b() {
assert_eq!(try_get_amount_delta_b(4 << 64, 2 << 64, 4, true), Ok(8));
assert_eq!(try_get_amount_delta_b(4 << 64, 2 << 64, 4, false), Ok(8));
assert_eq!(try_get_amount_delta_b(4 << 64, 4 << 64, 4, true), Ok(0));
assert_eq!(try_get_amount_delta_b(4 << 64, 4 << 64, 4, false), Ok(0));
}
#[test]
fn test_get_next_sqrt_price_from_a() {
assert_eq!(
try_get_next_sqrt_price_from_a(4 << 64, 4, 1, true),
Ok(2 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_a(2 << 64, 4, 1, false),
Ok(4 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_a(4 << 64, 4, 0, true),
Ok(4 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_a(4 << 64, 4, 0, false),
Ok(4 << 64)
);
}
#[test]
fn test_get_next_sqrt_price_from_b() {
assert_eq!(
try_get_next_sqrt_price_from_b(2 << 64, 4, 8, true),
Ok(4 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_b(4 << 64, 4, 8, false),
Ok(2 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_b(4 << 64, 4, 0, true),
Ok(4 << 64)
);
assert_eq!(
try_get_next_sqrt_price_from_b(4 << 64, 4, 0, false),
Ok(4 << 64)
);
}
#[test]
fn test_apply_transfer_fee() {
assert_eq!(try_apply_transfer_fee(0, TransferFee::new(100)), Ok(0));
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(0)),
Ok(10000)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(100)),
Ok(9900)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(1000)),
Ok(9000)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(10000)),
Ok(0)
);
assert_eq!(
try_apply_transfer_fee(u64::MAX, TransferFee::new(1000)),
Ok(16602069666338596453)
);
assert_eq!(
try_apply_transfer_fee(u64::MAX, TransferFee::new(10000)),
Ok(0)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(10001)),
Err(INVALID_TRANSFER_FEE)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new(u16::MAX)),
Err(INVALID_TRANSFER_FEE)
);
}
#[test]
fn test_apply_transfer_fee_with_max() {
assert_eq!(
try_apply_transfer_fee(0, TransferFee::new_with_max(100, 500)),
Ok(0)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(0, 500)),
Ok(10000)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(100, 500)),
Ok(9900)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(1000, 500)),
Ok(9500)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(10000, 500)),
Ok(9500)
);
assert_eq!(
try_apply_transfer_fee(u64::MAX, TransferFee::new_with_max(1000, 500)),
Ok(18446744073709551115)
);
assert_eq!(
try_apply_transfer_fee(u64::MAX, TransferFee::new_with_max(10000, 500)),
Ok(18446744073709551115)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(10001, 500)),
Err(INVALID_TRANSFER_FEE)
);
assert_eq!(
try_apply_transfer_fee(10000, TransferFee::new_with_max(u16::MAX, 500)),
Err(INVALID_TRANSFER_FEE)
);
}
#[test]
fn test_reverse_apply_transfer_fee() {
assert_eq!(
try_reverse_apply_transfer_fee(0, TransferFee::new(100)),
Ok(0)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new(0)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(9900, TransferFee::new(100)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(9000, TransferFee::new(1000)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(5000, TransferFee::new(10000)),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
assert_eq!(
try_reverse_apply_transfer_fee(0, TransferFee::new(10000)),
Ok(0)
);
assert_eq!(
try_reverse_apply_transfer_fee(u64::MAX, TransferFee::new(10000)),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new(10001)),
Err(INVALID_TRANSFER_FEE)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new(u16::MAX)),
Err(INVALID_TRANSFER_FEE)
);
}
#[test]
fn test_reverse_apply_transfer_fee_with_max() {
assert_eq!(
try_reverse_apply_transfer_fee(0, TransferFee::new_with_max(100, 500)),
Ok(0)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new_with_max(0, 500)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(9900, TransferFee::new_with_max(100, 500)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(9500, TransferFee::new_with_max(1000, 500)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(9500, TransferFee::new_with_max(10000, 500)),
Ok(10000)
);
assert_eq!(
try_reverse_apply_transfer_fee(0, TransferFee::new_with_max(10000, 500)),
Ok(0)
);
assert_eq!(
try_reverse_apply_transfer_fee(u64::MAX - 500, TransferFee::new_with_max(10000, 500)),
Ok(u64::MAX)
);
assert_eq!(
try_reverse_apply_transfer_fee(u64::MAX, TransferFee::new_with_max(10000, 500)),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new_with_max(10001, 500)),
Err(INVALID_TRANSFER_FEE)
);
assert_eq!(
try_reverse_apply_transfer_fee(10000, TransferFee::new_with_max(u16::MAX, 500)),
Err(INVALID_TRANSFER_FEE)
);
}
#[test]
fn test_get_max_amount_with_slippage_tolerance() {
assert_eq!(try_get_max_amount_with_slippage_tolerance(0, 100), Ok(0));
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, 0),
Ok(10000)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, 100),
Ok(10100)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, 1000),
Ok(11000)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, 10000),
Ok(20000)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(u64::MAX, 10000),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, 10001),
Err(INVALID_SLIPPAGE_TOLERANCE)
);
assert_eq!(
try_get_max_amount_with_slippage_tolerance(10000, u16::MAX),
Err(INVALID_SLIPPAGE_TOLERANCE)
);
}
#[test]
fn test_get_min_amount_with_slippage_tolerance() {
assert_eq!(try_get_min_amount_with_slippage_tolerance(0, 100), Ok(0));
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, 0),
Ok(10000)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, 100),
Ok(9900)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, 1000),
Ok(9000)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, 10000),
Ok(0)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(u64::MAX, 10000),
Ok(0)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(u64::MAX, 1000),
Ok(16602069666338596453)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, 10001),
Err(INVALID_SLIPPAGE_TOLERANCE)
);
assert_eq!(
try_get_min_amount_with_slippage_tolerance(10000, u16::MAX),
Err(INVALID_SLIPPAGE_TOLERANCE)
);
}
#[test]
fn test_apply_swap_fee() {
assert_eq!(try_apply_swap_fee(0, 1000), Ok(0));
assert_eq!(try_apply_swap_fee(10000, 0), Ok(10000));
assert_eq!(try_apply_swap_fee(10000, 1000), Ok(9990));
assert_eq!(try_apply_swap_fee(10000, 10000), Ok(9900));
assert_eq!(try_apply_swap_fee(10000, u16::MAX), Ok(9344));
assert_eq!(try_apply_swap_fee(u64::MAX, 1000), Ok(18428297329635842063));
assert_eq!(
try_apply_swap_fee(u64::MAX, 10000),
Ok(18262276632972456098)
);
}
#[test]
fn test_reverse_apply_swap_fee() {
assert_eq!(try_reverse_apply_swap_fee(0, 1000), Ok(0));
assert_eq!(try_reverse_apply_swap_fee(10000, 0), Ok(10000));
assert_eq!(try_reverse_apply_swap_fee(9990, 1000), Ok(10000));
assert_eq!(try_reverse_apply_swap_fee(9900, 10000), Ok(10000));
assert_eq!(try_reverse_apply_swap_fee(9344, u16::MAX), Ok(10000));
assert_eq!(
try_reverse_apply_swap_fee(u64::MAX, 1000),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
assert_eq!(
try_reverse_apply_swap_fee(u64::MAX, 10000),
Err(AMOUNT_EXCEEDS_MAX_U64)
);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/tick_array.rs
|
use crate::{
CoreError, TickArrayFacade, TickFacade, INVALID_TICK_INDEX, MAX_TICK_INDEX, MIN_TICK_INDEX,
TICK_ARRAY_NOT_EVENLY_SPACED, TICK_ARRAY_SIZE, TICK_INDEX_OUT_OF_BOUNDS, TICK_SEQUENCE_EMPTY,
};
use super::{
get_initializable_tick_index, get_next_initializable_tick_index,
get_prev_initializable_tick_index,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TickArraySequence<const SIZE: usize> {
pub tick_arrays: [Option<TickArrayFacade>; SIZE],
pub tick_spacing: u16,
}
impl<const SIZE: usize> TickArraySequence<SIZE> {
pub fn new(
tick_arrays: [Option<TickArrayFacade>; SIZE],
tick_spacing: u16,
) -> Result<Self, CoreError> {
let mut tick_arrays = tick_arrays;
tick_arrays.sort_by_key(start_tick_index);
if tick_arrays.is_empty() || tick_arrays[0].is_none() {
return Err(TICK_SEQUENCE_EMPTY);
}
let required_tick_array_spacing = TICK_ARRAY_SIZE as i32 * tick_spacing as i32;
for i in 0..tick_arrays.len() - 1 {
let current_start_tick_index = start_tick_index(&tick_arrays[i]);
let next_start_tick_index = start_tick_index(&tick_arrays[i + 1]);
if next_start_tick_index != <i32>::MAX
&& next_start_tick_index - current_start_tick_index != required_tick_array_spacing
{
return Err(TICK_ARRAY_NOT_EVENLY_SPACED);
}
}
Ok(Self {
tick_arrays,
tick_spacing,
})
}
/// Returns the first valid tick index in the sequence.
pub fn start_index(&self) -> i32 {
start_tick_index(&self.tick_arrays[0]).max(MIN_TICK_INDEX)
}
/// Returns the last valid tick index in the sequence.
pub fn end_index(&self) -> i32 {
let mut last_valid_start_index = self.start_index();
for i in 0..self.tick_arrays.len() {
if start_tick_index(&self.tick_arrays[i]) != <i32>::MAX {
last_valid_start_index = start_tick_index(&self.tick_arrays[i]);
}
}
let end_index =
last_valid_start_index + TICK_ARRAY_SIZE as i32 * self.tick_spacing as i32 - 1;
end_index.min(MAX_TICK_INDEX)
}
pub fn tick(&self, tick_index: i32) -> Result<&TickFacade, CoreError> {
if (tick_index < self.start_index()) || (tick_index > self.end_index()) {
return Err(TICK_INDEX_OUT_OF_BOUNDS);
}
if (tick_index % self.tick_spacing as i32) != 0 {
return Err(INVALID_TICK_INDEX);
}
let first_index = start_tick_index(&self.tick_arrays[0]);
let tick_array_index = ((tick_index - first_index)
/ (TICK_ARRAY_SIZE as i32 * self.tick_spacing as i32))
as usize;
let tick_array_start_index = start_tick_index(&self.tick_arrays[tick_array_index]);
let tick_array_ticks = ticks(&self.tick_arrays[tick_array_index]);
let index_in_array = (tick_index - tick_array_start_index) / self.tick_spacing as i32;
Ok(&tick_array_ticks[index_in_array as usize])
}
pub fn next_initialized_tick(
&self,
tick_index: i32,
) -> Result<(Option<&TickFacade>, i32), CoreError> {
let array_end_index = self.end_index();
let mut next_index = tick_index;
loop {
next_index = get_next_initializable_tick_index(next_index, self.tick_spacing);
// If at the end of the sequence, we don't have tick info but can still return the next tick index
if next_index > array_end_index {
return Ok((None, array_end_index));
}
let tick = self.tick(next_index)?;
if tick.initialized {
return Ok((Some(tick), next_index));
}
}
}
pub fn prev_initialized_tick(
&self,
tick_index: i32,
) -> Result<(Option<&TickFacade>, i32), CoreError> {
let array_start_index = self.start_index();
let mut prev_index =
get_initializable_tick_index(tick_index, self.tick_spacing, Some(false));
loop {
// If at the start of the sequence, we don't have tick info but can still return the previous tick index
if prev_index < array_start_index {
return Ok((None, array_start_index));
}
let tick = self.tick(prev_index)?;
if tick.initialized {
return Ok((Some(tick), prev_index));
}
prev_index = get_prev_initializable_tick_index(prev_index, self.tick_spacing);
}
}
}
// internal functions
fn start_tick_index(tick_array: &Option<TickArrayFacade>) -> i32 {
if let Some(tick_array) = tick_array {
tick_array.start_tick_index
} else {
<i32>::MAX
}
}
fn ticks(tick_array: &Option<TickArrayFacade>) -> &[TickFacade] {
if let Some(tick_array) = tick_array {
&tick_array.ticks
} else {
&[]
}
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
fn test_sequence(tick_spacing: u16) -> TickArraySequence<5> {
let ticks: [TickFacade; TICK_ARRAY_SIZE] = (0..TICK_ARRAY_SIZE)
.map(|x| TickFacade {
initialized: x & 1 == 1,
liquidity_net: x as i128,
..TickFacade::default()
})
.collect::<Vec<TickFacade>>()
.try_into()
.unwrap();
let one = TickArrayFacade {
start_tick_index: -(TICK_ARRAY_SIZE as i32 * tick_spacing as i32),
ticks,
};
let two = TickArrayFacade {
start_tick_index: 0,
ticks,
};
let three = TickArrayFacade {
start_tick_index: TICK_ARRAY_SIZE as i32 * tick_spacing as i32,
ticks,
};
TickArraySequence::new(
[Some(one), Some(two), Some(three), None, None],
tick_spacing,
)
.unwrap()
}
#[test]
fn test_tick_array_start_index() {
let sequence = test_sequence(16);
assert_eq!(sequence.start_index(), -1408);
}
#[test]
fn test_tick_array_end_index() {
let sequence = test_sequence(16);
assert_eq!(sequence.end_index(), 2815);
}
#[test]
fn test_get_tick() {
let sequence = test_sequence(16);
assert_eq!(sequence.tick(-1408).map(|x| x.liquidity_net), Ok(0));
assert_eq!(sequence.tick(-16).map(|x| x.liquidity_net), Ok(87));
assert_eq!(sequence.tick(0).map(|x| x.liquidity_net), Ok(0));
assert_eq!(sequence.tick(16).map(|x| x.liquidity_net), Ok(1));
assert_eq!(sequence.tick(1408).map(|x| x.liquidity_net), Ok(0));
assert_eq!(sequence.tick(1424).map(|x| x.liquidity_net), Ok(1));
}
#[test]
fn test_get_tick_large_tick_spacing() {
let sequence: TickArraySequence<5> = test_sequence(32896);
assert_eq!(sequence.tick(-427648).map(|x| x.liquidity_net), Ok(75));
assert_eq!(sequence.tick(0).map(|x| x.liquidity_net), Ok(0));
assert_eq!(sequence.tick(427648).map(|x| x.liquidity_net), Ok(13));
}
#[test]
fn test_get_tick_errors() {
let sequence = test_sequence(16);
let out_out_bounds_lower = sequence.tick(-1409);
assert!(matches!(
out_out_bounds_lower,
Err(TICK_INDEX_OUT_OF_BOUNDS)
));
let out_of_bounds_upper = sequence.tick(2817);
assert!(matches!(out_of_bounds_upper, Err(TICK_INDEX_OUT_OF_BOUNDS)));
let invalid_tick_index = sequence.tick(1);
assert!(matches!(invalid_tick_index, Err(INVALID_TICK_INDEX)));
let invalid_negative_tick_index = sequence.tick(-1);
assert!(matches!(
invalid_negative_tick_index,
Err(INVALID_TICK_INDEX)
));
}
#[test]
fn test_get_next_initializable_tick_index() {
let sequence = test_sequence(16);
let pair = sequence.next_initialized_tick(0);
assert_eq!(pair.map(|x| x.1), Ok(16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(1)));
}
#[test]
fn test_get_next_initializable_tick_index_off_spacing() {
let sequence = test_sequence(16);
let pair = sequence.next_initialized_tick(-17);
assert_eq!(pair.map(|x| x.1), Ok(-16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(87)));
}
#[test]
fn test_get_next_initializable_tick_cross_array() {
let sequence = test_sequence(16);
let pair = sequence.next_initialized_tick(1392);
assert_eq!(pair.map(|x| x.1), Ok(1424));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(1)));
}
#[test]
fn test_get_next_initializable_tick_skip_uninitialized() {
let sequence = test_sequence(16);
let pair = sequence.next_initialized_tick(-1);
assert_eq!(pair.map(|x| x.1), Ok(16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(1)));
}
#[test]
fn test_get_next_initializable_tick_out_of_bounds() {
let sequence = test_sequence(16);
let pair = sequence.next_initialized_tick(2817);
assert_eq!(pair.map(|x| x.1), Ok(2815));
assert_eq!(pair.map(|x| x.0), Ok(None));
}
#[test]
fn test_get_prev_initializable_tick_index() {
let sequence = test_sequence(16);
let pair = sequence.prev_initialized_tick(32);
assert_eq!(pair.map(|x| x.1), Ok(16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(1)));
}
#[test]
fn test_get_prev_initializable_tick_index_off_spacing() {
let sequence = test_sequence(16);
let pair = sequence.prev_initialized_tick(-1);
assert_eq!(pair.map(|x| x.1), Ok(-16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(87)));
}
#[test]
fn test_get_prev_initializable_tick_skip_uninitialized() {
let sequence = test_sequence(16);
let pair = sequence.prev_initialized_tick(33);
assert_eq!(pair.map(|x| x.1), Ok(16));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(1)));
}
#[test]
fn test_get_prev_initializable_tick_cross_array() {
let sequence = test_sequence(16);
let pair = sequence.prev_initialized_tick(1408);
assert_eq!(pair.map(|x| x.1), Ok(1392));
assert_eq!(pair.map(|x| x.0.map(|x| x.liquidity_net)), Ok(Some(87)));
}
#[test]
fn test_get_prev_initialized_tick_out_of_bounds() {
let sequence = test_sequence(16);
let pair = sequence.prev_initialized_tick(-1409);
assert_eq!(pair.map(|x| x.1), Ok(-1408));
assert_eq!(pair.map(|x| x.0), Ok(None));
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/bundle.rs
|
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use ethnum::U256;
use crate::POSITION_BUNDLE_SIZE;
const POSITION_BUNDLE_BYTES: usize = POSITION_BUNDLE_SIZE / 8;
/// Get the first unoccupied position in a bundle
///
/// # Arguments
/// * `bundle` - The bundle to check
///
/// # Returns
/// * `u32` - The first unoccupied position (None if full)
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn first_unoccupied_position_in_bundle(bitmap: &[u8]) -> Option<u32> {
let value = bitmap_to_u256(bitmap);
for i in 0..POSITION_BUNDLE_SIZE {
if value & (U256::ONE << i) == 0 {
return Some(i as u32);
}
}
None
}
/// Check whether a position bundle is full
/// A position bundle can contain 256 positions
///
/// # Arguments
/// * `bundle` - The bundle to check
///
/// # Returns
/// * `bool` - Whether the bundle is full
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn is_position_bundle_full(bitmap: &[u8]) -> bool {
let value = bitmap_to_u256(bitmap);
value == U256::MAX
}
/// Check whether a position bundle is empty
///
/// # Arguments
/// * `bundle` - The bundle to check
///
/// # Returns
/// * `bool` - Whether the bundle is empty
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn is_position_bundle_empty(bitmap: &[u8]) -> bool {
let value = bitmap_to_u256(bitmap);
value == U256::MIN
}
// Private functions
#[allow(clippy::needless_range_loop)]
fn bitmap_to_u256(bitmap: &[u8]) -> U256 {
let mut u256 = <U256>::from(0u32);
for i in 0..POSITION_BUNDLE_BYTES {
let byte = bitmap[i];
u256 += <U256>::from(byte) << (i * 8);
}
u256
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
#[test]
fn test_first_unoccupied_position_in_bundle() {
let bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
assert_eq!(first_unoccupied_position_in_bundle(&bundle), Some(0));
let mut low_bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
low_bundle[0] = 0b11101111;
assert_eq!(first_unoccupied_position_in_bundle(&low_bundle), Some(4));
let mut high_bundle: [u8; POSITION_BUNDLE_BYTES] = [255; POSITION_BUNDLE_BYTES];
high_bundle[10] = 0b10111111;
assert_eq!(first_unoccupied_position_in_bundle(&high_bundle), Some(86));
let full_bundle: [u8; POSITION_BUNDLE_BYTES] = [255; POSITION_BUNDLE_BYTES];
assert_eq!(first_unoccupied_position_in_bundle(&full_bundle), None);
}
#[test]
fn test_is_position_bundle_full() {
let bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
assert!(!is_position_bundle_full(&bundle));
let bundle: [u8; POSITION_BUNDLE_BYTES] = [255; POSITION_BUNDLE_BYTES];
assert!(is_position_bundle_full(&bundle));
let mut bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
bundle[0] = 0b11111111;
assert!(!is_position_bundle_full(&bundle));
}
#[test]
fn test_is_position_bundle_empty() {
let bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
assert!(is_position_bundle_empty(&bundle));
let bundle: [u8; POSITION_BUNDLE_BYTES] = [255; POSITION_BUNDLE_BYTES];
assert!(!is_position_bundle_empty(&bundle));
let mut bundle: [u8; POSITION_BUNDLE_BYTES] = [0; POSITION_BUNDLE_BYTES];
bundle[0] = 0b111111;
assert!(!is_position_bundle_empty(&bundle));
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/mod.rs
|
mod bundle;
mod position;
mod tick;
mod tick_array;
mod token;
#[cfg(feature = "floats")]
mod price;
pub use bundle::*;
pub use position::*;
pub use tick::*;
pub use tick_array::*;
pub use token::*;
#[cfg(feature = "floats")]
pub use price::*;
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/price.rs
|
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use libm::{floor, pow, sqrt};
use crate::U128;
use super::{invert_tick_index, sqrt_price_to_tick_index, tick_index_to_sqrt_price};
const Q64_RESOLUTION: f64 = 18446744073709551616.0;
/// Convert a price into a sqrt priceX64
/// IMPORTANT: floating point operations can reduce the precision of the result.
/// Make sure to do these operations last and not to use the result for further calculations.
///
/// # Parameters
/// * `price` - The price to convert
/// * `decimals_a` - The number of decimals of the base token
/// * `decimals_b` - The number of decimals of the quote token
///
/// # Returns
/// * `u128` - The sqrt priceX64
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn price_to_sqrt_price(price: f64, decimals_a: u8, decimals_b: u8) -> U128 {
let power = pow(10f64, decimals_a as f64 - decimals_b as f64);
(floor(sqrt(price / power) * Q64_RESOLUTION) as u128).into()
}
/// Convert a sqrt priceX64 into a tick index
/// IMPORTANT: floating point operations can reduce the precision of the result.
/// Make sure to do these operations last and not to use the result for further calculations.
///
/// # Parameters
/// * `sqrt_price` - The sqrt priceX64 to convert
/// * `decimals_a` - The number of decimals of the base token
/// * `decimals_b` - The number of decimals of the quote token
///
/// # Returns
/// * `f64` - The decimal price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn sqrt_price_to_price(sqrt_price: U128, decimals_a: u8, decimals_b: u8) -> f64 {
let power = pow(10f64, decimals_a as f64 - decimals_b as f64);
let sqrt_price: u128 = sqrt_price.into();
let sqrt_price_u128 = sqrt_price as f64;
pow(sqrt_price_u128 / Q64_RESOLUTION, 2.0) * power
}
/// Invert a price
/// IMPORTANT: floating point operations can reduce the precision of the result.
/// Make sure to do these operations last and not to use the result for further calculations.
///
/// # Parameters
/// * `price` - The price to invert
/// * `decimals_a` - The number of decimals of the base token
/// * `decimals_b` - The number of decimals of the quote token
///
/// # Returns
/// * `f64` - The inverted price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn invert_price(price: f64, decimals_a: u8, decimals_b: u8) -> f64 {
let tick_index = price_to_tick_index(price, decimals_a, decimals_b);
let inverted_tick_index = invert_tick_index(tick_index);
tick_index_to_price(inverted_tick_index, decimals_a, decimals_b)
}
/// Convert a tick index into a price
/// IMPORTANT: floating point operations can reduce the precision of the result.
/// Make sure to do these operations last and not to use the result for further calculations.
///
/// # Parameters
/// * `tick_index` - The tick index to convert
/// * `decimals_a` - The number of decimals of the base token
/// * `decimals_b` - The number of decimals of the quote token
///
/// # Returns
/// * `f64` - The decimal price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn tick_index_to_price(tick_index: i32, decimals_a: u8, decimals_b: u8) -> f64 {
let sqrt_price = tick_index_to_sqrt_price(tick_index);
sqrt_price_to_price(sqrt_price, decimals_a, decimals_b)
}
/// Convert a price into a tick index
/// IMPORTANT: floating point operations can reduce the precision of the result.
/// Make sure to do these operations last and not to use the result for further calculations.
///
/// # Parameters
/// * `price` - The price to convert
/// * `decimals_a` - The number of decimals of the base token
/// * `decimals_b` - The number of decimals of the quote token
///
/// # Returns
/// * `i32` - The tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn price_to_tick_index(price: f64, decimals_a: u8, decimals_b: u8) -> i32 {
let sqrt_price = price_to_sqrt_price(price, decimals_a, decimals_b);
sqrt_price_to_tick_index(sqrt_price)
}
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use approx::assert_relative_eq;
use super::*;
#[test]
fn test_price_to_sqrt_price() {
assert_eq!(price_to_sqrt_price(0.00999999, 8, 6), 184467348503352096);
assert_eq!(price_to_sqrt_price(100.0, 6, 6), 184467440737095516160);
assert_eq!(price_to_sqrt_price(100.0111, 6, 8), 1844776783959692673024);
}
#[test]
fn test_sqrt_price_to_price() {
assert_relative_eq!(sqrt_price_to_price(184467348503352096, 8, 6), 0.00999999);
assert_relative_eq!(sqrt_price_to_price(184467440737095516160, 6, 6), 100.0);
assert_relative_eq!(sqrt_price_to_price(1844776783959692673024, 6, 8), 100.0111);
}
#[test]
fn test_invert_price() {
assert_relative_eq!(
invert_price(0.00999999, 8, 6),
1000099.11863,
epsilon = 1e-5
);
assert_relative_eq!(invert_price(100.0, 6, 6), 0.01, epsilon = 1e-5);
assert_relative_eq!(invert_price(100.0111, 6, 8), 9.99e-7, epsilon = 1e-5);
}
#[test]
fn test_tick_index_to_price() {
assert_relative_eq!(tick_index_to_price(-92111, 8, 6), 0.009998, epsilon = 1e-5);
assert_relative_eq!(tick_index_to_price(0, 6, 6), 1.0);
assert_relative_eq!(tick_index_to_price(92108, 6, 8), 99.999912, epsilon = 1e-5);
}
#[test]
fn test_price_to_tick_index() {
assert_eq!(price_to_tick_index(0.009998, 8, 6), -92111);
assert_eq!(price_to_tick_index(1.0, 6, 6), 0);
assert_eq!(price_to_tick_index(99.999912, 6, 8), 92108);
}
#[test]
fn test_sol_usdc() {
let sqrt_price = 6918418495991757039u128; // 140.661 USDC/SOL
let decimals_a = 9u8; // SOL
let decimals_b = 6u8; // USDC
let price = sqrt_price_to_price(sqrt_price, decimals_a, decimals_b);
assert_eq!(price, 140.66116595692344);
let sqrt_price_back = price_to_sqrt_price(price, decimals_a, decimals_b);
let diff = (sqrt_price_back as i128) - (sqrt_price as i128);
let diff_rate = (diff as f64) / (sqrt_price as f64) * 100.0;
assert_relative_eq!(diff_rate, 0.0, epsilon = 1e-10);
}
#[test]
fn test_bonk_usdc() {
let sqrt_price = 265989152599097743u128; // 0.00002 USDC/BONK
let decimals_a = 5u8; // BONK
let decimals_b = 6u8; // USDC
let price = sqrt_price_to_price(sqrt_price, decimals_a, decimals_b);
assert_eq!(price, 2.0791623715496336e-5);
let sqrt_price_back = price_to_sqrt_price(price, decimals_a, decimals_b);
let diff = (sqrt_price_back as i128) - (sqrt_price as i128);
let diff_rate = (diff as f64) / (sqrt_price as f64) * 100.0;
assert_relative_eq!(diff_rate, 0.0, epsilon = 1e-10);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/position.rs
|
use crate::{PositionRatio, PositionStatus, BPS_DENOMINATOR, U128};
use ethnum::U256;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use super::{order_tick_indexes, tick_index_to_sqrt_price};
/// Check if a position is in range.
/// When a position is in range it is earning fees and rewards
///
/// # Parameters
/// - `sqrt_price` - A u128 integer representing the sqrt price of the pool
/// - `tick_index_1` - A i32 integer representing the first tick index of the position
/// - `tick_index_2` - A i32 integer representing the second tick index of the position
///
/// # Returns
/// - A boolean value indicating if the position is in range
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn is_position_in_range(
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
) -> bool {
position_status(current_sqrt_price.into(), tick_index_1, tick_index_2)
== PositionStatus::PriceInRange
}
/// Calculate the status of a position
/// The status can be one of three values:
/// - InRange: The position is in range
/// - BelowRange: The position is below the range
/// - AboveRange: The position is above the range
///
/// # Parameters
/// - `sqrt_price` - A u128 integer representing the sqrt price of the pool
/// - `tick_index_1` - A i32 integer representing the first tick index of the position
/// - `tick_index_2` - A i32 integer representing the second tick index of the position
///
/// # Returns
/// - A PositionStatus enum value indicating the status of the position
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn position_status(
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
) -> PositionStatus {
let current_sqrt_price: u128 = current_sqrt_price.into();
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let sqrt_price_lower: u128 = tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let sqrt_price_upper: u128 = tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
if tick_index_1 == tick_index_2 {
PositionStatus::Invalid
} else if current_sqrt_price <= sqrt_price_lower {
PositionStatus::PriceBelowRange
} else if current_sqrt_price >= sqrt_price_upper {
PositionStatus::PriceAboveRange
} else {
PositionStatus::PriceInRange
}
}
/// Calculate the token_a / token_b ratio of a (ficticious) position
///
/// # Parameters
/// - `sqrt_price` - A u128 integer representing the sqrt price of the pool
/// - `tick_index_1` - A i32 integer representing the first tick index of the position
/// - `tick_index_2` - A i32 integer representing the second tick index of the position
///
/// # Returns
/// - A PositionRatio struct containing the ratio of token_a and token_b
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn position_ratio(
current_sqrt_price: U128,
tick_index_1: i32,
tick_index_2: i32,
) -> PositionRatio {
let current_sqrt_price: u128 = current_sqrt_price.into();
let position_status = position_status(current_sqrt_price.into(), tick_index_1, tick_index_2);
match position_status {
PositionStatus::Invalid => PositionRatio {
ratio_a: 0,
ratio_b: 0,
},
PositionStatus::PriceBelowRange => PositionRatio {
ratio_a: 10000,
ratio_b: 0,
},
PositionStatus::PriceAboveRange => PositionRatio {
ratio_a: 0,
ratio_b: 10000,
},
PositionStatus::PriceInRange => {
let tick_range = order_tick_indexes(tick_index_1, tick_index_2);
let lower_sqrt_price: u128 =
tick_index_to_sqrt_price(tick_range.tick_lower_index).into();
let upper_sqrt_price: u128 =
tick_index_to_sqrt_price(tick_range.tick_upper_index).into();
let l: U256 = <U256>::from(1u16) << 128;
let p = <U256>::from(current_sqrt_price) * <U256>::from(current_sqrt_price);
let deposit_a_1: U256 = (l << 64) / current_sqrt_price;
let deposit_a_2: U256 = (l << 64) / upper_sqrt_price;
let deposit_a: U256 = ((deposit_a_1 - deposit_a_2) * p) >> 128;
let deposit_b_1 = current_sqrt_price - lower_sqrt_price;
let deposit_b = (l * deposit_b_1) >> 64;
let total_deposit = deposit_a + deposit_b;
let denominator = <U256>::from(BPS_DENOMINATOR);
let ratio_a: U256 = (deposit_a * denominator) / total_deposit;
let ratio_b: U256 = denominator - ratio_a;
PositionRatio {
ratio_a: ratio_a.as_u16(),
ratio_b: ratio_b.as_u16(),
}
}
}
}
#[cfg(all(test, not(feature = "wasm")))]
mod test {
use super::*;
#[test]
fn test_is_position_in_range() {
assert!(is_position_in_range(18446744073709551616, -5, 5));
assert!(!is_position_in_range(18446744073709551616, 0, 5));
assert!(!is_position_in_range(18446744073709551616, -5, 0));
assert!(!is_position_in_range(18446744073709551616, -5, -1));
assert!(!is_position_in_range(18446744073709551616, 1, 5));
}
#[test]
fn test_position_status() {
assert_eq!(
position_status(18354745142194483560, -100, 100),
PositionStatus::PriceBelowRange
);
assert_eq!(
position_status(18354745142194483561, -100, 100),
PositionStatus::PriceBelowRange
);
assert_eq!(
position_status(18354745142194483562, -100, 100),
PositionStatus::PriceInRange
);
assert_eq!(
position_status(18446744073709551616, -100, 100),
PositionStatus::PriceInRange
);
assert_eq!(
position_status(18539204128674405811, -100, 100),
PositionStatus::PriceInRange
);
assert_eq!(
position_status(18539204128674405812, -100, 100),
PositionStatus::PriceAboveRange
);
assert_eq!(
position_status(18539204128674405813, -100, 100),
PositionStatus::PriceAboveRange
);
assert_eq!(
position_status(18446744073709551616, 100, 100),
PositionStatus::Invalid
);
}
#[test]
fn test_position_ratio() {
let ratio_1 = position_ratio(18354745142194483561, -100, 100);
assert_eq!(ratio_1.ratio_a, 10000);
assert_eq!(ratio_1.ratio_b, 0);
let ratio_2 = position_ratio(18446744073709551616, -100, 100);
assert_eq!(ratio_2.ratio_a, 4999);
assert_eq!(ratio_2.ratio_b, 5001);
let ratio_3 = position_ratio(18539204128674405812, -100, 100);
assert_eq!(ratio_3.ratio_a, 0);
assert_eq!(ratio_3.ratio_b, 10000);
let ratio_4 = position_ratio(18446744073709551616, 0, 0);
assert_eq!(ratio_4.ratio_a, 0);
assert_eq!(ratio_4.ratio_b, 0);
let ratio_5 = position_ratio(7267764841821948241, -21136, -17240);
assert_eq!(ratio_5.ratio_a, 3630);
assert_eq!(ratio_5.ratio_b, 6370);
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src
|
solana_public_repos/orca-so/whirlpools/rust-sdk/core/src/math/tick.rs
|
use ethnum::U256;
#[cfg(feature = "wasm")]
use orca_whirlpools_macros::wasm_expose;
use crate::{
CoreError, TickRange, FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD, MAX_TICK_INDEX, MIN_TICK_INDEX,
TICK_ARRAY_SIZE, TICK_INDEX_NOT_IN_ARRAY, U128,
};
const LOG_B_2_X32: i128 = 59543866431248i128;
const BIT_PRECISION: u32 = 14;
const LOG_B_P_ERR_MARGIN_LOWER_X64: i128 = 184467440737095516i128; // 0.01
const LOG_B_P_ERR_MARGIN_UPPER_X64: i128 = 15793534762490258745i128; // 2^-precision / log_2_b + 0.01
/// Get the first tick index in the tick array that contains the specified tick index.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
/// - `tick_spacing` - A i32 integer representing the tick spacing
///
/// # Returns
/// - A i32 integer representing the first tick index in the tick array
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_tick_array_start_tick_index(tick_index: i32, tick_spacing: u16) -> i32 {
let tick_spacing_i32 = tick_spacing as i32;
let tick_array_size_i32 = TICK_ARRAY_SIZE as i32;
let real_index = tick_index
.div_euclid(tick_spacing_i32)
.div_euclid(tick_array_size_i32);
real_index * tick_spacing_i32 * tick_array_size_i32
}
/// Derive the sqrt-price from a tick index. The precision of this method is only guarranted
/// if tick is within the bounds of {max, min} tick-index.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
///
/// # Returns
/// - `Ok`: A u128 Q32.64 representing the sqrt_price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn tick_index_to_sqrt_price(tick_index: i32) -> U128 {
if tick_index >= 0 {
get_sqrt_price_positive_tick(tick_index).into()
} else {
get_sqrt_price_negative_tick(tick_index).into()
}
}
/// Derive the tick index from a sqrt price. The precision of this method is only guarranted
/// if tick is within the bounds of {max, min} tick-index.
///
/// # Parameters
/// - `sqrt_price` - A u128 integer representing the sqrt price
///
/// # Returns
/// - `Ok`: A i32 integer representing the tick integer
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn sqrt_price_to_tick_index(sqrt_price: U128) -> i32 {
let sqrt_price_x64: u128 = sqrt_price.into();
// Determine log_b(sqrt_ratio). First by calculating integer portion (msb)
let msb: u32 = 128 - sqrt_price_x64.leading_zeros() - 1;
let log2p_integer_x32 = (msb as i128 - 64) << 32;
// get fractional value (r/2^msb), msb always > 128
// We begin the iteration from bit 63 (0.5 in Q64.64)
let mut bit: i128 = 0x8000_0000_0000_0000i128;
let mut precision = 0;
let mut log2p_fraction_x64 = 0;
// Log2 iterative approximation for the fractional part
// Go through each 2^(j) bit where j < 64 in a Q64.64 number
// Append current bit value to fraction result if r^2 Q2.126 is more than 2
let mut r = if msb >= 64 {
sqrt_price_x64 >> (msb - 63)
} else {
sqrt_price_x64 << (63 - msb)
};
while bit > 0 && precision < BIT_PRECISION {
r *= r;
let is_r_more_than_two = r >> 127_u32;
r >>= 63 + is_r_more_than_two;
log2p_fraction_x64 += bit * is_r_more_than_two as i128;
bit >>= 1;
precision += 1;
}
let log2p_fraction_x32 = log2p_fraction_x64 >> 32;
let log2p_x32 = log2p_integer_x32 + log2p_fraction_x32;
// Transform from base 2 to base b
let logbp_x64 = log2p_x32 * LOG_B_2_X32;
// Derive tick_low & high estimate. Adjust with the possibility of under-estimating by 2^precision_bits/log_2(b) + 0.01 error margin.
let tick_low: i32 = ((logbp_x64 - LOG_B_P_ERR_MARGIN_LOWER_X64) >> 64) as i32;
let tick_high: i32 = ((logbp_x64 + LOG_B_P_ERR_MARGIN_UPPER_X64) >> 64) as i32;
if tick_low == tick_high {
tick_low
} else {
// If our estimation for tick_high returns a lower sqrt_price than the input
// then the actual tick_high has to be higher than than tick_high.
// Otherwise, the actual value is between tick_low & tick_high, so a floor value
// (tick_low) is returned
let actual_tick_high_sqrt_price_x64: u128 = tick_index_to_sqrt_price(tick_high).into();
if actual_tick_high_sqrt_price_x64 <= sqrt_price_x64 {
tick_high
} else {
tick_low
}
}
}
/// Get the initializable tick index.
/// If the tick index is already initializable, it is returned as is.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
/// - `tick_spacing` - A i32 integer representing the tick spacing
/// - `round_up` - A boolean value indicating if the supplied tick index should be rounded up. None will round to the nearest.
///
/// # Returns
/// - A i32 integer representing the previous initializable tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_initializable_tick_index(
tick_index: i32,
tick_spacing: u16,
round_up: Option<bool>,
) -> i32 {
let tick_spacing_i32 = tick_spacing as i32;
let remainder = tick_index.rem_euclid(tick_spacing_i32);
let result = tick_index.div_euclid(tick_spacing_i32) * tick_spacing_i32;
let should_round_up = if let Some(round_up) = round_up {
round_up && remainder > 0
} else {
remainder >= tick_spacing_i32 / 2
};
if should_round_up {
result + tick_spacing_i32
} else {
result
}
}
/// Get the previous initializable tick index.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
/// - `tick_spacing` - A i32 integer representing the tick spacing
///
/// # Returns
/// - A i32 integer representing the previous initializable tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_prev_initializable_tick_index(tick_index: i32, tick_spacing: u16) -> i32 {
let tick_spacing_i32 = tick_spacing as i32;
let remainder = tick_index.rem_euclid(tick_spacing_i32);
if remainder == 0 {
tick_index - tick_spacing_i32
} else {
tick_index - remainder
}
}
/// Get the next initializable tick index.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
/// - `tick_spacing` - A i32 integer representing the tick spacing
///
/// # Returns
/// - A i32 integer representing the next initializable tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_next_initializable_tick_index(tick_index: i32, tick_spacing: u16) -> i32 {
let tick_spacing_i32 = tick_spacing as i32;
let remainder = tick_index.rem_euclid(tick_spacing_i32);
tick_index - remainder + tick_spacing_i32
}
/// Check if a tick is in-bounds.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
///
/// # Returns
/// - A boolean value indicating if the tick is in-bounds
#[cfg_attr(feature = "wasm", wasm_expose)]
#[allow(clippy::manual_range_contains)]
pub fn is_tick_index_in_bounds(tick_index: i32) -> bool {
tick_index <= MAX_TICK_INDEX && tick_index >= MIN_TICK_INDEX
}
/// Check if a tick is initializable.
/// A tick is initializable if it is divisible by the tick spacing.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
/// - `tick_spacing` - A i32 integer representing the tick spacing
///
/// # Returns
/// - A boolean value indicating if the tick is initializable
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn is_tick_initializable(tick_index: i32, tick_spacing: u16) -> bool {
let tick_spacing_i32 = tick_spacing as i32;
tick_index % tick_spacing_i32 == 0
}
/// Get the tick index for the inverse of the price that this tick represents.
/// Eg: Consider tick i where Pb/Pa = 1.0001 ^ i
/// inverse of this, i.e. Pa/Pb = 1 / (1.0001 ^ i) = 1.0001^-i
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick integer
///
/// # Returns
/// - A i32 integer representing the tick index for the inverse of the price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn invert_tick_index(tick_index: i32) -> i32 {
-tick_index
}
/// Get the sqrt price for the inverse of the price that this tick represents.
/// Because converting to a tick index and then back to a sqrt price is lossy,
/// this function is clamped to the nearest tick index.
///
/// # Parameters
/// - `sqrt_price` - A u128 integer representing the sqrt price
///
/// # Returns
/// - A u128 integer representing the sqrt price for the inverse of the price
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn invert_sqrt_price(sqrt_price: U128) -> U128 {
let tick_index = sqrt_price_to_tick_index(sqrt_price);
let inverted_tick_index = invert_tick_index(tick_index);
tick_index_to_sqrt_price(inverted_tick_index)
}
/// Get the minimum and maximum tick index that can be initialized.
///
/// # Parameters
/// - `tick_spacing` - A i32 integer representing the tick spacing
///
/// # Returns
/// - A TickRange struct containing the lower and upper tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_full_range_tick_indexes(tick_spacing: u16) -> TickRange {
let tick_spacing_i32 = tick_spacing as i32;
let min_tick_index = (MIN_TICK_INDEX / tick_spacing_i32) * tick_spacing_i32;
let max_tick_index = (MAX_TICK_INDEX / tick_spacing_i32) * tick_spacing_i32;
TickRange {
tick_lower_index: min_tick_index,
tick_upper_index: max_tick_index,
}
}
/// Order tick indexes in ascending order.
/// If the lower tick index is greater than the upper tick index, the indexes are swapped.
/// This is useful for ensuring that the lower tick index is always less than the upper tick index.
///
/// # Parameters
/// - `tick_index_1` - A i32 integer representing the first tick index
/// - `tick_index_2` - A i32 integer representing the second tick index
///
/// # Returns
/// - A TickRange struct containing the lower and upper tick index
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn order_tick_indexes(tick_index_1: i32, tick_index_2: i32) -> TickRange {
if tick_index_1 < tick_index_2 {
TickRange {
tick_lower_index: tick_index_1,
tick_upper_index: tick_index_2,
}
} else {
TickRange {
tick_lower_index: tick_index_2,
tick_upper_index: tick_index_1,
}
}
}
/// Check if a whirlpool is a full-range only pool.
///
/// # Parameters
/// - `tick_spacing` - A u16 integer representing the tick spacing
///
/// # Returns
/// - A boolean value indicating if the whirlpool is a full-range only pool
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn is_full_range_only(tick_spacing: u16) -> bool {
tick_spacing >= FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD
}
/// Get the index of a tick in a tick array.
///
/// # Parameters
/// - `tick_index` - A i32 integer representing the tick index
/// - `tick_array_start_index` - A i32 integer representing the start tick index of the tick array
/// - `tick_spacing` - A u16 integer representing the tick spacing
///
/// # Returns
/// - A u32 integer representing the tick index in the tick array
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_tick_index_in_array(
tick_index: i32,
tick_array_start_index: i32,
tick_spacing: u16,
) -> Result<u32, CoreError> {
if tick_index < tick_array_start_index {
return Err(TICK_INDEX_NOT_IN_ARRAY);
}
if tick_index >= tick_array_start_index + (TICK_ARRAY_SIZE as i32) * (tick_spacing as i32) {
return Err(TICK_INDEX_NOT_IN_ARRAY);
}
let result = (tick_index - tick_array_start_index).unsigned_abs() / (tick_spacing as u32);
Ok(result)
}
// Private functions
fn mul_shift_96(n0: u128, n1: u128) -> u128 {
let mul: U256 = (<U256>::from(n0) * <U256>::from(n1)) >> 96;
mul.as_u128()
}
fn get_sqrt_price_positive_tick(tick: i32) -> u128 {
let mut ratio: u128 = if tick & 1 != 0 {
79232123823359799118286999567
} else {
79228162514264337593543950336
};
if tick & 2 != 0 {
ratio = mul_shift_96(ratio, 79236085330515764027303304731);
}
if tick & 4 != 0 {
ratio = mul_shift_96(ratio, 79244008939048815603706035061);
}
if tick & 8 != 0 {
ratio = mul_shift_96(ratio, 79259858533276714757314932305);
}
if tick & 16 != 0 {
ratio = mul_shift_96(ratio, 79291567232598584799939703904);
}
if tick & 32 != 0 {
ratio = mul_shift_96(ratio, 79355022692464371645785046466);
}
if tick & 64 != 0 {
ratio = mul_shift_96(ratio, 79482085999252804386437311141);
}
if tick & 128 != 0 {
ratio = mul_shift_96(ratio, 79736823300114093921829183326);
}
if tick & 256 != 0 {
ratio = mul_shift_96(ratio, 80248749790819932309965073892);
}
if tick & 512 != 0 {
ratio = mul_shift_96(ratio, 81282483887344747381513967011);
}
if tick & 1024 != 0 {
ratio = mul_shift_96(ratio, 83390072131320151908154831281);
}
if tick & 2048 != 0 {
ratio = mul_shift_96(ratio, 87770609709833776024991924138);
}
if tick & 4096 != 0 {
ratio = mul_shift_96(ratio, 97234110755111693312479820773);
}
if tick & 8192 != 0 {
ratio = mul_shift_96(ratio, 119332217159966728226237229890);
}
if tick & 16384 != 0 {
ratio = mul_shift_96(ratio, 179736315981702064433883588727);
}
if tick & 32768 != 0 {
ratio = mul_shift_96(ratio, 407748233172238350107850275304);
}
if tick & 65536 != 0 {
ratio = mul_shift_96(ratio, 2098478828474011932436660412517);
}
if tick & 131072 != 0 {
ratio = mul_shift_96(ratio, 55581415166113811149459800483533);
}
if tick & 262144 != 0 {
ratio = mul_shift_96(ratio, 38992368544603139932233054999993551);
}
ratio >> 32
}
fn get_sqrt_price_negative_tick(tick: i32) -> u128 {
let abs_tick = tick.abs();
let mut ratio: u128 = if abs_tick & 1 != 0 {
18445821805675392311
} else {
18446744073709551616
};
if abs_tick & 2 != 0 {
ratio = (ratio * 18444899583751176498) >> 64
}
if abs_tick & 4 != 0 {
ratio = (ratio * 18443055278223354162) >> 64
}
if abs_tick & 8 != 0 {
ratio = (ratio * 18439367220385604838) >> 64
}
if abs_tick & 16 != 0 {
ratio = (ratio * 18431993317065449817) >> 64
}
if abs_tick & 32 != 0 {
ratio = (ratio * 18417254355718160513) >> 64
}
if abs_tick & 64 != 0 {
ratio = (ratio * 18387811781193591352) >> 64
}
if abs_tick & 128 != 0 {
ratio = (ratio * 18329067761203520168) >> 64
}
if abs_tick & 256 != 0 {
ratio = (ratio * 18212142134806087854) >> 64
}
if abs_tick & 512 != 0 {
ratio = (ratio * 17980523815641551639) >> 64
}
if abs_tick & 1024 != 0 {
ratio = (ratio * 17526086738831147013) >> 64
}
if abs_tick & 2048 != 0 {
ratio = (ratio * 16651378430235024244) >> 64
}
if abs_tick & 4096 != 0 {
ratio = (ratio * 15030750278693429944) >> 64
}
if abs_tick & 8192 != 0 {
ratio = (ratio * 12247334978882834399) >> 64
}
if abs_tick & 16384 != 0 {
ratio = (ratio * 8131365268884726200) >> 64
}
if abs_tick & 32768 != 0 {
ratio = (ratio * 3584323654723342297) >> 64
}
if abs_tick & 65536 != 0 {
ratio = (ratio * 696457651847595233) >> 64
}
if abs_tick & 131072 != 0 {
ratio = (ratio * 26294789957452057) >> 64
}
if abs_tick & 262144 != 0 {
ratio = (ratio * 37481735321082) >> 64
}
ratio
}
// Tests
#[cfg(all(test, not(feature = "wasm")))]
mod tests {
use super::*;
use crate::{MAX_SQRT_PRICE, MIN_SQRT_PRICE};
#[test]
fn test_get_tick_array_start_tick_index() {
assert_eq!(get_tick_array_start_tick_index(1000, 10), 880);
assert_eq!(get_tick_array_start_tick_index(100, 10), 0);
assert_eq!(get_tick_array_start_tick_index(0, 10), 0);
assert_eq!(get_tick_array_start_tick_index(-100, 10), -880);
assert_eq!(get_tick_array_start_tick_index(-1000, 10), -1760);
}
#[test]
fn test_tick_index_to_sqrt_price() {
assert_eq!(tick_index_to_sqrt_price(MAX_TICK_INDEX), MAX_SQRT_PRICE);
assert_eq!(tick_index_to_sqrt_price(100), 18539204128674405812);
assert_eq!(tick_index_to_sqrt_price(1), 18447666387855959850);
assert_eq!(tick_index_to_sqrt_price(0), 18446744073709551616);
assert_eq!(tick_index_to_sqrt_price(-1), 18445821805675392311);
assert_eq!(tick_index_to_sqrt_price(-100), 18354745142194483561);
assert_eq!(tick_index_to_sqrt_price(MIN_TICK_INDEX), MIN_SQRT_PRICE);
}
#[test]
fn test_sqrt_price_to_tick_index() {
assert_eq!(sqrt_price_to_tick_index(MAX_SQRT_PRICE), MAX_TICK_INDEX);
assert_eq!(sqrt_price_to_tick_index(18539204128674405812), 100);
assert_eq!(sqrt_price_to_tick_index(18447666387855959850), 1);
assert_eq!(sqrt_price_to_tick_index(18446744073709551616), 0);
assert_eq!(sqrt_price_to_tick_index(18445821805675392311), -1);
assert_eq!(sqrt_price_to_tick_index(18354745142194483561), -100);
assert_eq!(sqrt_price_to_tick_index(MIN_SQRT_PRICE), MIN_TICK_INDEX);
}
#[test]
fn test_get_initializable_tick_index() {
assert_eq!(get_initializable_tick_index(-100, 10, Some(true)), -100);
assert_eq!(get_initializable_tick_index(-100, 10, Some(false)), -100);
assert_eq!(get_initializable_tick_index(-100, 10, None), -100);
assert_eq!(get_initializable_tick_index(-101, 10, Some(true)), -100);
assert_eq!(get_initializable_tick_index(-101, 10, Some(false)), -110);
assert_eq!(get_initializable_tick_index(-101, 10, None), -100);
assert_eq!(get_initializable_tick_index(-105, 10, Some(true)), -100);
assert_eq!(get_initializable_tick_index(-105, 10, Some(false)), -110);
assert_eq!(get_initializable_tick_index(-105, 10, None), -100);
assert_eq!(get_initializable_tick_index(-109, 10, Some(true)), -100);
assert_eq!(get_initializable_tick_index(-109, 10, Some(false)), -110);
assert_eq!(get_initializable_tick_index(-109, 10, None), -110);
assert_eq!(get_initializable_tick_index(-100, 10, Some(true)), -100);
assert_eq!(get_initializable_tick_index(-100, 10, Some(false)), -100);
assert_eq!(get_initializable_tick_index(-100, 10, None), -100);
assert_eq!(get_initializable_tick_index(101, 10, Some(true)), 110);
assert_eq!(get_initializable_tick_index(101, 10, Some(false)), 100);
assert_eq!(get_initializable_tick_index(101, 10, None), 100);
assert_eq!(get_initializable_tick_index(105, 10, Some(true)), 110);
assert_eq!(get_initializable_tick_index(105, 10, Some(false)), 100);
assert_eq!(get_initializable_tick_index(105, 10, None), 110);
assert_eq!(get_initializable_tick_index(109, 10, Some(true)), 110);
assert_eq!(get_initializable_tick_index(109, 10, Some(false)), 100);
assert_eq!(get_initializable_tick_index(109, 10, None), 110);
}
#[test]
fn test_get_prev_initializable_tick_index() {
assert_eq!(get_prev_initializable_tick_index(10, 10), 0);
assert_eq!(get_prev_initializable_tick_index(5, 10), 0);
assert_eq!(get_prev_initializable_tick_index(0, 10), -10);
assert_eq!(get_prev_initializable_tick_index(-5, 10), -10);
assert_eq!(get_prev_initializable_tick_index(-10, 10), -20);
}
#[test]
fn test_get_next_initializable_tick_index() {
assert_eq!(get_next_initializable_tick_index(10, 10), 20);
assert_eq!(get_next_initializable_tick_index(5, 10), 10);
assert_eq!(get_next_initializable_tick_index(0, 10), 10);
assert_eq!(get_next_initializable_tick_index(-5, 10), 0);
assert_eq!(get_next_initializable_tick_index(-10, 10), 0);
}
#[test]
fn test_is_tick_index_in_bounds() {
assert!(is_tick_index_in_bounds(MAX_TICK_INDEX));
assert!(is_tick_index_in_bounds(MIN_TICK_INDEX));
assert!(!is_tick_index_in_bounds(MAX_TICK_INDEX + 1));
assert!(!is_tick_index_in_bounds(MIN_TICK_INDEX - 1));
}
#[test]
fn test_is_tick_initializable() {
assert!(is_tick_initializable(100, 10));
assert!(!is_tick_initializable(105, 10));
}
#[test]
fn test_invert_tick_index() {
assert_eq!(invert_tick_index(100), -100);
assert_eq!(invert_tick_index(-100), 100);
}
#[test]
fn test_get_full_range_tick_indexes() {
let range = get_full_range_tick_indexes(10);
assert_eq!(range.tick_lower_index, (MIN_TICK_INDEX / 10) * 10);
assert_eq!(range.tick_upper_index, (MAX_TICK_INDEX / 10) * 10);
}
#[test]
fn test_order_tick_indexes() {
let range_1 = order_tick_indexes(100, 200);
assert_eq!(range_1.tick_lower_index, 100);
assert_eq!(range_1.tick_upper_index, 200);
let range_2 = order_tick_indexes(200, 100);
assert_eq!(range_2.tick_lower_index, 100);
assert_eq!(range_2.tick_upper_index, 200);
let range_3 = order_tick_indexes(100, 100);
assert_eq!(range_3.tick_lower_index, 100);
assert_eq!(range_3.tick_upper_index, 100);
}
#[test]
fn test_is_full_range_only() {
assert!(is_full_range_only(FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD));
assert!(!is_full_range_only(
FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD - 1
));
}
#[test]
fn test_get_tick_index_in_array() {
// Zero tick index
assert_eq!(get_tick_index_in_array(0, 0, 10), Ok(0));
// Positive tick index
assert_eq!(get_tick_index_in_array(100, 0, 10), Ok(10));
assert_eq!(get_tick_index_in_array(50, 0, 10), Ok(5));
// Negative tick index
assert_eq!(get_tick_index_in_array(-830, -880, 10), Ok(5));
assert_eq!(get_tick_index_in_array(-780, -880, 10), Ok(10));
// Outside of the tick array
assert_eq!(
get_tick_index_in_array(880, 0, 10),
Err(TICK_INDEX_NOT_IN_ARRAY)
);
assert_eq!(
get_tick_index_in_array(-1, 0, 10),
Err(TICK_INDEX_NOT_IN_ARRAY)
);
assert_eq!(
get_tick_index_in_array(-881, -880, 10),
Err(TICK_INDEX_NOT_IN_ARRAY)
);
// Splash pool tick spacing
assert_eq!(get_tick_index_in_array(2861952, 0, 32896), Ok(87));
assert_eq!(get_tick_index_in_array(-32896, -2894848, 32896), Ok(87));
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/index.test.ts
|
import assert from "assert";
import { execSync } from "child_process";
import { readdirSync } from "fs";
import { describe, it } from "vitest";
const clientConfigs = readdirSync("./client");
const coreConfigs = readdirSync("./core");
const whirlpoolConfigs = readdirSync("./whirlpool");
function exec(command: string) {
try {
return execSync(command);
} catch (error) {
assert.fail(`${error}`);
}
}
describe("Integration", () => {
clientConfigs.forEach((config) => {
it.concurrent(`Build client using ${config}`, () => {
exec(`cargo check --manifest-path './client/${config}/Cargo.toml'`);
});
});
coreConfigs.forEach((config) => {
it.concurrent(`Build core using ${config}`, () => {
exec(`cargo check --manifest-path './core/${config}/Cargo.toml'`);
});
});
whirlpoolConfigs.forEach((config) => {
it.concurrent(`Build whirlpool using ${config}`, () => {
exec(`cargo check --manifest-path './whirlpool/${config}/Cargo.toml'`);
});
});
});
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/README.md
|
# Rust SDK Integration tests
This directory contains integration tests for the Rust SDK. This project contains various sub-projects to test different build configurations of the SDK.
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/package.json
|
{
"name": "@orca-so/whirlpools-rust-integration",
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "tsc --noEmit",
"test": "vitest run index.test.ts"
},
"devDependencies": {
"@orca-so/whirlpools-rust": "*",
"@orca-so/whirlpools-rust-client": "*",
"@orca-so/whirlpools-rust-core": "*",
"typescript": "^5.7.2"
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/tsconfig.json
|
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"include": ["index.test.ts"]
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/ethnum_1.3/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_ethnum_v1_3"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
ethnum = { version = "~1.3" }
orca_whirlpools_core = { path = "../../../core" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/ethnum_1.4/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_ethnum_v1_4"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
ethnum = { version = "~1.4" }
orca_whirlpools_core = { path = "../../../core" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/ethnum_1.5/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_ethnum_v1_5"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
ethnum = { version = "~1.5" }
orca_whirlpools_core = { path = "../../../core" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/ethnum_1.2/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_ethnum_v1_2"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
ethnum = { version = "~1.2" }
orca_whirlpools_core = { path = "../../../core" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/libm_0.1/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_libm_v0_1"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
libm = { version = "~0.1" }
orca_whirlpools_core = { path = "../../../core", features = ["floats"] }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/ethnum_1.1/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_ethnum_v1_1"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
ethnum = { version = "~1.1" }
orca_whirlpools_core = { path = "../../../core" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/core/libm_0.2/Cargo.toml
|
[package]
name = "orca_whirlpools_core_integration_libm_v0_2"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
libm = { version = "~0.2" }
orca_whirlpools_core = { path = "../../../core", features = ["floats"] }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/whirlpool
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/whirlpool/solana v1.18/Cargo.toml
|
[package]
name = "orca_whirlpools_integration_solana_v1_18"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
solana-program = { version = "~1.18" }
solana-sdk = { version = "~1.18" }
solana-client = { version = "~1.18" }
solana-account-decoder = { version = "~1.18" }
orca_whirlpools = { path = "../../../whirlpool" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client/solana_v1.17/Cargo.toml
|
[package]
name = "orca_whirlpools_client_integration_solana_v1_17"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
solana-program = { version = "~1.17" }
solana-sdk = { version = "~1.17" }
solana-client = { version = "~1.17" }
solana-account-decoder = { version = "~1.17" }
orca_whirlpools_client = { path = "../../../client" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client/solana_v1.18/Cargo.toml
|
[package]
name = "orca_whirlpools_client_integration_solana_v1_18"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
solana-program = { version = "~1.18" }
solana-sdk = { version = "~1.18" }
solana-client = { version = "~1.18" }
solana-account-decoder = { version = "~1.18" }
orca_whirlpools_client = { path = "../../../client" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client/anchor_v0.29/Cargo.toml
|
[package]
name = "orca_whirlpools_client_integration_anchor_v0_29"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
anchor-lang = { version = "~0.29" }
orca_whirlpools_client = { path = "../../../client", features = ["anchor"] }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client
|
solana_public_repos/orca-so/whirlpools/rust-sdk/integration/client/anchor_v0.30/Cargo.toml
|
[package]
name = "orca_whirlpools_client_integration_anchor_v0_30"
edition = "2021"
[lib]
path = "../../lib.rs"
[dependencies]
anchor-lang = { version = "~0.30" }
orca_whirlpools_client = { path = "../../../client", features = ["anchor"] }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/Cargo.toml
|
[package]
name = "orca_whirlpools_macros"
version = "0.1.0"
description = "Orca's rust wasm macros package."
include = ["src/*"]
documentation = "https://orca-so.github.io/whirlpools/"
homepage = "https://orca.so"
repository = "https://github.com/orca-so/whirlpools"
license = "Apache-2.0"
keywords = ["solana", "crypto", "defi", "dex", "amm"]
authors = ["team@orca.so"]
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "^2", features = ["full"] }
quote = { version = "^1" }
proc-macro2 = { version = "^1" }
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/README.md
|
# Orca Whirlpools Rust Macros
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk
|
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/package.json
|
{
"name": "@orca-so/whirlpools-rust-macros",
"version": "0.0.1",
"scripts": {
"build": "cargo build",
"test": "cargo test --lib",
"format": "cargo clippy --fix --allow-dirty --allow-staged && cargo fmt",
"lint": "cargo clippy && cargo fmt --check",
"clean": "cargo clean"
}
}
| 0
|
solana_public_repos/orca-so/whirlpools/rust-sdk/macros
|
solana_public_repos/orca-so/whirlpools/rust-sdk/macros/src/wasm_struct.rs
|
use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse::Nothing, parse_quote, ItemStruct, Result, Type};
pub fn wasm_struct_impl(item: ItemStruct, _attr: Nothing) -> Result<TokenStream> {
let mut item = item;
// Add attributes to u64 fields
for field in &mut item.fields {
if let Type::Path(type_path) = &field.ty {
if type_path.path.is_ident("u64") {
field
.attrs
.push(parse_quote!(#[serde(serialize_with = "crate::u64_serialize")]));
field.attrs.push(parse_quote!(#[tsify(type = "bigint")]));
}
}
}
let expanded = quote! {
#[derive(::serde::Serialize, ::serde::Deserialize, ::tsify::Tsify)]
#[serde(rename_all = "camelCase")]
#[tsify(from_wasm_abi, into_wasm_abi)]
#item
};
Ok(expanded)
}
#[cfg(test)]
mod tests {
use super::*;
use syn::parse_quote;
#[test]
fn test_correct() {
let item: ItemStruct = parse_quote! {
#[existing_attr]
pub struct TestStruct {
#[existing_attr]
pub foo: u64,
pub bar: u128
}
};
let attr = Nothing {};
let result = wasm_struct_impl(item, attr);
let output = result.unwrap().to_string();
assert_eq!(output, "# [derive (:: serde :: Serialize , :: serde :: Deserialize , :: tsify :: Tsify)] # [serde (rename_all = \"camelCase\")] # [tsify (from_wasm_abi , into_wasm_abi)] # [existing_attr] pub struct TestStruct { # [existing_attr] # [serde (serialize_with = \"crate::u64_serialize\")] # [tsify (type = \"bigint\")] pub foo : u64 , pub bar : u128 }");
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.