@kamino-finance/klend-sdk 5.2.12 → 5.2.14

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.
Files changed (36) hide show
  1. package/dist/classes/manager.d.ts +36 -7
  2. package/dist/classes/manager.d.ts.map +1 -1
  3. package/dist/classes/manager.js +41 -7
  4. package/dist/classes/manager.js.map +1 -1
  5. package/dist/classes/obligation.d.ts +2 -0
  6. package/dist/classes/obligation.d.ts.map +1 -1
  7. package/dist/classes/obligation.js +12 -6
  8. package/dist/classes/obligation.js.map +1 -1
  9. package/dist/classes/types.d.ts +23 -0
  10. package/dist/classes/types.d.ts.map +1 -0
  11. package/dist/classes/types.js +3 -0
  12. package/dist/classes/types.js.map +1 -0
  13. package/dist/classes/vault.d.ts +45 -9
  14. package/dist/classes/vault.d.ts.map +1 -1
  15. package/dist/classes/vault.js +349 -20
  16. package/dist/classes/vault.js.map +1 -1
  17. package/dist/client_kamino_manager.d.ts.map +1 -1
  18. package/dist/client_kamino_manager.js +100 -16
  19. package/dist/client_kamino_manager.js.map +1 -1
  20. package/dist/lending_operations/repay_with_collateral_calcs.d.ts +4 -2
  21. package/dist/lending_operations/repay_with_collateral_calcs.d.ts.map +1 -1
  22. package/dist/lending_operations/repay_with_collateral_calcs.js +45 -52
  23. package/dist/lending_operations/repay_with_collateral_calcs.js.map +1 -1
  24. package/dist/lending_operations/repay_with_collateral_operations.d.ts +7 -0
  25. package/dist/lending_operations/repay_with_collateral_operations.d.ts.map +1 -1
  26. package/dist/lending_operations/repay_with_collateral_operations.js +13 -3
  27. package/dist/lending_operations/repay_with_collateral_operations.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/classes/manager.ts +57 -10
  30. package/src/classes/obligation.ts +15 -6
  31. package/src/classes/types.ts +27 -0
  32. package/src/classes/vault.ts +511 -26
  33. package/src/client_kamino_manager.ts +174 -19
  34. package/src/lending_operations/repay_with_collateral_calcs.ts +55 -61
  35. package/src/lending_operations/repay_with_collateral_operations.ts +24 -4
  36. package/src/leverage/operations.ts +1 -1
@@ -1,6 +1,7 @@
1
1
  import { BN } from '@coral-xyz/anchor';
2
2
  import {
3
3
  AccountMeta,
4
+ AddressLookupTableProgram,
4
5
  Connection,
5
6
  GetProgramAccountsResponse,
6
7
  Keypair,
@@ -42,10 +43,13 @@ import {
42
43
  UpdateVaultConfigArgs,
43
44
  WithdrawAccounts,
44
45
  WithdrawArgs,
46
+ withdrawFromAvailable,
47
+ WithdrawFromAvailableAccounts,
48
+ WithdrawFromAvailableArgs,
45
49
  withdrawPendingFees,
46
50
  WithdrawPendingFeesAccounts,
47
51
  } from '../idl_codegen_kamino_vault/instructions';
48
- import { VaultConfigFieldKind } from '../idl_codegen_kamino_vault/types';
52
+ import { VaultConfigField, VaultConfigFieldKind } from '../idl_codegen_kamino_vault/types';
49
53
  import { VaultState } from '../idl_codegen_kamino_vault/accounts';
50
54
  import Decimal from 'decimal.js';
51
55
  import { bpsToPct, getTokenBalanceFromAccountInfoLamports, numberToLamportsDecimal, parseTokenSymbol } from './utils';
@@ -54,9 +58,17 @@ import { withdraw } from '../idl_codegen_kamino_vault/instructions';
54
58
  import { PROGRAM_ID } from '../idl_codegen/programId';
55
59
  import { DEFAULT_RECENT_SLOT_DURATION_MS, ReserveWithAddress } from './reserve';
56
60
  import { Fraction } from './fraction';
57
- import { createAtasIdempotent, lendingMarketAuthPda } from '../utils';
61
+ import { createAtasIdempotent, lendingMarketAuthPda, PublicKeySet } from '../utils';
58
62
  import bs58 from 'bs58';
59
63
  import { getAccountOwner, getProgramAccounts } from '../utils/rpc';
64
+ import {
65
+ AcceptVaultOwnershipIxs,
66
+ InitVaultIxs,
67
+ SyncVaultLUTIxs,
68
+ UpdateReserveAllocationIxs,
69
+ UpdateVaultConfigIxs,
70
+ } from './types';
71
+ import { collToLamportsDecimal } from '@kamino-finance/kliquidity-sdk';
60
72
 
61
73
  export const kaminoVaultId = new PublicKey('kvauTFR8qm1dhniz6pYuBZkuene3Hfrs1VQhVRgCNrr');
62
74
  export const kaminoVaultStagingId = new PublicKey('STkvh7ostar39Fwr4uZKASs1RNNuYMFMTsE77FiRsL2');
@@ -99,9 +111,9 @@ export class KaminoVaultClient {
99
111
  * This method will create a vault with a given config. The config can be changed later on, but it is recommended to set it up correctly from the start
100
112
  * @param vaultConfig - the config object used to create a vault
101
113
  * @returns vault - keypair, should be used to sign the transaction which creates the vault account
102
- * @returns ixns - an array of instructions to create the vault
114
+ * @returns vault: the keypair of the vault, used to sign the initialization transaction; initVaultIxs: a struct with ixs to initialize the vault and its lookup table + populateLUTIxs, a list to populate the lookup table which has to be executed in a separate transaction
103
115
  */
104
- async createVaultIxs(vaultConfig: KaminoVaultConfig): Promise<{ vault: Keypair; ixns: TransactionInstruction[] }> {
116
+ async createVaultIxs(vaultConfig: KaminoVaultConfig): Promise<{ vault: Keypair; initVaultIxs: InitVaultIxs }> {
105
117
  const vaultState = Keypair.generate();
106
118
  const size = VaultState.layout.span + 8;
107
119
 
@@ -142,9 +154,63 @@ export class KaminoVaultClient {
142
154
  };
143
155
  const initVaultIx = initVault(initVaultAccounts, this._kaminoVaultProgramId);
144
156
 
145
- // TODO: Add logic to update vault based on vaultConfig
157
+ // create and set up the vault lookup table
158
+ const slot = await this._connection.getSlot();
159
+ const [createLUTIx, lut] = this.getInitLookupTableIx(vaultConfig.admin, slot);
160
+
161
+ const accountsToBeInserted = [
162
+ vaultConfig.admin,
163
+ vaultState.publicKey,
164
+ vaultConfig.tokenMint,
165
+ vaultConfig.tokenMintProgramId,
166
+ baseVaultAuthority,
167
+ sharesMint,
168
+ SystemProgram.programId,
169
+ SYSVAR_RENT_PUBKEY,
170
+ TOKEN_PROGRAM_ID,
171
+ this._kaminoLendProgramId,
172
+ SYSVAR_INSTRUCTIONS_PUBKEY,
173
+ ];
174
+ const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(vaultConfig.admin, lut, accountsToBeInserted, []);
175
+
176
+ const setLUTIx = this.updateUninitialisedVaultConfigIx(
177
+ vaultConfig.admin,
178
+ vaultState.publicKey,
179
+ new VaultConfigField.LookupTable(),
180
+ lut.toString()
181
+ );
182
+
183
+ const ixns = [createVaultIx, initVaultIx, createLUTIx, setLUTIx];
184
+
185
+ if (vaultConfig.getPerformanceFeeBps() > 0) {
186
+ const setPerformanceFeeIx = this.updateUninitialisedVaultConfigIx(
187
+ vaultConfig.admin,
188
+ vaultState.publicKey,
189
+ new VaultConfigField.PerformanceFeeBps(),
190
+ vaultConfig.getPerformanceFeeBps().toString()
191
+ );
192
+ ixns.push(setPerformanceFeeIx);
193
+ }
194
+ if (vaultConfig.getManagementFeeBps() > 0) {
195
+ const setManagementFeeIx = this.updateUninitialisedVaultConfigIx(
196
+ vaultConfig.admin,
197
+ vaultState.publicKey,
198
+ new VaultConfigField.ManagementFeeBps(),
199
+ vaultConfig.getManagementFeeBps().toString()
200
+ );
201
+ ixns.push(setManagementFeeIx);
202
+ }
203
+ if (vaultConfig.name && vaultConfig.name.length > 0) {
204
+ const setNameIx = this.updateUninitialisedVaultConfigIx(
205
+ vaultConfig.admin,
206
+ vaultState.publicKey,
207
+ new VaultConfigField.Name(),
208
+ vaultConfig.name
209
+ );
210
+ ixns.push(setNameIx);
211
+ }
146
212
 
147
- return { vault: vaultState, ixns: [createVaultIx, initVaultIx] };
213
+ return { vault: vaultState, initVaultIxs: { initVaultIxs: ixns, populateLUTIxs: insertIntoLUTIxs } };
148
214
  }
149
215
 
150
216
  /**
@@ -156,7 +222,7 @@ export class KaminoVaultClient {
156
222
  async updateReserveAllocationIxs(
157
223
  vault: KaminoVault,
158
224
  reserveAllocationConfig: ReserveAllocationConfig
159
- ): Promise<TransactionInstruction> {
225
+ ): Promise<UpdateReserveAllocationIxs> {
160
226
  const vaultState: VaultState = await vault.getState(this.getConnection());
161
227
  const reserveState: Reserve = reserveAllocationConfig.getReserveState();
162
228
 
@@ -183,25 +249,47 @@ export class KaminoVaultClient {
183
249
  cap: new BN(reserveAllocationConfig.getAllocationCapLamports().floor().toString()),
184
250
  };
185
251
 
186
- return updateReserveAllocation(
252
+ const updateReserveAllocationIx = updateReserveAllocation(
187
253
  updateReserveAllocationArgs,
188
254
  updateReserveAllocationAccounts,
189
255
  this._kaminoVaultProgramId
190
256
  );
257
+
258
+ const accountsToAddToLUT = [
259
+ reserveAllocationConfig.getReserveAddress(),
260
+ cTokenVault,
261
+ ...this.getReserveAccountsToInsertInLut(reserveState),
262
+ ];
263
+
264
+ const lendingMarketAuth = lendingMarketAuthPda(reserveState.lendingMarket, this._kaminoLendProgramId)[0];
265
+ accountsToAddToLUT.push(lendingMarketAuth);
266
+
267
+ const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(
268
+ vaultState.adminAuthority,
269
+ vaultState.vaultLookupTable,
270
+ accountsToAddToLUT
271
+ );
272
+
273
+ const updateReserveAllocationIxs: UpdateReserveAllocationIxs = {
274
+ updateReserveAllocationIx,
275
+ updateLUTIxs: insertIntoLUTIxs,
276
+ };
277
+
278
+ return updateReserveAllocationIxs;
191
279
  }
192
280
 
193
281
  /**
194
- * This method updates the vault config
195
- * @param vault - vault to be updated
196
- * @param mode - the field to be updated
197
- * @param value - the new value for the field to be updated (number or pubkey)
198
- * @returns - a list of instructions
282
+ * Update a field of the vault. If the field is a pubkey it will return an extra instruction to add that account into the lookup table
283
+ * @param vault the vault to update
284
+ * @param mode the field to update (based on VaultConfigFieldKind enum)
285
+ * @param value the value to update the field with
286
+ * @returns a struct that contains the instruction to update the field and an optional list of instructions to update the lookup table
199
287
  */
200
- async updateVaultConfigIx(
288
+ async updateVaultConfigIxs(
201
289
  vault: KaminoVault,
202
290
  mode: VaultConfigFieldKind,
203
291
  value: string
204
- ): Promise<TransactionInstruction> {
292
+ ): Promise<UpdateVaultConfigIxs> {
205
293
  const vaultState: VaultState = await vault.getState(this.getConnection());
206
294
 
207
295
  const updateVaultConfigAccs: UpdateVaultConfigAccounts = {
@@ -216,8 +304,13 @@ export class KaminoVaultClient {
216
304
  };
217
305
 
218
306
  if (isNaN(+value)) {
219
- const data = new PublicKey(value);
220
- updateVaultConfigArgs.data = data.toBuffer();
307
+ if (mode.kind === new VaultConfigField.Name().kind) {
308
+ const data = Array.from(this.encodeVaultName(value));
309
+ updateVaultConfigArgs.data = Buffer.from(data);
310
+ } else {
311
+ const data = new PublicKey(value);
312
+ updateVaultConfigArgs.data = data.toBuffer();
313
+ }
221
314
  } else {
222
315
  const buffer = Buffer.alloc(8);
223
316
  buffer.writeBigUInt64LE(BigInt(value.toString()));
@@ -251,6 +344,70 @@ export class KaminoVaultClient {
251
344
  updateVaultConfigIx.keys = updateVaultConfigIx.keys.concat(vaultReservesAccountMetas);
252
345
  updateVaultConfigIx.keys = updateVaultConfigIx.keys.concat(vaultReservesLendingMarkets);
253
346
 
347
+ const updateLUTIxs = [];
348
+
349
+ if (mode.kind === new VaultConfigField.PendingVaultAdmin().kind || mode.kind === new VaultConfigField.Farm().kind) {
350
+ const newPubkey = new PublicKey(value);
351
+ const insertIntoLutIxs = await this.insertIntoLookupTableIxs(
352
+ vaultState.adminAuthority,
353
+ vaultState.vaultLookupTable,
354
+ [newPubkey]
355
+ );
356
+ updateLUTIxs.push(...insertIntoLutIxs);
357
+ }
358
+
359
+ const updateVaultConfigIxs: UpdateVaultConfigIxs = {
360
+ updateVaultConfigIx,
361
+ updateLUTIxs,
362
+ };
363
+
364
+ return updateVaultConfigIxs;
365
+ }
366
+
367
+ /**
368
+ * This method updates the vault config for a vault that
369
+ * @param vault - address of vault to be updated
370
+ * @param mode - the field to be updated
371
+ * @param value - the new value for the field to be updated (number or pubkey)
372
+ * @returns - a list of instructions
373
+ */
374
+ updateUninitialisedVaultConfigIx(
375
+ admin: PublicKey,
376
+ vault: PublicKey,
377
+ mode: VaultConfigFieldKind,
378
+ value: string
379
+ ): TransactionInstruction {
380
+ const updateVaultConfigAccs: UpdateVaultConfigAccounts = {
381
+ adminAuthority: admin,
382
+ vaultState: vault,
383
+ klendProgram: this._kaminoLendProgramId,
384
+ };
385
+
386
+ const updateVaultConfigArgs: UpdateVaultConfigArgs = {
387
+ entry: mode,
388
+ data: Buffer.from([0]),
389
+ };
390
+
391
+ if (isNaN(+value)) {
392
+ if (mode.kind === new VaultConfigField.Name().kind) {
393
+ const data = Array.from(this.encodeVaultName(value));
394
+ updateVaultConfigArgs.data = Buffer.from(data);
395
+ } else {
396
+ const data = new PublicKey(value);
397
+ updateVaultConfigArgs.data = data.toBuffer();
398
+ }
399
+ } else {
400
+ const buffer = Buffer.alloc(8);
401
+ buffer.writeBigUInt64LE(BigInt(value.toString()));
402
+ updateVaultConfigArgs.data = buffer;
403
+ }
404
+
405
+ const updateVaultConfigIx = updateVaultConfig(
406
+ updateVaultConfigArgs,
407
+ updateVaultConfigAccs,
408
+ this._kaminoVaultProgramId
409
+ );
410
+
254
411
  return updateVaultConfigIx;
255
412
  }
256
413
 
@@ -259,7 +416,7 @@ export class KaminoVaultClient {
259
416
  * @param vault - vault to change the ownership for
260
417
  * @returns - an instruction to be used to be executed
261
418
  */
262
- async acceptVaultOwnershipIx(vault: KaminoVault): Promise<TransactionInstruction> {
419
+ async acceptVaultOwnershipIxs(vault: KaminoVault): Promise<AcceptVaultOwnershipIxs> {
263
420
  const vaultState: VaultState = await vault.getState(this.getConnection());
264
421
 
265
422
  const acceptOwneshipAccounts: UpdateAdminAccounts = {
@@ -267,7 +424,39 @@ export class KaminoVaultClient {
267
424
  vaultState: vault.address,
268
425
  };
269
426
 
270
- return updateAdmin(acceptOwneshipAccounts, this._kaminoVaultProgramId);
427
+ const acceptVaultOwnershipIx = updateAdmin(acceptOwneshipAccounts, this._kaminoVaultProgramId);
428
+
429
+ // read the current LUT and create a new one for the new admin and backfill it
430
+ const accountsInExistentLUT = (await this.getAccountsInLUT(vaultState.vaultLookupTable)).filter(
431
+ (account) => !account.equals(vaultState.adminAuthority)
432
+ );
433
+
434
+ const LUTIxs = [];
435
+ const [initNewLUTIx, newLUT] = this.getInitLookupTableIx(vaultState.pendingAdmin, await this._connection.getSlot());
436
+ LUTIxs.push(initNewLUTIx);
437
+
438
+ const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(
439
+ vaultState.pendingAdmin,
440
+ newLUT,
441
+ accountsInExistentLUT
442
+ );
443
+
444
+ LUTIxs.push(...insertIntoLUTIxs);
445
+
446
+ const updateVaultConfigIxs = await this.updateVaultConfigIxs(
447
+ vault,
448
+ new VaultConfigField.LookupTable(),
449
+ newLUT.toString()
450
+ );
451
+ LUTIxs.push(updateVaultConfigIxs.updateVaultConfigIx);
452
+ LUTIxs.push(...updateVaultConfigIxs.updateLUTIxs);
453
+
454
+ const acceptVaultOwnershipIxs: AcceptVaultOwnershipIxs = {
455
+ acceptVaultOwnershipIx,
456
+ updateLUTIxs: LUTIxs,
457
+ };
458
+
459
+ return acceptVaultOwnershipIxs;
271
460
  }
272
461
 
273
462
  /**
@@ -483,6 +672,57 @@ export class KaminoVaultClient {
483
672
  vaultReservesMap?: PubkeyHashMap<PublicKey, KaminoReserve>
484
673
  ): Promise<TransactionInstruction[]> {
485
674
  const vaultState = await vault.getState(this._connection);
675
+ const kaminoVault = new KaminoVault(vault.address, vaultState, vault.programId);
676
+
677
+ // if the vault has allocations withdraw otherwise wtihdraw from available ix
678
+ const vaultAllocation = vaultState.vaultAllocationStrategy.find(
679
+ (allocation) => ~allocation.reserve.equals(PublicKey.default)
680
+ );
681
+
682
+ if (vaultAllocation) {
683
+ return this.wihdrdrawWithReserveIxns(user, kaminoVault, shareAmount, slot, vaultReservesMap);
684
+ } else {
685
+ return this.withdrawFromAvailableIxns(user, kaminoVault, shareAmount);
686
+ }
687
+ }
688
+
689
+ private async withdrawFromAvailableIxns(
690
+ user: PublicKey,
691
+ vault: KaminoVault,
692
+ shareAmount: Decimal
693
+ ): Promise<TransactionInstruction[]> {
694
+ const vaultState = await vault.getState(this._connection);
695
+ const kaminoVault = new KaminoVault(vault.address, vaultState, vault.programId);
696
+
697
+ const userSharesAta = getAssociatedTokenAddress(vaultState.sharesMint, user);
698
+ const [{ ata: userTokenAta, createAtaIx }] = createAtasIdempotent(user, [
699
+ {
700
+ mint: vaultState.tokenMint,
701
+ tokenProgram: vaultState.tokenProgram,
702
+ },
703
+ ]);
704
+
705
+ const shareLamportsToWithdraw = collToLamportsDecimal(shareAmount, vaultState.sharesMintDecimals.toNumber());
706
+ const withdrawFromAvailableIxn = await this.withdrawFromAvailableIxn(
707
+ user,
708
+ kaminoVault,
709
+ vaultState,
710
+ userSharesAta,
711
+ userTokenAta,
712
+ shareLamportsToWithdraw
713
+ );
714
+
715
+ return [createAtaIx, withdrawFromAvailableIxn];
716
+ }
717
+
718
+ private async wihdrdrawWithReserveIxns(
719
+ user: PublicKey,
720
+ vault: KaminoVault,
721
+ shareAmount: Decimal,
722
+ slot: number,
723
+ vaultReservesMap?: PubkeyHashMap<PublicKey, KaminoReserve>
724
+ ): Promise<TransactionInstruction[]> {
725
+ const vaultState = await vault.getState(this._connection);
486
726
 
487
727
  const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
488
728
 
@@ -589,10 +829,10 @@ export class KaminoVaultClient {
589
829
  async investSingleReserveIxs(
590
830
  payer: PublicKey,
591
831
  vault: KaminoVault,
592
- reserve: ReserveWithAddress
832
+ reserve: ReserveWithAddress,
833
+ vaultReservesMap?: PubkeyHashMap<PublicKey, KaminoReserve>
593
834
  ): Promise<TransactionInstruction[]> {
594
835
  const vaultState = await vault.getState(this._connection);
595
-
596
836
  const cTokenVault = getCTokenVaultPda(vault.address, reserve.address, this._kaminoVaultProgramId);
597
837
  const lendingMarketAuth = lendingMarketAuthPda(reserve.state.lendingMarket, this._kaminoLendProgramId)[0];
598
838
 
@@ -624,14 +864,43 @@ export class KaminoVaultClient {
624
864
  const investIx = invest(investAccounts, this._kaminoVaultProgramId);
625
865
 
626
866
  const vaultReserves = this.getVaultReserves(vaultState);
627
- const vaultReservesAccountMetas: AccountMeta[] = vaultReserves.map((reserve) => {
628
- return { pubkey: reserve, isSigner: false, isWritable: true };
867
+ const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
868
+
869
+ let vaultReservesAccountMetas: AccountMeta[] = [];
870
+ let vaultReservesLendingMarkets: AccountMeta[] = [];
871
+ vaultReserves.forEach((reserve) => {
872
+ const reserveState = vaultReservesState.get(reserve);
873
+ if (reserveState === undefined) {
874
+ throw new Error(`Reserve ${reserve.toBase58()} not found`);
875
+ }
876
+ vaultReservesAccountMetas = vaultReservesAccountMetas.concat([
877
+ { pubkey: reserve, isSigner: false, isWritable: true },
878
+ ]);
879
+ vaultReservesLendingMarkets = vaultReservesLendingMarkets.concat([
880
+ { pubkey: reserveState.state.lendingMarket, isSigner: false, isWritable: false },
881
+ ]);
629
882
  });
630
883
  investIx.keys = investIx.keys.concat(vaultReservesAccountMetas);
884
+ investIx.keys = investIx.keys.concat(vaultReservesLendingMarkets);
631
885
 
632
886
  return [createAtaIx, investIx];
633
887
  }
634
888
 
889
+ encodeVaultName(token: string): Uint8Array {
890
+ const maxArray = new Uint8Array(40);
891
+ const s: Uint8Array = new TextEncoder().encode(token);
892
+ maxArray.set(s);
893
+ return maxArray;
894
+ }
895
+
896
+ decodeVaultName(token: number[]): string {
897
+ const maxArray = new Uint8Array(token);
898
+ let s: string = new TextDecoder().decode(maxArray);
899
+ // Remove trailing zeros and spaces
900
+ s = s.replace(/[\0 ]+$/, '');
901
+ return s;
902
+ }
903
+
635
904
  private withdrawIxn(
636
905
  user: PublicKey,
637
906
  vault: KaminoVault,
@@ -702,6 +971,35 @@ export class KaminoVaultClient {
702
971
  return withdrawIxn;
703
972
  }
704
973
 
974
+ private async withdrawFromAvailableIxn(
975
+ user: PublicKey,
976
+ vault: KaminoVault,
977
+ vaultState: VaultState,
978
+ userSharesAta: PublicKey,
979
+ userTokenAta: PublicKey,
980
+ shareAmountLamports: Decimal
981
+ ): Promise<TransactionInstruction> {
982
+ const withdrawFromAvailableAccounts: WithdrawFromAvailableAccounts = {
983
+ user,
984
+ vaultState: vault.address,
985
+ tokenVault: vaultState.tokenVault,
986
+ baseVaultAuthority: vaultState.baseVaultAuthority,
987
+ userTokenAta: userTokenAta,
988
+ tokenMint: vaultState.tokenMint,
989
+ userSharesAta: userSharesAta,
990
+ sharesMint: vaultState.sharesMint,
991
+ tokenProgram: vaultState.tokenProgram,
992
+ sharesTokenProgram: TOKEN_PROGRAM_ID,
993
+ klendProgram: this._kaminoLendProgramId,
994
+ };
995
+
996
+ const withdrawFromAvailableArgs: WithdrawFromAvailableArgs = {
997
+ sharesAmount: new BN(shareAmountLamports.toString()),
998
+ };
999
+
1000
+ return withdrawFromAvailable(withdrawFromAvailableArgs, withdrawFromAvailableAccounts, this._kaminoVaultProgramId);
1001
+ }
1002
+
705
1003
  private async withdrawPendingFeesIxn(
706
1004
  vault: KaminoVault,
707
1005
  vaultState: VaultState,
@@ -758,6 +1056,189 @@ export class KaminoVaultClient {
758
1056
  return withdrawPendingFeesIxn;
759
1057
  }
760
1058
 
1059
+ /**
1060
+ * Sync a vault for lookup table; create and set the LUT for the vault if needed and fill it with all the needed accounts
1061
+ * @param vault the vault to sync and set the LUT for if needed
1062
+ * @param vaultReserves optional; the state of the reserves in the vault allocation
1063
+ * @returns a struct that contains a list of ix to create the LUT and assign it to the vault if needed + a list of ixs to insert all the accounts in the LUT
1064
+ */
1065
+ async syncVaultLookupTable(
1066
+ vault: KaminoVault,
1067
+ vaultReserves?: PubkeyHashMap<PublicKey, KaminoReserve>
1068
+ ): Promise<SyncVaultLUTIxs> {
1069
+ const vaultState = await vault.getState(this._connection);
1070
+ const allAccountsToBeInserted = [
1071
+ vault.address,
1072
+ vaultState.adminAuthority,
1073
+ vaultState.baseVaultAuthority,
1074
+ vaultState.tokenMint,
1075
+ vaultState.tokenVault,
1076
+ vaultState.sharesMint,
1077
+ vaultState.tokenProgram,
1078
+ this._kaminoLendProgramId,
1079
+ ];
1080
+
1081
+ vaultState.vaultAllocationStrategy.forEach((allocation) => {
1082
+ allAccountsToBeInserted.push(allocation.reserve);
1083
+ allAccountsToBeInserted.push(allocation.ctokenVault);
1084
+ });
1085
+
1086
+ if (vaultReserves) {
1087
+ vaultReserves.forEach((reserve) => {
1088
+ allAccountsToBeInserted.push(reserve.state.lendingMarket);
1089
+ allAccountsToBeInserted.push(reserve.state.farmCollateral);
1090
+ allAccountsToBeInserted.push(reserve.state.farmDebt);
1091
+ allAccountsToBeInserted.push(reserve.state.liquidity.supplyVault);
1092
+ allAccountsToBeInserted.push(reserve.state.liquidity.feeVault);
1093
+ allAccountsToBeInserted.push(reserve.state.collateral.mintPubkey);
1094
+ allAccountsToBeInserted.push(reserve.state.collateral.supplyVault);
1095
+ });
1096
+ } else {
1097
+ const vaultReservesState = await this.loadVaultReserves(vaultState);
1098
+ vaultReservesState.forEach((reserve) => {
1099
+ allAccountsToBeInserted.push(reserve.state.lendingMarket);
1100
+ allAccountsToBeInserted.push(reserve.state.farmCollateral);
1101
+ allAccountsToBeInserted.push(reserve.state.farmDebt);
1102
+ allAccountsToBeInserted.push(reserve.state.liquidity.supplyVault);
1103
+ allAccountsToBeInserted.push(reserve.state.liquidity.feeVault);
1104
+ allAccountsToBeInserted.push(reserve.state.collateral.mintPubkey);
1105
+ allAccountsToBeInserted.push(reserve.state.collateral.supplyVault);
1106
+ });
1107
+ }
1108
+
1109
+ if (!vaultState.vaultFarm.equals(PublicKey.default)) {
1110
+ allAccountsToBeInserted.push(vaultState.vaultFarm);
1111
+ }
1112
+
1113
+ const setupLUTIfNeededIxs: TransactionInstruction[] = [];
1114
+ let lut = vaultState.vaultLookupTable;
1115
+ if (lut.equals(PublicKey.default)) {
1116
+ const recentSlot = await this._connection.getSlot();
1117
+ const [ixn, address] = this.getInitLookupTableIx(vaultState.adminAuthority, recentSlot);
1118
+ setupLUTIfNeededIxs.push(ixn);
1119
+ lut = address;
1120
+
1121
+ // set the new LUT for the vault
1122
+ const updateVaultConfigIxs = await this.updateVaultConfigIxs(
1123
+ vault,
1124
+ new VaultConfigField.LookupTable(),
1125
+ lut.toString()
1126
+ );
1127
+ setupLUTIfNeededIxs.push(updateVaultConfigIxs.updateVaultConfigIx);
1128
+ }
1129
+
1130
+ const ixns: TransactionInstruction[] = [];
1131
+ let overridenExistentAccounts: PublicKey[] | undefined = undefined;
1132
+ if (vaultState.vaultLookupTable.equals(PublicKey.default)) {
1133
+ overridenExistentAccounts = [];
1134
+ }
1135
+ ixns.push(
1136
+ ...(await this.insertIntoLookupTableIxs(
1137
+ vaultState.adminAuthority,
1138
+ lut,
1139
+ allAccountsToBeInserted,
1140
+ overridenExistentAccounts
1141
+ ))
1142
+ );
1143
+
1144
+ return {
1145
+ setupLUTIfNeededIxs,
1146
+ syncLUTIxs: ixns,
1147
+ };
1148
+ }
1149
+
1150
+ getInitLookupTableIx(payer: PublicKey, slot: number): [TransactionInstruction, PublicKey] {
1151
+ const [ixn, address] = AddressLookupTableProgram.createLookupTable({
1152
+ authority: payer,
1153
+ payer,
1154
+ recentSlot: slot,
1155
+ });
1156
+
1157
+ return [ixn, address];
1158
+ }
1159
+
1160
+ getReserveAccountsToInsertInLut(reserveState: Reserve): PublicKey[] {
1161
+ return [
1162
+ reserveState.lendingMarket,
1163
+ reserveState.farmCollateral,
1164
+ reserveState.farmDebt,
1165
+ reserveState.liquidity.mintPubkey,
1166
+ reserveState.liquidity.supplyVault,
1167
+ reserveState.liquidity.feeVault,
1168
+ reserveState.collateral.mintPubkey,
1169
+ reserveState.collateral.supplyVault,
1170
+ ];
1171
+ }
1172
+
1173
+ async insertIntoLookupTableIxs(
1174
+ payer: PublicKey,
1175
+ lookupTable: PublicKey,
1176
+ keys: PublicKey[],
1177
+ accountsInLUT?: PublicKey[]
1178
+ ): Promise<TransactionInstruction[]> {
1179
+ let lutContents = accountsInLUT;
1180
+ if (!accountsInLUT) {
1181
+ lutContents = await this.getAccountsInLUT(lookupTable);
1182
+ } else {
1183
+ lutContents = accountsInLUT;
1184
+ }
1185
+
1186
+ const missingAccounts = keys.filter((key) => !lutContents!.includes(key) && !key.equals(PublicKey.default));
1187
+ // deduplicate missing accounts and remove default accounts and convert it back to an array
1188
+ const missingAccountsList = new PublicKeySet(missingAccounts).toArray();
1189
+
1190
+ const chunkSize = 20;
1191
+ const ixns: TransactionInstruction[] = [];
1192
+
1193
+ for (let i = 0; i < missingAccountsList.length; i += chunkSize) {
1194
+ const chunk = missingAccountsList.slice(i, i + chunkSize);
1195
+ const ixn = AddressLookupTableProgram.extendLookupTable({
1196
+ lookupTable,
1197
+ authority: payer,
1198
+ payer,
1199
+ addresses: chunk,
1200
+ });
1201
+ ixns.push(ixn);
1202
+ }
1203
+
1204
+ return ixns;
1205
+ }
1206
+
1207
+ /**
1208
+ *
1209
+ * @param connection
1210
+ * @param lookupTable
1211
+ * @returns
1212
+ */
1213
+ async getAccountsInLUT(lookupTable: PublicKey): Promise<PublicKey[]> {
1214
+ const lutState = await this._connection.getAddressLookupTable(lookupTable);
1215
+ if (!lutState || !lutState.value) {
1216
+ throw new Error(`Lookup table ${lookupTable} not found`);
1217
+ }
1218
+
1219
+ return lutState.value.state.addresses;
1220
+ }
1221
+
1222
+ deactivateLookupTableIx(payer: PublicKey, lookupTable: PublicKey): TransactionInstruction {
1223
+ const ixn = AddressLookupTableProgram.deactivateLookupTable({
1224
+ authority: payer,
1225
+ lookupTable: lookupTable,
1226
+ });
1227
+
1228
+ return ixn;
1229
+ }
1230
+
1231
+ /// this require the LUT to be deactivated at least 500 blocks before
1232
+ closeLookupTableIx(payer: PublicKey, lookupTable: PublicKey): TransactionInstruction {
1233
+ const ixn = AddressLookupTableProgram.closeLookupTable({
1234
+ authority: payer,
1235
+ recipient: payer,
1236
+ lookupTable: lookupTable,
1237
+ });
1238
+
1239
+ return ixn;
1240
+ }
1241
+
761
1242
  /**
762
1243
  * This method returns the user shares balance for a given vault
763
1244
  * @param user - user to calculate the shares balance for
@@ -1494,6 +1975,8 @@ export class KaminoVaultConfig {
1494
1975
  readonly performanceFeeRate: Decimal;
1495
1976
  /** The management fee rate of the vault, expressed as a decimal */
1496
1977
  readonly managementFeeRate: Decimal;
1978
+ /** The name to be stored on cain for the vault (max 40 characters). */
1979
+ readonly name: string;
1497
1980
 
1498
1981
  constructor(args: {
1499
1982
  admin: PublicKey;
@@ -1501,20 +1984,22 @@ export class KaminoVaultConfig {
1501
1984
  tokenMintProgramId: PublicKey;
1502
1985
  performanceFeeRate: Decimal;
1503
1986
  managementFeeRate: Decimal;
1987
+ name: string;
1504
1988
  }) {
1505
1989
  this.admin = args.admin;
1506
1990
  this.tokenMint = args.tokenMint;
1507
1991
  this.performanceFeeRate = args.performanceFeeRate;
1508
1992
  this.managementFeeRate = args.managementFeeRate;
1509
1993
  this.tokenMintProgramId = args.tokenMintProgramId;
1994
+ this.name = args.name;
1510
1995
  }
1511
1996
 
1512
1997
  getPerformanceFeeBps(): number {
1513
- return this.performanceFeeRate.mul(10000).toNumber();
1998
+ return this.performanceFeeRate.mul(100).toNumber();
1514
1999
  }
1515
2000
 
1516
- getManagementFeeRate(): number {
1517
- return this.managementFeeRate.mul(10000).toNumber();
2001
+ getManagementFeeBps(): number {
2002
+ return this.managementFeeRate.mul(100).toNumber();
1518
2003
  }
1519
2004
  }
1520
2005