@kamino-finance/klend-sdk 7.3.1 → 7.3.2

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.
@@ -696,67 +696,6 @@ class KaminoVaultClient {
696
696
  * @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
697
  */
698
698
  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
699
  const vaultState = await vault.getState();
761
700
  const tokenProgramID = vaultState.tokenProgram;
762
701
  const userTokenAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.tokenMint, user.address, tokenProgramID);
@@ -926,85 +865,6 @@ class KaminoVaultClient {
926
865
  }
927
866
  return withdrawIxs;
928
867
  }
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
868
  async withdrawFromAvailableIxs(user, vault, shareAmount) {
1009
869
  const vaultState = await vault.getState();
1010
870
  const userSharesAta = await (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user.address);
@@ -1018,83 +878,6 @@ class KaminoVaultClient {
1018
878
  const withdrawFromAvailableIxn = await this.withdrawFromAvailableIx(user, vault, vaultState, userSharesAta, userTokenAta, shareLamportsToWithdraw);
1019
879
  return [createAtaIx, withdrawFromAvailableIxn];
1020
880
  }
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
881
  async withdrawWithReserveIxs(user, vault, shareAmount, allUserShares, slot, vaultReservesMap) {
1099
882
  const vaultState = await vault.getState();
1100
883
  const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
@@ -1167,8 +950,8 @@ class KaminoVaultClient {
1167
950
  throw new Error(`Reserve ${reserveWithTokens.reserve} not found in vault reserves map`);
1168
951
  }
1169
952
  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);
953
+ const sellIx = await this.sellIx(user, vault, vaultState, marketAddress, { address: reserveWithTokens.reserve, state: reserveState.state }, userSharesAta, userTokenAta, reserveWithTokens.shares, vaultReservesState);
954
+ withdrawIxs.push(sellIx);
1172
955
  }
1173
956
  return withdrawIxs;
1174
957
  }
@@ -1380,49 +1163,6 @@ class KaminoVaultClient {
1380
1163
  sellIxn = this.appendRemainingAccountsForVaultReserves(sellIxn, vaultReserves, vaultReservesState);
1381
1164
  return sellIxn;
1382
1165
  }
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
1166
  async withdrawFromAvailableIx(user, vault, vaultState, userSharesAta, userTokenAta, shareAmountLamports) {
1427
1167
  const globalConfig = await getKvaultGlobalConfigPda(this._kaminoVaultProgramId);
1428
1168
  const eventAuthority = await getEventAuthorityPda(this._kaminoVaultProgramId);