@kamino-finance/kliquidity-sdk
Version:
Typescript SDK for interacting with the Kamino Liquidity (kliquidity) protocol
388 lines • 18.6 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrcaService = void 0;
const kit_1 = require("@solana/kit");
const decimal_js_1 = __importDefault(require("decimal.js"));
const axios_1 = __importDefault(require("axios"));
const accounts_1 = require("../@codegen/whirlpools/accounts");
const codamaHelpers_1 = require("../utils/codamaHelpers");
const utils_1 = require("../utils");
const programs_1 = require("../@codegen/whirlpools/programs");
const whirlpools_core_1 = require("@orca-so/whirlpools-core");
function toOptionalAddress(value) {
if (value === undefined || value === null) {
return undefined;
}
return (0, kit_1.address)(value.toString());
}
function setRequiredTokenPrice(tokensPrices, prices, mint) {
const price = prices.spot[mint]?.price;
if (!price) {
throw new Error(`Could not get token ${mint} price`);
}
tokensPrices.set(mint, price);
}
function setOptionalTokenPrice(tokensPrices, prices, mint, logger) {
if (!mint) {
return;
}
const price = prices.spot[mint]?.price;
if (price) {
tokensPrices.set(mint, price);
}
else {
logger.error(`Could not get optional token ${mint} price`);
}
}
function sumAprComponents(feeApr, rewardsApr) {
return rewardsApr.reduce((totalApr, rewardApr) => totalApr.add(rewardApr), new decimal_js_1.default(feeApr));
}
class OrcaService {
_rpc;
_whirlpoolProgramId;
_orcaApiUrl;
_logger;
constructor(rpc, whirlpoolProgramId = programs_1.WHIRLPOOL_PROGRAM_ADDRESS, logger = console) {
this._rpc = rpc;
this._whirlpoolProgramId = whirlpoolProgramId;
this._orcaApiUrl = `https://api.orca.so/v2/solana`;
this._logger = logger;
}
getWhirlpoolProgramId() {
return this._whirlpoolProgramId;
}
// Fetch all Orca whirlpools with pagination support (note there are over 20 pages so it may take a while)
async getOrcaWhirlpools(tokens = []) {
const maxPageSize = 1000;
const maxPages = 100; // Safety limit to prevent infinite loops
const allWhirlpools = [];
let after = undefined;
let hasMore = true;
let pageCount = 0;
while (hasMore && pageCount < maxPages) {
pageCount++;
const url = new URL(`${this._orcaApiUrl}/pools`);
url.searchParams.set('size', maxPageSize.toString());
if (after) {
url.searchParams.set('after', after);
}
// Add token filtering parameters based on the number of tokens provided
if (tokens.length === 1) {
url.searchParams.set('token', tokens[0]);
}
else if (tokens.length === 2) {
url.searchParams.set('tokensBothOf', tokens.join(','));
}
try {
const response = await axios_1.default.get(url.toString());
const data = response.data;
// Add whirlpools from this page to our collection
if (data.data && data.data.length > 0) {
allWhirlpools.push(...data.data);
}
// Check if there are more pages using the meta.cursor.next field
if (data.meta?.cursor?.next) {
after = data.meta.cursor.next;
hasMore = true;
}
else {
hasMore = false;
}
}
catch (error) {
this._logger.error('Error fetching Orca whirlpools page:', error);
throw error;
}
}
if (pageCount >= maxPages) {
this._logger.warn(`Reached maximum page limit (${maxPages}). There might be more whirlpools available.`);
}
return allWhirlpools;
}
async getOrcaWhirlpool(poolAddress) {
const response = await axios_1.default.get(`${this._orcaApiUrl}/pools/${poolAddress}`);
// If the API response has a nested data field that contains the actual pool data
if (response.data.data && typeof response.data.data === 'object') {
return response.data.data;
}
return response.data;
}
getStrategyRewardMint(strategy, collateralInfos, rewardIndex) {
const rewardCollateralId = rewardIndex === 0
? Number(strategy.reward0CollateralId)
: rewardIndex === 1
? Number(strategy.reward1CollateralId)
: Number(strategy.reward2CollateralId);
const rewardMint = collateralInfos[rewardCollateralId]?.mint?.toString();
const rewardDecimals = rewardIndex === 0
? Number(strategy.reward0Decimals)
: rewardIndex === 1
? Number(strategy.reward1Decimals)
: Number(strategy.reward2Decimals);
if (rewardDecimals !== 0 && !rewardMint) {
this._logger.error(`Could not get strategy reward mint for reward index ${rewardIndex} and collateral id ${rewardCollateralId}`);
}
return toOptionalAddress(rewardMint);
}
getPoolRewardMint(pool, rewardIndex) {
return toOptionalAddress(pool.rewards?.[rewardIndex]?.mint?.toString());
}
getRewardsDecimals(pool, strategy) {
const rewardsDecimals = new Map();
const reward0Mint = this.getPoolRewardMint(pool, 0);
const reward1Mint = this.getPoolRewardMint(pool, 1);
const reward2Mint = this.getPoolRewardMint(pool, 2);
if (Number(strategy.reward0Decimals) !== 0 && reward0Mint) {
rewardsDecimals.set(reward0Mint, Number(strategy.reward0Decimals));
}
else if (Number(strategy.reward0Decimals) !== 0) {
this._logger.error(`Could not get Orca API reward mint for pool ${pool.address} at reward index 0`);
}
if (Number(strategy.reward1Decimals) !== 0 && reward1Mint) {
rewardsDecimals.set(reward1Mint, Number(strategy.reward1Decimals));
}
else if (Number(strategy.reward1Decimals) !== 0) {
this._logger.error(`Could not get Orca API reward mint for pool ${pool.address} at reward index 1`);
}
if (Number(strategy.reward2Decimals) !== 0 && reward2Mint) {
rewardsDecimals.set(reward2Mint, Number(strategy.reward2Decimals));
}
else if (Number(strategy.reward2Decimals) !== 0) {
this._logger.error(`Could not get Orca API reward mint for pool ${pool.address} at reward index 2`);
}
return rewardsDecimals;
}
/**
* Get token prices for a strategy - for use with orca sdk
* @param strategy
* @param prices
* @param collateralInfos
* @returns {Record<string, Decimal>} - token prices by mint string
* @private
*/
getTokenPrices(strategy, prices, collateralInfos) {
const tokensPrices = new Map();
const tokenA = collateralInfos[Number(strategy.tokenACollateralId)];
const tokenB = collateralInfos[Number(strategy.tokenBCollateralId)];
const rewardToken0 = collateralInfos[Number(strategy.reward0CollateralId)];
const rewardToken1 = collateralInfos[Number(strategy.reward1CollateralId)];
const rewardToken2 = collateralInfos[Number(strategy.reward2CollateralId)];
const aPrice = prices.spot[tokenA.mint.toString()];
const bPrice = prices.spot[tokenB.mint.toString()];
const reward0Price = Number(strategy.reward0Decimals) !== 0 && rewardToken0 ? prices.spot[rewardToken0.mint.toString()] : null;
const reward1Price = Number(strategy.reward1Decimals) !== 0 && rewardToken1 ? prices.spot[rewardToken1.mint.toString()] : null;
const reward2Price = Number(strategy.reward2Decimals) !== 0 && rewardToken2 ? prices.spot[rewardToken2.mint.toString()] : null;
const mintA = (0, kit_1.address)(strategy.tokenAMint.toString());
const mintB = (0, kit_1.address)(strategy.tokenBMint.toString());
const reward0 = this.getStrategyRewardMint(strategy, collateralInfos, 0);
const reward1 = this.getStrategyRewardMint(strategy, collateralInfos, 1);
const reward2 = this.getStrategyRewardMint(strategy, collateralInfos, 2);
tokensPrices.set(mintA, aPrice.price);
tokensPrices.set(mintB, bPrice.price);
if (reward0Price !== null && reward0) {
if (reward0Price) {
tokensPrices.set(reward0, reward0Price.price);
}
else {
this._logger.error(`Could not get strategy reward0 token ${reward0} price`);
}
}
if (reward1Price !== null && reward1) {
if (reward1Price) {
tokensPrices.set(reward1, reward1Price.price);
}
else {
this._logger.error(`Could not get strategy reward1 token ${reward1} price`);
}
}
if (reward2Price !== null && reward2) {
if (reward2Price) {
tokensPrices.set(reward2, reward2Price.price);
}
else {
this._logger.error(`Could not get strategy reward2 token ${reward2} price`);
}
}
return tokensPrices;
}
getPoolTokensPrices(pool, prices) {
const tokensPrices = new Map();
setRequiredTokenPrice(tokensPrices, prices, (0, kit_1.address)(pool.tokenMintA.toString()));
setRequiredTokenPrice(tokensPrices, prices, (0, kit_1.address)(pool.tokenMintB.toString()));
setOptionalTokenPrice(tokensPrices, prices, this.getPoolRewardMint(pool, 0), this._logger);
setOptionalTokenPrice(tokensPrices, prices, this.getPoolRewardMint(pool, 1), this._logger);
setOptionalTokenPrice(tokensPrices, prices, this.getPoolRewardMint(pool, 2), this._logger);
return tokensPrices;
}
async getStrategyWhirlpoolPoolAprApy(strategy, collateralInfos, prices) {
const position = (0, codamaHelpers_1.unwrapAccount)(await (0, accounts_1.fetchMaybePosition)(this._rpc, strategy.position));
if (!position) {
throw new Error(`Position ${strategy.position.toString()} does not exist`);
}
const pool = await this.getOrcaWhirlpool(strategy.pool);
if (!pool) {
throw Error(`Could not get orca pool data for ${strategy.pool.toString()}`);
}
const priceRange = (0, utils_1.getStrategyPriceRangeOrca)(position.tickLowerIndex, position.tickUpperIndex, strategy, new decimal_js_1.default(pool.price.toString()));
if (priceRange.strategyOutOfRange) {
return {
priceLower: new decimal_js_1.default(priceRange.priceLower),
priceUpper: new decimal_js_1.default(priceRange.priceUpper),
poolPrice: new decimal_js_1.default(pool.price),
strategyOutOfRange: priceRange.strategyOutOfRange,
rewardsApy: [],
rewardsApr: [],
feeApy: utils_1.ZERO,
feeApr: utils_1.ZERO,
totalApy: utils_1.ZERO,
totalApr: utils_1.ZERO,
};
}
const lpFeeRate = new decimal_js_1.default(pool.feeRate);
const volume24hUsd = pool.stats?.['24h']?.volume ?? new decimal_js_1.default(0);
const fee24Usd = new decimal_js_1.default(volume24hUsd).mul(lpFeeRate).toNumber();
const tokensPrices = this.getTokenPrices(strategy, prices, collateralInfos);
const rewardsDecimals = this.getRewardsDecimals(pool, strategy);
const apr = (0, utils_1.estimateAprsForPriceRange)(pool, tokensPrices, fee24Usd, position.tickLowerIndex, position.tickUpperIndex, rewardsDecimals);
const totalApr = sumAprComponents(apr.fee, apr.rewards);
const feeApr = new decimal_js_1.default(apr.fee);
const rewardsApr = apr.rewards.map((r) => new decimal_js_1.default(r));
return {
totalApr,
totalApy: (0, utils_1.aprToApy)(totalApr, 365),
feeApr,
feeApy: (0, utils_1.aprToApy)(feeApr, 365),
rewardsApr,
rewardsApy: rewardsApr.map((x) => (0, utils_1.aprToApy)(x, 365)),
priceLower: new decimal_js_1.default(priceRange.priceLower),
priceUpper: new decimal_js_1.default(priceRange.priceUpper),
poolPrice: new decimal_js_1.default(pool.price),
strategyOutOfRange: priceRange.strategyOutOfRange,
};
}
// strongly recommended to pass lowestTick and highestTick because fetching the lowest and highest existent takes very long
async getWhirlpoolLiquidityDistribution(pool, keepOrder = true, lowestTick, highestTick) {
const whirlpool = await this.getOrcaWhirlpool(pool);
if (!whirlpool) {
throw new Error(`Could not get pool data for Whirlpool ${pool}`);
}
let lowestInitializedTick;
if (lowestTick) {
lowestInitializedTick = lowestTick;
}
else {
lowestInitializedTick = await (0, utils_1.getLowestInitializedTickArrayTickIndex)(this._rpc, pool, whirlpool.tickSpacing);
}
let highestInitializedTick;
if (highestTick) {
highestInitializedTick = highestTick;
}
else {
highestInitializedTick = await (0, utils_1.getHighestInitializedTickArrayTickIndex)(this._rpc, pool, whirlpool.tickSpacing);
}
const orcaLiqDistribution = await (0, utils_1.getLiquidityDistribution)(this._rpc, pool, whirlpool, lowestInitializedTick, highestInitializedTick, this._whirlpoolProgramId);
const liqDistribution = {
currentPrice: new decimal_js_1.default(whirlpool.price),
currentTickIndex: whirlpool.tickCurrentIndex,
distribution: [],
};
orcaLiqDistribution.datapoints.forEach((entry) => {
let priceWithOrder = new decimal_js_1.default(entry.price);
if (!keepOrder) {
priceWithOrder = new decimal_js_1.default(1).div(priceWithOrder);
}
const liq = {
price: priceWithOrder,
liquidity: entry.liquidity,
tickIndex: entry.tickIndex,
};
liqDistribution.distribution.push(liq);
});
return liqDistribution;
}
async getWhirlpoolPositionAprApy(poolPubkey, priceLower, priceUpper, prices, rewardsDecimals) {
const pool = await this.getOrcaWhirlpool(poolPubkey);
if (!pool) {
throw Error(`Could not get orca pool data for ${poolPubkey}`);
}
let strategyOutOfRange = false;
if (priceLower.gt(new decimal_js_1.default(pool.price)) || priceUpper.lt(new decimal_js_1.default(pool.price))) {
strategyOutOfRange = true;
}
if (strategyOutOfRange) {
return {
priceLower,
priceUpper,
strategyOutOfRange,
poolPrice: new decimal_js_1.default(pool.price),
rewardsApy: [],
rewardsApr: [],
feeApy: utils_1.ZERO,
feeApr: utils_1.ZERO,
totalApy: utils_1.ZERO,
totalApr: utils_1.ZERO,
};
}
const lpFeeRate = pool.feeRate;
const volume24hUsd = pool.stats?.['24h']?.volume ?? new decimal_js_1.default(0);
const fee24Usd = new decimal_js_1.default(volume24hUsd).mul(lpFeeRate).toNumber();
const tokensPrices = this.getPoolTokensPrices(pool, prices);
const tickLowerIndex = (0, utils_1.getNearestValidTickIndexFromTickIndex)((0, whirlpools_core_1.priceToTickIndex)(priceLower.toNumber(), pool.tokenA.decimals, pool.tokenB.decimals), pool.tickSpacing);
const tickUpperIndex = (0, utils_1.getNearestValidTickIndexFromTickIndex)((0, whirlpools_core_1.priceToTickIndex)(priceUpper.toNumber(), pool.tokenA.decimals, pool.tokenB.decimals), pool.tickSpacing);
const apr = (0, utils_1.estimateAprsForPriceRange)(pool, tokensPrices, fee24Usd, tickLowerIndex, tickUpperIndex, rewardsDecimals);
const totalApr = sumAprComponents(apr.fee, apr.rewards);
const feeApr = new decimal_js_1.default(apr.fee);
const rewardsApr = apr.rewards.map((r) => new decimal_js_1.default(r));
return {
totalApr,
totalApy: (0, utils_1.aprToApy)(totalApr, 365),
feeApr,
feeApy: (0, utils_1.aprToApy)(feeApr, 365),
rewardsApr,
rewardsApy: rewardsApr.map((x) => (0, utils_1.aprToApy)(x, 365)),
priceLower,
priceUpper,
poolPrice: new decimal_js_1.default(pool.price),
strategyOutOfRange,
};
}
async getGenericPoolInfo(poolPubkey) {
const pool = await this.getOrcaWhirlpool(poolPubkey);
if (!pool) {
throw Error(`Could not get orca pool data for ${poolPubkey.toString()}`);
}
const poolInfo = {
dex: 'ORCA',
address: poolPubkey,
tokenMintA: (0, kit_1.address)(pool.tokenMintA),
tokenMintB: (0, kit_1.address)(pool.tokenMintB),
price: new decimal_js_1.default(pool.price),
feeRate: new decimal_js_1.default(pool.feeRate),
volumeOnLast7d: pool.stats['7d'] ? new decimal_js_1.default(pool.stats['7d'].volume) : undefined,
tvl: pool.tvlUsdc ? new decimal_js_1.default(pool.tvlUsdc) : undefined,
tickSpacing: new decimal_js_1.default(pool.tickSpacing),
// todo(Silviu): get real amount of positions
positions: new decimal_js_1.default(0),
};
return poolInfo;
}
async getPositionsCountByPool(pool) {
const rawPositions = await this._rpc
.getProgramAccounts(programs_1.WHIRLPOOL_PROGRAM_ADDRESS, {
commitment: 'confirmed',
filters: [
// account LAYOUT: https://github.com/orca-so/whirlpools/blob/main/programs/whirlpool/src/state/position.rs#L20
{ dataSize: 216n },
{ memcmp: { bytes: pool.toString(), offset: 8n, encoding: 'base58' } },
],
encoding: 'base64+zstd',
})
.send();
return rawPositions.length;
}
}
exports.OrcaService = OrcaService;
//# sourceMappingURL=OrcaService.js.map