@kamino-finance/klend-sdk 7.3.1 → 7.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,6 +36,7 @@ const farms_sdk_1 = require("@kamino-finance/farms-sdk");
36
36
  const apy_1 = require("@kamino-finance/farms-sdk/dist/utils/apy");
37
37
  const vaultAllocation_1 = require("../utils/vaultAllocation");
38
38
  const farmUtils_1 = require("../utils/farmUtils");
39
+ const readCdnData_1 = require("../utils/readCdnData");
39
40
  exports.kaminoVaultId = (0, kit_1.address)('KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd');
40
41
  exports.kaminoVaultStagingId = (0, kit_1.address)('stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK');
41
42
  const TOKEN_VAULT_SEED = 'token_vault';
@@ -696,67 +697,6 @@ class KaminoVaultClient {
696
697
  * @returns - an instance of DepositIxs which contains the instructions to deposit in vault and the instructions to stake the shares in the farm if the vault has a farm
697
698
  */
698
699
  async depositIxs(user, vault, tokenAmount, vaultReservesMap, farmState) {
699
- const vaultState = await vault.getState();
700
- const tokenProgramID = vaultState.tokenProgram;
701
- const userTokenAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.tokenMint, user.address, tokenProgramID);
702
- const createAtasIxs = [];
703
- const closeAtasIxs = [];
704
- if (vaultState.tokenMint === lib_1.WRAPPED_SOL_MINT) {
705
- const [{ ata: wsolAta, createAtaIx: createWsolAtaIxn }] = await (0, utils_2.createAtasIdempotent)(user, [
706
- {
707
- mint: lib_1.WRAPPED_SOL_MINT,
708
- tokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
709
- },
710
- ]);
711
- createAtasIxs.push(createWsolAtaIxn);
712
- const transferWsolIxs = (0, lib_1.getTransferWsolIxs)(user, wsolAta, (0, kit_1.lamports)(BigInt((0, utils_1.numberToLamportsDecimal)(tokenAmount, vaultState.tokenMintDecimals.toNumber()).ceil().toString())));
713
- createAtasIxs.push(...transferWsolIxs);
714
- }
715
- const [{ ata: userSharesAta, createAtaIx: createSharesAtaIxs }] = await (0, utils_2.createAtasIdempotent)(user, [
716
- {
717
- mint: vaultState.sharesMint,
718
- tokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
719
- },
720
- ]);
721
- createAtasIxs.push(createSharesAtaIxs);
722
- const eventAuthority = await getEventAuthorityPda(this._kaminoVaultProgramId);
723
- const depositAccounts = {
724
- user: user,
725
- vaultState: vault.address,
726
- tokenVault: vaultState.tokenVault,
727
- tokenMint: vaultState.tokenMint,
728
- baseVaultAuthority: vaultState.baseVaultAuthority,
729
- sharesMint: vaultState.sharesMint,
730
- userTokenAta: userTokenAta,
731
- userSharesAta: userSharesAta,
732
- tokenProgram: tokenProgramID,
733
- klendProgram: this._kaminoLendProgramId,
734
- sharesTokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
735
- eventAuthority: eventAuthority,
736
- program: this._kaminoVaultProgramId,
737
- };
738
- const depositArgs = {
739
- maxAmount: new bn_js_1.default((0, utils_1.numberToLamportsDecimal)(tokenAmount, vaultState.tokenMintDecimals.toNumber()).floor().toString()),
740
- };
741
- let depositIx = (0, instructions_1.deposit)(depositArgs, depositAccounts, undefined, this._kaminoVaultProgramId);
742
- const vaultReserves = this.getVaultReserves(vaultState);
743
- const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
744
- depositIx = this.appendRemainingAccountsForVaultReserves(depositIx, vaultReserves, vaultReservesState);
745
- const depositIxs = {
746
- depositIxs: [...createAtasIxs, depositIx, ...closeAtasIxs],
747
- stakeInFarmIfNeededIxs: [],
748
- };
749
- // if there is no farm, we can return the deposit instructions, otherwise include the stake ix in the response
750
- if (!(await vault.hasFarm())) {
751
- return depositIxs;
752
- }
753
- // if there is a farm, stake the shares
754
- const stakeSharesIxs = await this.stakeSharesIxs(user, vault, undefined, farmState);
755
- depositIxs.stakeInFarmIfNeededIxs = stakeSharesIxs;
756
- return depositIxs;
757
- }
758
- // todo (silviu): after all tx indexing works for buy/sell ixs remove this function and use the buyIx in the deposit function above
759
- async buySharesIxs(user, vault, tokenAmount, vaultReservesMap, farmState) {
760
700
  const vaultState = await vault.getState();
761
701
  const tokenProgramID = vaultState.tokenProgram;
762
702
  const userTokenAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.tokenMint, user.address, tokenProgramID);
@@ -926,85 +866,6 @@ class KaminoVaultClient {
926
866
  }
927
867
  return withdrawIxs;
928
868
  }
929
- async sellSharesIxs(user, vault, shareAmountToWithdraw, slot, vaultReservesMap, farmState) {
930
- const vaultState = await vault.getState();
931
- const hasFarm = await vault.hasFarm();
932
- const withdrawIxs = {
933
- unstakeFromFarmIfNeededIxs: [],
934
- withdrawIxs: [],
935
- postWithdrawIxs: [],
936
- };
937
- // compute the total shares the user has (in ATA + in farm) and check if they want to withdraw everything or just a part
938
- let userSharesAtaBalance = new decimal_js_1.default(0);
939
- const userSharesAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user.address);
940
- const userSharesAtaState = await (0, token_2022_1.fetchMaybeToken)(this.getConnection(), userSharesAta);
941
- if (userSharesAtaState.exists) {
942
- const userSharesAtaBalanceInLamports = (0, lib_1.getTokenBalanceFromAccountInfoLamports)(userSharesAtaState);
943
- userSharesAtaBalance = userSharesAtaBalanceInLamports.div(new decimal_js_1.default(10).pow(vaultState.sharesMintDecimals.toString()));
944
- }
945
- let userSharesInFarm = new decimal_js_1.default(0);
946
- if (hasFarm) {
947
- userSharesInFarm = await (0, farm_utils_1.getUserSharesInTokensStakedInFarm)(this.getConnection(), user.address, vaultState.vaultFarm, vaultState.sharesMintDecimals.toNumber());
948
- }
949
- let sharesToWithdraw = shareAmountToWithdraw;
950
- const totalUserShares = userSharesAtaBalance.add(userSharesInFarm);
951
- let withdrawAllShares = false;
952
- if (sharesToWithdraw.gt(totalUserShares)) {
953
- sharesToWithdraw = new decimal_js_1.default(utils_2.U64_MAX.toString()).div(new decimal_js_1.default(10).pow(vaultState.sharesMintDecimals.toString()));
954
- withdrawAllShares = true;
955
- }
956
- // if not enough shares in ATA unstake from farm
957
- const sharesInAtaAreEnoughForWithdraw = sharesToWithdraw.lte(userSharesAtaBalance);
958
- if (hasFarm && !sharesInAtaAreEnoughForWithdraw && userSharesInFarm.gt(0)) {
959
- // if we need to unstake we need to make sure share ata is created
960
- const [{ createAtaIx }] = await (0, utils_2.createAtasIdempotent)(user, [
961
- {
962
- mint: vaultState.sharesMint,
963
- tokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
964
- },
965
- ]);
966
- withdrawIxs.unstakeFromFarmIfNeededIxs.push(createAtaIx);
967
- let shareLamportsToWithdraw = new decimal_js_1.default(utils_2.U64_MAX.toString());
968
- if (!withdrawAllShares) {
969
- const sharesToWithdrawFromFarm = sharesToWithdraw.sub(userSharesAtaBalance);
970
- shareLamportsToWithdraw = (0, kliquidity_sdk_1.collToLamportsDecimal)(sharesToWithdrawFromFarm, vaultState.sharesMintDecimals.toNumber());
971
- }
972
- const unstakeAndWithdrawFromFarmIxs = await (0, farm_utils_1.getFarmUnstakeAndWithdrawIxs)(this.getConnection(), user, shareLamportsToWithdraw, vaultState.vaultFarm, farmState);
973
- withdrawIxs.unstakeFromFarmIfNeededIxs.push(unstakeAndWithdrawFromFarmIxs.unstakeIx);
974
- withdrawIxs.unstakeFromFarmIfNeededIxs.push(unstakeAndWithdrawFromFarmIxs.withdrawIx);
975
- }
976
- // if the vault has allocations withdraw otherwise wtihdraw from available ix
977
- const vaultAllocation = vaultState.vaultAllocationStrategy.find((allocation) => allocation.reserve !== lib_1.DEFAULT_PUBLIC_KEY);
978
- if (vaultAllocation) {
979
- const withdrawFromVaultIxs = await this.sellSharesWithReserveIxs(user, vault, sharesToWithdraw, totalUserShares, slot, vaultReservesMap);
980
- withdrawIxs.withdrawIxs = withdrawFromVaultIxs;
981
- }
982
- else {
983
- const withdrawFromVaultIxs = await this.withdrawFromAvailableIxs(user, vault, sharesToWithdraw);
984
- withdrawIxs.withdrawIxs = withdrawFromVaultIxs;
985
- }
986
- // if the vault is for SOL return the ix to unwrap the SOL
987
- if (vaultState.tokenMint === lib_1.WRAPPED_SOL_MINT) {
988
- const userWsolAta = await (0, lib_1.getAssociatedTokenAddress)(lib_1.WRAPPED_SOL_MINT, user.address);
989
- const unwrapIx = (0, token_2022_1.getCloseAccountInstruction)({
990
- account: userWsolAta,
991
- owner: user,
992
- destination: user.address,
993
- }, { programAddress: token_1.TOKEN_PROGRAM_ADDRESS });
994
- withdrawIxs.postWithdrawIxs.push(unwrapIx);
995
- }
996
- // if we burn all of user's shares close its shares ATA
997
- const burnAllUserShares = sharesToWithdraw.gt(totalUserShares);
998
- if (burnAllUserShares) {
999
- const closeAtaIx = (0, token_2022_1.getCloseAccountInstruction)({
1000
- account: userSharesAta,
1001
- owner: user,
1002
- destination: user.address,
1003
- }, { programAddress: token_1.TOKEN_PROGRAM_ADDRESS });
1004
- withdrawIxs.postWithdrawIxs.push(closeAtaIx);
1005
- }
1006
- return withdrawIxs;
1007
- }
1008
869
  async withdrawFromAvailableIxs(user, vault, shareAmount) {
1009
870
  const vaultState = await vault.getState();
1010
871
  const userSharesAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user.address);
@@ -1018,83 +879,6 @@ class KaminoVaultClient {
1018
879
  const withdrawFromAvailableIxn = await this.withdrawFromAvailableIx(user, vault, vaultState, userSharesAta, userTokenAta, shareLamportsToWithdraw);
1019
880
  return [createAtaIx, withdrawFromAvailableIxn];
1020
881
  }
1021
- async sellSharesWithReserveIxs(user, vault, shareAmount, allUserShares, slot, vaultReservesMap) {
1022
- const vaultState = await vault.getState();
1023
- const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
1024
- const userSharesAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user.address);
1025
- const [{ ata: userTokenAta, createAtaIx }] = await (0, utils_2.createAtasIdempotent)(user, [
1026
- {
1027
- mint: vaultState.tokenMint,
1028
- tokenProgram: vaultState.tokenProgram,
1029
- },
1030
- ]);
1031
- const withdrawAllShares = shareAmount.gte(allUserShares);
1032
- const actualSharesToWithdraw = shareAmount.lte(allUserShares) ? shareAmount : allUserShares;
1033
- const shareLamportsToWithdraw = (0, kliquidity_sdk_1.collToLamportsDecimal)(actualSharesToWithdraw, vaultState.sharesMintDecimals.toNumber());
1034
- const tokensPerShare = await this.getTokensPerShareSingleVault(vault, slot);
1035
- const sharesPerToken = new decimal_js_1.default(1).div(tokensPerShare);
1036
- const tokensToWithdraw = shareLamportsToWithdraw.mul(tokensPerShare);
1037
- let tokenLeftToWithdraw = tokensToWithdraw;
1038
- const availableTokens = new decimal_js_1.default(vaultState.tokenAvailable.toString());
1039
- tokenLeftToWithdraw = tokenLeftToWithdraw.sub(availableTokens);
1040
- const reserveWithSharesAmountToWithdraw = [];
1041
- let isFirstWithdraw = true;
1042
- if (tokenLeftToWithdraw.lte(0)) {
1043
- // Availabe enough to withdraw all - using the first existent reserve
1044
- const firstReserve = vaultState.vaultAllocationStrategy.find((reserve) => reserve.reserve !== lib_1.DEFAULT_PUBLIC_KEY);
1045
- if (withdrawAllShares) {
1046
- reserveWithSharesAmountToWithdraw.push({
1047
- reserve: firstReserve.reserve,
1048
- shares: new decimal_js_1.default(utils_2.U64_MAX.toString()),
1049
- });
1050
- }
1051
- else {
1052
- reserveWithSharesAmountToWithdraw.push({
1053
- reserve: firstReserve.reserve,
1054
- shares: shareLamportsToWithdraw,
1055
- });
1056
- }
1057
- }
1058
- else {
1059
- // Get decreasing order sorted available liquidity to withdraw from each reserve allocated to
1060
- const reserveAllocationAvailableLiquidityToWithdraw = await this.getReserveAllocationAvailableLiquidityToWithdraw(vault, slot, vaultReservesState);
1061
- // sort
1062
- const reserveAllocationAvailableLiquidityToWithdrawSorted = [
1063
- ...reserveAllocationAvailableLiquidityToWithdraw.entries(),
1064
- ].sort((a, b) => b[1].sub(a[1]).toNumber());
1065
- reserveAllocationAvailableLiquidityToWithdrawSorted.forEach(([key, availableLiquidityToWithdraw], _) => {
1066
- if (tokenLeftToWithdraw.gt(0)) {
1067
- let tokensToWithdrawFromReserve = decimal_js_1.default.min(tokenLeftToWithdraw, availableLiquidityToWithdraw);
1068
- if (isFirstWithdraw) {
1069
- tokensToWithdrawFromReserve = tokensToWithdrawFromReserve.add(availableTokens);
1070
- isFirstWithdraw = false;
1071
- }
1072
- if (withdrawAllShares) {
1073
- reserveWithSharesAmountToWithdraw.push({ reserve: key, shares: new decimal_js_1.default(utils_2.U64_MAX.toString()) });
1074
- }
1075
- else {
1076
- // round up to the nearest integer the shares to withdraw
1077
- const sharesToWithdrawFromReserve = tokensToWithdrawFromReserve.mul(sharesPerToken).floor();
1078
- reserveWithSharesAmountToWithdraw.push({ reserve: key, shares: sharesToWithdrawFromReserve });
1079
- }
1080
- tokenLeftToWithdraw = tokenLeftToWithdraw.sub(tokensToWithdrawFromReserve);
1081
- }
1082
- });
1083
- }
1084
- const withdrawIxs = [];
1085
- withdrawIxs.push(createAtaIx);
1086
- for (let reserveIndex = 0; reserveIndex < reserveWithSharesAmountToWithdraw.length; reserveIndex++) {
1087
- const reserveWithTokens = reserveWithSharesAmountToWithdraw[reserveIndex];
1088
- const reserveState = vaultReservesState.get(reserveWithTokens.reserve);
1089
- if (reserveState === undefined) {
1090
- throw new Error(`Reserve ${reserveWithTokens.reserve} not found in vault reserves map`);
1091
- }
1092
- const marketAddress = reserveState.state.lendingMarket;
1093
- const withdrawFromReserveIx = await this.sellIx(user, vault, vaultState, marketAddress, { address: reserveWithTokens.reserve, state: reserveState.state }, userSharesAta, userTokenAta, reserveWithTokens.shares, vaultReservesState);
1094
- withdrawIxs.push(withdrawFromReserveIx);
1095
- }
1096
- return withdrawIxs;
1097
- }
1098
882
  async withdrawWithReserveIxs(user, vault, shareAmount, allUserShares, slot, vaultReservesMap) {
1099
883
  const vaultState = await vault.getState();
1100
884
  const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
@@ -1167,8 +951,8 @@ class KaminoVaultClient {
1167
951
  throw new Error(`Reserve ${reserveWithTokens.reserve} not found in vault reserves map`);
1168
952
  }
1169
953
  const marketAddress = reserveState.state.lendingMarket;
1170
- const withdrawFromReserveIx = await this.withdrawIx(user, vault, vaultState, marketAddress, { address: reserveWithTokens.reserve, state: reserveState.state }, userSharesAta, userTokenAta, reserveWithTokens.shares, vaultReservesState);
1171
- withdrawIxs.push(withdrawFromReserveIx);
954
+ const sellIx = await this.sellIx(user, vault, vaultState, marketAddress, { address: reserveWithTokens.reserve, state: reserveState.state }, userSharesAta, userTokenAta, reserveWithTokens.shares, vaultReservesState);
955
+ withdrawIxs.push(sellIx);
1172
956
  }
1173
957
  return withdrawIxs;
1174
958
  }
@@ -1380,49 +1164,6 @@ class KaminoVaultClient {
1380
1164
  sellIxn = this.appendRemainingAccountsForVaultReserves(sellIxn, vaultReserves, vaultReservesState);
1381
1165
  return sellIxn;
1382
1166
  }
1383
- async withdrawIx(user, vault, vaultState, marketAddress, reserve, userSharesAta, userTokenAta, shareAmountLamports, vaultReservesState) {
1384
- const [lendingMarketAuth] = await (0, utils_2.lendingMarketAuthPda)(marketAddress, this._kaminoLendProgramId);
1385
- const globalConfig = await getKvaultGlobalConfigPda(this._kaminoVaultProgramId);
1386
- const eventAuthority = await getEventAuthorityPda(this._kaminoVaultProgramId);
1387
- const withdrawAccounts = {
1388
- withdrawFromAvailable: {
1389
- user,
1390
- vaultState: vault.address,
1391
- globalConfig: globalConfig,
1392
- tokenVault: vaultState.tokenVault,
1393
- baseVaultAuthority: vaultState.baseVaultAuthority,
1394
- userTokenAta: userTokenAta,
1395
- tokenMint: vaultState.tokenMint,
1396
- userSharesAta: userSharesAta,
1397
- sharesMint: vaultState.sharesMint,
1398
- tokenProgram: vaultState.tokenProgram,
1399
- sharesTokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
1400
- klendProgram: this._kaminoLendProgramId,
1401
- eventAuthority: eventAuthority,
1402
- program: this._kaminoVaultProgramId,
1403
- },
1404
- withdrawFromReserveAccounts: {
1405
- vaultState: vault.address,
1406
- reserve: reserve.address,
1407
- ctokenVault: await getCTokenVaultPda(vault.address, reserve.address, this._kaminoVaultProgramId),
1408
- lendingMarket: marketAddress,
1409
- lendingMarketAuthority: lendingMarketAuth,
1410
- reserveLiquiditySupply: reserve.state.liquidity.supplyVault,
1411
- reserveCollateralMint: reserve.state.collateral.mintPubkey,
1412
- reserveCollateralTokenProgram: token_1.TOKEN_PROGRAM_ADDRESS,
1413
- instructionSysvarAccount: sysvars_1.SYSVAR_INSTRUCTIONS_ADDRESS,
1414
- },
1415
- eventAuthority: eventAuthority,
1416
- program: this._kaminoVaultProgramId,
1417
- };
1418
- const withdrawArgs = {
1419
- sharesAmount: new bn_js_1.default(shareAmountLamports.floor().toString()),
1420
- };
1421
- let withdrawIxn = (0, instructions_1.withdraw)(withdrawArgs, withdrawAccounts, undefined, this._kaminoVaultProgramId);
1422
- const vaultReserves = this.getVaultReserves(vaultState);
1423
- withdrawIxn = this.appendRemainingAccountsForVaultReserves(withdrawIxn, vaultReserves, vaultReservesState);
1424
- return withdrawIxn;
1425
- }
1426
1167
  async withdrawFromAvailableIx(user, vault, vaultState, userSharesAta, userTokenAta, shareAmountLamports) {
1427
1168
  const globalConfig = await getKvaultGlobalConfigPda(this._kaminoVaultProgramId);
1428
1169
  const eventAuthority = await getEventAuthorityPda(this._kaminoVaultProgramId);
@@ -1966,13 +1707,16 @@ class KaminoVaultClient {
1966
1707
  const vaultReservesAddressesSet = new Set(vaults.flatMap((vault) => this.getVaultReserves(vault)));
1967
1708
  const vaultReservesAddresses = [...vaultReservesAddressesSet];
1968
1709
  const deserializedReserves = await (0, kliquidity_sdk_1.batchFetch)(vaultReservesAddresses, (chunk) => this.loadReserializedReserves(chunk));
1969
- const reservesAndOracles = await (0, lib_1.getTokenOracleData)(this.getConnection(), deserializedReserves, oracleAccounts);
1710
+ const [reservesAndOracles, cdnResourcesData] = await Promise.all([
1711
+ (0, lib_1.getTokenOracleData)(this.getConnection(), deserializedReserves, oracleAccounts),
1712
+ (0, readCdnData_1.fetchKaminoCdnData)(),
1713
+ ]);
1970
1714
  const kaminoReserves = new Map();
1971
1715
  reservesAndOracles.forEach(([reserve, oracle], index) => {
1972
1716
  if (!oracle) {
1973
1717
  throw Error(`Could not find oracle for ${(0, utils_1.parseTokenSymbol)(reserve.config.tokenInfo.name)} (${vaultReservesAddresses[index]}) reserve in market ${reserve.lendingMarket}`);
1974
1718
  }
1975
- const kaminoReserve = lib_1.KaminoReserve.initialize(vaultReservesAddresses[index], reserve, oracle, this.getConnection(), this.recentSlotDurationMs);
1719
+ const kaminoReserve = lib_1.KaminoReserve.initialize(vaultReservesAddresses[index], reserve, oracle, this.getConnection(), this.recentSlotDurationMs, cdnResourcesData);
1976
1720
  kaminoReserves.set(kaminoReserve.address, kaminoReserve);
1977
1721
  });
1978
1722
  return kaminoReserves;