@kamino-finance/klend-sdk 3.2.10 → 3.2.11

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.
@@ -55,8 +55,6 @@ yarn kamino-manager add-asset-to-market --market market_address --mint token_min
55
55
  - **staging** - is a boolean flag. If set, staging programs will be used
56
56
  - **multisig** - address string to be used as admin PublicKey. To be used in conjunction with multisig mode
57
57
 
58
-
59
-
60
58
  #### Download a reserve config
61
59
 
62
60
  In order to update a reserve config, you need the latest reserve configuration, to modify. To get the latest, this command can be used:
@@ -65,7 +63,7 @@ In order to update a reserve config, you need the latest reserve configuration,
65
63
  yarn kamino-manager download-reserve-config --reserve reserve_address --staging
66
64
  ```
67
65
 
68
- - **reserve** - address to update the reserve config for
66
+ - **reserve** - address to download the reserve config for
69
67
  - **staging** - is a boolean flag. If set, staging programs will be used
70
68
 
71
69
  #### Update a reserve config
@@ -86,6 +84,49 @@ yarn kamino-manager update-reserve-config --reserve reserve_address --reserve-co
86
84
 
87
85
  A reserve config example can be found [here](https://github.com/Kamino-Finance/klend-sdk/blob/master/configs/reserve_config_example.json)
88
86
 
87
+ #### Download a lending market configuration
88
+
89
+ ```
90
+ yarn kamino-manager download-lending-market-config --lending-market lending_market_address --staging
91
+ ```
92
+
93
+ - **lending-market** - address to download the lending market config for
94
+ - **staging** - is a boolean flag. If set, staging programs will be used
95
+
96
+ #### Download a lending market together with all the associated reserves
97
+
98
+ ```
99
+ yarn kamino-manager download-lending-market-config-and-all-reserves-configs --lending-market lending_market_address --staging
100
+ ```
101
+
102
+ - **lending-market** - address to download the lending market config for
103
+ - **staging** - is a boolean flag. If set, staging programs will be used
104
+
105
+ #### Update a lending market
106
+ ```
107
+ yarn kamino-manager update-lending-market-from-config --lending-market lending_market_address --staging --lending-market-config-path ./configs/lending_market_address/market-lending_market_address.json --mode inspect --staging
108
+ ```
109
+
110
+ - **lending-market** - address of market to update the config for
111
+ - **lending-market-config-path** - the path to the config file to be used
112
+ - **mode** - can have these values:
113
+ - *inspect* - will print an url to the explorer txn inspection, where it can be simulated
114
+ - *simulate* - will print the simulation outputs
115
+ - *execute* - will execute the transaction
116
+ - *multisig* - will print the bs58 transaction to be used within a multisig
117
+ It is recommended to **1. inspect/simulate** and then **2. execute/multisig**
118
+ - **staging** - is a boolean flag. If set, staging programs will be used
119
+
120
+ #### Update a lending market owner
121
+ All markets should be owned by a multisig once they are publicly used and maintained.
122
+ However, to start of with, preparing the configuration and adding all the necessary reserves would take longer under a multisig.
123
+ In order to migrate from a hot wallet (private key on a local machine) you first need to set the lending_market_owner_cached to the new admin (ideally multisig) using the command above, followed by running the following command:
124
+
125
+ ```
126
+ yarn kamino-manager update-lending-market-owner --lending-market lending_market_address --staging --mode multisig
127
+ ```
128
+ **To note** this command can only be executed by the current market lending_market_owner_cached and it will set the lending_market_owner to that address.
129
+
89
130
  #### Create a vault
90
131
  ```
91
132
  yarn kamino-manager create-vault --mint token_mint --staging --mode execute
@@ -125,6 +166,22 @@ This can be used to get scope oracle mappings to be used when configuring the re
125
166
  yarn kamino-manager get-oracle-mappings
126
167
  ```
127
168
 
169
+ #### Useful to know
170
+
171
+ **Exploring the created markets** on the webapp can be done by going to
172
+ https://app.kamino.finance/?STAGING_PROGRAM&market=market_address for the staging program
173
+ https://app.kamino.finance/?market=market_address for the prod program
174
+
175
+ **Creating a new keypair to use as an admin** can be achieved by running the following:
176
+ ```
177
+ solana-keygen new -o path_to_private_key.json
178
+ ```
179
+ make sure to keep the private key **private** and only shar ethe public key.
180
+ If you forget the publickey you can get it by running the following:
181
+ ```
182
+ solana-keygen pubkey path_to_private_key.json
183
+ ```
184
+
128
185
  ## 2. Kamino Manager Class
129
186
 
130
187
  In order to use the kamino manager class, which provides a high-level interface
@@ -1,6 +1,6 @@
1
1
  import { Connection, Keypair, PublicKey, TransactionInstruction } from '@solana/web3.js';
2
2
  import { KaminoVault, KaminoVaultClient, KaminoVaultConfig, ReserveAllocationConfig } from './vault';
3
- import { AddAssetToMarketParams, CreateKaminoMarketParams, ENV, MarketWithAddress, PubkeyHashMap, Reserve, ReserveWithAddress, ScopeOracleConfig } from '../lib';
3
+ import { AddAssetToMarketParams, CreateKaminoMarketParams, ENV, LendingMarket, MarketWithAddress, PubkeyHashMap, Reserve, ReserveWithAddress, ScopeOracleConfig } from '../lib';
4
4
  import { ReserveConfig } from '../idl_codegen/types';
5
5
  import Decimal from 'decimal.js';
6
6
  /**
@@ -142,4 +142,18 @@ export declare class KaminoManager {
142
142
  * @returns - an array of scope oracle configs
143
143
  */
144
144
  getScopeOracleConfigs(feed?: string, cluster?: ENV): Promise<Array<ScopeOracleConfig>>;
145
+ /**
146
+ * This retruns an array of instructions to be used to update the lending market configurations
147
+ * @param marketWithAddress - the market address and market state object
148
+ * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state
149
+ * @returns - an array of instructions
150
+ */
151
+ updateLendingMarketIxs(marketWithAddress: MarketWithAddress, newMarket: LendingMarket): TransactionInstruction[];
152
+ /**
153
+ * This retruns an instruction to be used to update the market owner. This can only be executed by the current lendingMarketOwnerCached
154
+ * @param marketWithAddress - the market address and market state object
155
+ * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state
156
+ * @returns - an array of instructions
157
+ */
158
+ updateLendingMarketOwnerIxs(marketWithAddress: MarketWithAddress): TransactionInstruction;
145
159
  }
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -20,6 +43,7 @@ const programId_1 = require("../idl_codegen/programId");
20
43
  const scope_sdk_1 = require("@hubbleprotocol/scope-sdk");
21
44
  const bn_js_1 = __importDefault(require("bn.js"));
22
45
  const types_1 = require("../idl_codegen/types");
46
+ const anchor = __importStar(require("@coral-xyz/anchor"));
23
47
  /**
24
48
  * KaminoManager is a class that provides a high-level interface to interact with the Kamino Lend and Kamino Vault programs, in order to create and manage a market, as well as vaults
25
49
  */
@@ -308,6 +332,274 @@ class KaminoManager {
308
332
  return scopeOracleConfigs;
309
333
  });
310
334
  }
335
+ /**
336
+ * This retruns an array of instructions to be used to update the lending market configurations
337
+ * @param marketWithAddress - the market address and market state object
338
+ * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state
339
+ * @returns - an array of instructions
340
+ */
341
+ updateLendingMarketIxs(marketWithAddress, newMarket) {
342
+ return parseForChangesMarketConfigAndGetIxs(marketWithAddress, newMarket, this._kaminoLendProgramId);
343
+ }
344
+ /**
345
+ * This retruns an instruction to be used to update the market owner. This can only be executed by the current lendingMarketOwnerCached
346
+ * @param marketWithAddress - the market address and market state object
347
+ * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state
348
+ * @returns - an array of instructions
349
+ */
350
+ updateLendingMarketOwnerIxs(marketWithAddress) {
351
+ const accounts = {
352
+ lendingMarketOwnerCached: marketWithAddress.state.lendingMarketOwnerCached,
353
+ lendingMarket: marketWithAddress.address,
354
+ };
355
+ return (0, lib_1.updateLendingMarketOwner)(accounts, this._kaminoLendProgramId);
356
+ }
311
357
  } // KaminoManager
312
358
  exports.KaminoManager = KaminoManager;
359
+ function parseForChangesMarketConfigAndGetIxs(marketWithAddress, newMarket, programId) {
360
+ const market = marketWithAddress.state;
361
+ const updateLendingMarketIxnsArgs = [];
362
+ for (const key in market.toJSON()) {
363
+ if (key === 'lendingMarketOwner') {
364
+ if (!market.lendingMarketOwner.equals(newMarket.lendingMarketOwner)) {
365
+ updateLendingMarketIxnsArgs.push({
366
+ mode: types_1.UpdateLendingMarketMode.UpdateOwner.discriminator,
367
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateOwner.discriminator, newMarket.lendingMarketOwner),
368
+ });
369
+ }
370
+ }
371
+ else if (key === 'lendingMarketOwnerCached') {
372
+ if (!market.lendingMarketOwnerCached.equals(newMarket.lendingMarketOwnerCached)) {
373
+ updateLendingMarketIxnsArgs.push({
374
+ mode: types_1.UpdateLendingMarketMode.UpdateOwner.discriminator,
375
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateOwner.discriminator, newMarket.lendingMarketOwnerCached),
376
+ });
377
+ }
378
+ }
379
+ else if (key === 'referralFeeBps') {
380
+ if (market.referralFeeBps !== newMarket.referralFeeBps) {
381
+ updateLendingMarketIxnsArgs.push({
382
+ mode: types_1.UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator,
383
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator, newMarket.referralFeeBps),
384
+ });
385
+ }
386
+ }
387
+ else if (key === 'emergencyMode') {
388
+ if (market.emergencyMode !== newMarket.emergencyMode) {
389
+ updateLendingMarketIxnsArgs.push({
390
+ mode: types_1.UpdateLendingMarketMode.UpdateEmergencyMode.discriminator,
391
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateEmergencyMode.discriminator, newMarket.emergencyMode),
392
+ });
393
+ }
394
+ }
395
+ else if (key === 'autodeleverageEnabled') {
396
+ if (market.autodeleverageEnabled !== newMarket.autodeleverageEnabled) {
397
+ updateLendingMarketIxnsArgs.push({
398
+ mode: types_1.UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator,
399
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator, newMarket.autodeleverageEnabled),
400
+ });
401
+ }
402
+ }
403
+ else if (key === 'borrowDisabled') {
404
+ if (market.borrowDisabled !== newMarket.borrowDisabled) {
405
+ updateLendingMarketIxnsArgs.push({
406
+ mode: types_1.UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator,
407
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator, newMarket.borrowDisabled),
408
+ });
409
+ }
410
+ }
411
+ else if (key === 'priceRefreshTriggerToMaxAgePct') {
412
+ if (market.priceRefreshTriggerToMaxAgePct !== newMarket.priceRefreshTriggerToMaxAgePct) {
413
+ updateLendingMarketIxnsArgs.push({
414
+ mode: types_1.UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator,
415
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator, newMarket.priceRefreshTriggerToMaxAgePct),
416
+ });
417
+ }
418
+ }
419
+ else if (key === 'liquidationMaxDebtCloseFactorPct') {
420
+ if (market.liquidationMaxDebtCloseFactorPct !== newMarket.liquidationMaxDebtCloseFactorPct) {
421
+ updateLendingMarketIxnsArgs.push({
422
+ mode: types_1.UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator,
423
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator, newMarket.liquidationMaxDebtCloseFactorPct),
424
+ });
425
+ }
426
+ }
427
+ else if (key === 'insolvencyRiskUnhealthyLtvPct') {
428
+ if (market.insolvencyRiskUnhealthyLtvPct !== newMarket.insolvencyRiskUnhealthyLtvPct) {
429
+ updateLendingMarketIxnsArgs.push({
430
+ mode: types_1.UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator,
431
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator, newMarket.insolvencyRiskUnhealthyLtvPct),
432
+ });
433
+ }
434
+ }
435
+ else if (key === 'minFullLiquidationValueThreshold') {
436
+ if (!market.minFullLiquidationValueThreshold.eq(newMarket.minFullLiquidationValueThreshold)) {
437
+ updateLendingMarketIxnsArgs.push({
438
+ mode: types_1.UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator,
439
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator, newMarket.minFullLiquidationValueThreshold.toNumber()),
440
+ });
441
+ }
442
+ }
443
+ else if (key === 'maxLiquidatableDebtMarketValueAtOnce') {
444
+ if (!market.maxLiquidatableDebtMarketValueAtOnce.eq(newMarket.maxLiquidatableDebtMarketValueAtOnce)) {
445
+ updateLendingMarketIxnsArgs.push({
446
+ mode: types_1.UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator,
447
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator, newMarket.maxLiquidatableDebtMarketValueAtOnce.toNumber()),
448
+ });
449
+ }
450
+ }
451
+ else if (key === 'globalUnhealthyBorrowValue') {
452
+ if (!market.globalUnhealthyBorrowValue.eq(newMarket.globalUnhealthyBorrowValue)) {
453
+ updateLendingMarketIxnsArgs.push({
454
+ mode: types_1.UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator,
455
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator, newMarket.globalUnhealthyBorrowValue.toNumber()),
456
+ });
457
+ }
458
+ }
459
+ else if (key === 'globalAllowedBorrowValue') {
460
+ if (!market.globalAllowedBorrowValue.eq(newMarket.globalAllowedBorrowValue)) {
461
+ updateLendingMarketIxnsArgs.push({
462
+ mode: types_1.UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator,
463
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator, newMarket.globalAllowedBorrowValue.toNumber()),
464
+ });
465
+ }
466
+ }
467
+ else if (key === 'riskCouncil') {
468
+ if (!market.riskCouncil.equals(newMarket.riskCouncil)) {
469
+ updateLendingMarketIxnsArgs.push({
470
+ mode: types_1.UpdateLendingMarketMode.UpdateRiskCouncil.discriminator,
471
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateRiskCouncil.discriminator, newMarket.riskCouncil),
472
+ });
473
+ }
474
+ }
475
+ else if (key === 'multiplierPointsTagBoost') {
476
+ for (let i = 0; i < market.multiplierPointsTagBoost.length; i++) {
477
+ if (market.multiplierPointsTagBoost[i] !== newMarket.multiplierPointsTagBoost[i]) {
478
+ updateLendingMarketIxnsArgs.push({
479
+ mode: types_1.UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator,
480
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator, newMarket.multiplierPointsTagBoost),
481
+ });
482
+ }
483
+ }
484
+ }
485
+ else if (key === 'minNetValueInObligationSf') {
486
+ if (!market.minNetValueInObligationSf.eq(newMarket.minNetValueInObligationSf)) {
487
+ updateLendingMarketIxnsArgs.push({
488
+ mode: types_1.UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator,
489
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator, newMarket.minNetValueInObligationSf.toString()),
490
+ });
491
+ }
492
+ }
493
+ else if (key === 'minValueSkipLiquidationLtvBfChecks') {
494
+ if (!market.minValueSkipLiquidationLtvBfChecks.eq(newMarket.minValueSkipLiquidationLtvBfChecks)) {
495
+ updateLendingMarketIxnsArgs.push({
496
+ mode: types_1.UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator,
497
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator, newMarket.minValueSkipLiquidationLtvBfChecks.toNumber()),
498
+ });
499
+ }
500
+ }
501
+ else if (key === 'elevationGroups') {
502
+ let elevationGroupsDiffs = 0;
503
+ for (let i = 0; i < market.elevationGroups.length; i++) {
504
+ if (market.elevationGroups[i].id !== newMarket.elevationGroups[i].id ||
505
+ market.elevationGroups[i].maxLiquidationBonusBps !== newMarket.elevationGroups[i].maxLiquidationBonusBps ||
506
+ market.elevationGroups[i].ltvPct !== newMarket.elevationGroups[i].ltvPct ||
507
+ market.elevationGroups[i].liquidationThresholdPct !== newMarket.elevationGroups[i].liquidationThresholdPct ||
508
+ market.elevationGroups[i].allowNewLoans !== newMarket.elevationGroups[i].allowNewLoans ||
509
+ market.elevationGroups[i].maxReservesAsCollateral !== newMarket.elevationGroups[i].maxReservesAsCollateral ||
510
+ !market.elevationGroups[i].debtReserve.equals(newMarket.elevationGroups[i].debtReserve)) {
511
+ updateLendingMarketIxnsArgs.push({
512
+ mode: types_1.UpdateLendingMarketMode.UpdateElevationGroup.discriminator,
513
+ value: updateMarketConfigEncodedValue(types_1.UpdateLendingMarketMode.UpdateElevationGroup.discriminator, newMarket.elevationGroups[i]),
514
+ });
515
+ elevationGroupsDiffs++;
516
+ }
517
+ }
518
+ if (elevationGroupsDiffs > 1) {
519
+ throw new Error('Can only update 1 elevation group at a time');
520
+ }
521
+ }
522
+ } // for loop
523
+ const ixns = [];
524
+ updateLendingMarketIxnsArgs.forEach((updateLendingMarketConfigArgs) => {
525
+ ixns.push(updateMarketConfigIx(marketWithAddress, updateLendingMarketConfigArgs.mode, updateLendingMarketConfigArgs.value, programId));
526
+ });
527
+ return ixns;
528
+ }
529
+ function updateMarketConfigEncodedValue(discriminator, value) {
530
+ let buffer = Buffer.alloc(72);
531
+ let valueArray = [];
532
+ let pkBuffer;
533
+ let valueBigInt;
534
+ switch (discriminator) {
535
+ case types_1.UpdateLendingMarketMode.UpdateEmergencyMode.discriminator:
536
+ case types_1.UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator:
537
+ case types_1.UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator:
538
+ case types_1.UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator:
539
+ case types_1.UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator:
540
+ case types_1.UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator:
541
+ buffer.writeUIntLE(value, 0, 1);
542
+ break;
543
+ case types_1.UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator:
544
+ buffer.writeUInt16LE(value, 0);
545
+ break;
546
+ case types_1.UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator:
547
+ case types_1.UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator:
548
+ case types_1.UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator:
549
+ case types_1.UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator:
550
+ case types_1.UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator:
551
+ value = value;
552
+ buffer.writeBigUint64LE(BigInt(value), 0);
553
+ break;
554
+ case types_1.UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator:
555
+ valueArray = value;
556
+ for (let i = 0; i < valueArray.length; i++) {
557
+ buffer.writeUIntLE(valueArray[i], i, 1);
558
+ }
559
+ break;
560
+ case types_1.UpdateLendingMarketMode.UpdateOwner.discriminator:
561
+ case types_1.UpdateLendingMarketMode.UpdateRiskCouncil.discriminator:
562
+ pkBuffer = value.toBuffer();
563
+ pkBuffer.copy(buffer, 0);
564
+ break;
565
+ case types_1.UpdateLendingMarketMode.UpdateElevationGroup.discriminator:
566
+ buffer = serializeElevationGroup(value);
567
+ break;
568
+ case types_1.UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator:
569
+ valueBigInt = BigInt(value);
570
+ for (let i = 0; i < 16; i++) {
571
+ buffer[15 - i] = Number((valueBigInt >> BigInt(i * 8)) & BigInt(0xff));
572
+ }
573
+ break;
574
+ default:
575
+ break;
576
+ }
577
+ return buffer;
578
+ }
579
+ function updateMarketConfigIx(marketWithAddress, modeDiscriminator, value, programId) {
580
+ value;
581
+ const accounts = {
582
+ lendingMarketOwner: marketWithAddress.state.lendingMarketOwner,
583
+ lendingMarket: marketWithAddress.address,
584
+ };
585
+ const args = {
586
+ mode: new anchor.BN(modeDiscriminator),
587
+ value: [...value],
588
+ };
589
+ const ix = (0, lib_1.updateLendingMarket)(args, accounts, programId);
590
+ return ix;
591
+ }
592
+ function serializeElevationGroup(elevationGroup) {
593
+ const buffer = Buffer.alloc(72);
594
+ buffer.writeUInt16LE(elevationGroup.maxLiquidationBonusBps, 0);
595
+ buffer.writeUIntLE(elevationGroup.id, 2, 1);
596
+ buffer.writeUIntLE(elevationGroup.ltvPct, 3, 1);
597
+ buffer.writeUIntLE(elevationGroup.liquidationThresholdPct, 4, 1);
598
+ buffer.writeUIntLE(elevationGroup.allowNewLoans, 5, 1);
599
+ buffer.writeUIntLE(elevationGroup.maxReservesAsCollateral, 6, 1);
600
+ buffer.writeUIntLE(elevationGroup.padding0, 7, 1);
601
+ const debtReserveBuffer = elevationGroup.debtReserve.toBuffer();
602
+ debtReserveBuffer.copy(buffer, 8);
603
+ return buffer;
604
+ }
313
605
  //# sourceMappingURL=manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/classes/manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,6CAOyB;AACzB,mCAAoH;AACpH,gCAoBgB;AAChB,wDAAsD;AACt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,EAAE,KAAK,GAAG,cAAc,CAAC,iBAAiB,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;gBAC7E,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,mBAAS,CAAC,OAAO,CAAC,EAAE,CAAC;oBACvE,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAC3G,MAAM,UAAU,GAAG,IAAA,qBAAe,EAAC,cAAc,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;oBAErE,kBAAkB,CAAC,IAAI,CAAC;wBACtB,uBAAuB,EAAE,UAAU,CAAC,YAAY;wBAChD,IAAI,EAAE,IAAI;wBACV,UAAU,EAAE,UAAU;wBACtB,QAAQ,EAAE,KAAK;wBACf,aAAa,EAAE,cAAc,CAAC,iBAAiB,CAAC,KAAK,CAAC;wBACtD,WAAW,EAAE,cAAc,CAAC,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC;wBACpD,YAAY,EAAE,cAAc,CAAC,UAAU,CAAC,KAAK,CAAC;wBAC9C,OAAO,EAAE,cAAc,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,gBAAgB,CAAC,QAAQ,EAAE;qBAC1E,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;YAED,OAAO,kBAAkB,CAAC;QAC5B,CAAC;KAAA;CACF,CAAC,gBAAgB;AA1XlB,sCA0XC","sourcesContent":["import {\n Connection,\n Keypair,\n PublicKey,\n SystemProgram,\n SYSVAR_RENT_PUBKEY,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { KaminoVault, KaminoVaultClient, KaminoVaultConfig, kaminoVaultId, ReserveAllocationConfig } from './vault';\nimport {\n AddAssetToMarketParams,\n CreateKaminoMarketParams,\n createReserveIxs,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n ENV,\n getReserveOracleConfigs,\n initLendingMarket,\n InitLendingMarketAccounts,\n InitLendingMarketArgs,\n LendingMarket,\n lendingMarketAuthPda,\n MarketWithAddress,\n parseForChangesReserveConfigAndGetIxs,\n parseOracleType,\n PubkeyHashMap,\n Reserve,\n ReserveWithAddress,\n ScopeOracleConfig,\n updateEntireReserveConfigIx,\n} from '../lib';\nimport { PROGRAM_ID } from '../idl_codegen/programId';\nimport { Scope, TokenMetadatas, U16_MAX } from '@hubbleprotocol/scope-sdk';\nimport BN from 'bn.js';\nimport { ReserveConfig } from '../idl_codegen/types';\nimport Decimal from 'decimal.js';\n\n/**\n * KaminoManager is a class that provides a high-level interface to interact with the Kamino Lend and Kamino Vault programs, in order to create and manage a market, as well as vaults\n */\nexport class KaminoManager {\n private readonly _connection: Connection;\n private readonly _kaminoVaultProgramId: PublicKey;\n private readonly _kaminoLendProgramId: PublicKey;\n private readonly _vaultClient: KaminoVaultClient;\n recentSlotDurationMs: number;\n\n constructor(\n connection: Connection,\n kaminoLendProgramId?: PublicKey,\n kaminoVaultProgramId?: PublicKey,\n recentSlotDurationMs?: number\n ) {\n this._connection = connection;\n this._kaminoVaultProgramId = kaminoVaultProgramId ? kaminoVaultProgramId : kaminoVaultId;\n this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : PROGRAM_ID;\n this.recentSlotDurationMs = recentSlotDurationMs ? recentSlotDurationMs : DEFAULT_RECENT_SLOT_DURATION_MS;\n this._vaultClient = new KaminoVaultClient(\n connection,\n this._kaminoVaultProgramId,\n this._kaminoLendProgramId,\n this.recentSlotDurationMs\n );\n }\n\n getConnection() {\n return this._connection;\n }\n\n getProgramID() {\n return this._kaminoVaultProgramId;\n }\n\n /**\n * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.\n * @param params.admin - the admin of the market\n * @returns market keypair - keypair used for market account creation -> to be signed with when executing the transaction\n * @returns ixns - an array of ixns for creating and initializing the market account\n */\n async createMarketIxs(\n params: CreateKaminoMarketParams\n ): Promise<{ market: Keypair; ixns: TransactionInstruction[] }> {\n const marketAccount = Keypair.generate();\n const size = LendingMarket.layout.span + 8;\n const [lendingMarketAuthority, _] = lendingMarketAuthPda(marketAccount.publicKey, this._kaminoLendProgramId);\n const createMarketIxns: TransactionInstruction[] = [];\n\n createMarketIxns.push(\n SystemProgram.createAccount({\n fromPubkey: params.admin,\n newAccountPubkey: marketAccount.publicKey,\n lamports: await this._connection.getMinimumBalanceForRentExemption(size),\n space: size,\n programId: this._kaminoLendProgramId,\n })\n );\n\n const accounts: InitLendingMarketAccounts = {\n lendingMarketOwner: params.admin,\n lendingMarket: marketAccount.publicKey,\n lendingMarketAuthority: lendingMarketAuthority,\n systemProgram: SystemProgram.programId,\n rent: SYSVAR_RENT_PUBKEY,\n };\n\n const args: InitLendingMarketArgs = {\n quoteCurrency: Array(32).fill(0),\n };\n\n createMarketIxns.push(initLendingMarket(args, accounts, this._kaminoLendProgramId));\n\n return { market: marketAccount, ixns: createMarketIxns };\n }\n\n /**\n * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.\n * @param params.admin - the admin of the reserve\n * @param params.marketAddress - the market to create a reserve for, only the market admin can create a reserve for the market\n * @param params.assetConfig - an object that helps generate a default reserve config with some inputs which have to be configured before calling this function\n * @returns reserve - keypair used for reserve creation -> to be signed with when executing the transaction\n * @returns txnIxns - an array of arrays of ixns -> first array for reserve creation, second for updating it with correct params\n */\n async addAssetToMarketIxs(\n params: AddAssetToMarketParams\n ): Promise<{ reserve: Keypair; txnIxns: TransactionInstruction[][] }> {\n const market = await LendingMarket.fetch(this._connection, params.marketAddress, this._kaminoLendProgramId);\n if (!market) {\n throw new Error('Market not found');\n }\n const marketWithAddress: MarketWithAddress = { address: params.marketAddress, state: market };\n\n const reserveAccount = Keypair.generate();\n\n const createReserveInstructions = await createReserveIxs(\n this._connection,\n params.admin,\n params.marketAddress,\n params.assetConfig.mint,\n reserveAccount.publicKey,\n this._kaminoLendProgramId\n );\n\n const updateReserveInstructions = await this.updateReserveIxs(\n marketWithAddress,\n reserveAccount.publicKey,\n params.assetConfig.getReserveConfig(),\n undefined,\n true\n );\n\n const txnIxns: TransactionInstruction[][] = [];\n txnIxns.push(createReserveInstructions);\n txnIxns.push(updateReserveInstructions);\n\n return { reserve: reserveAccount, txnIxns };\n }\n\n /**\n * 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\n * @param vaultConfig - the config object used to create a vault\n * @returns vault - keypair, should be used to sign the transaction which creates the vault account\n * @returns ixns - an array of instructions to create the vault\n */\n async createVaultIxs(vaultConfig: KaminoVaultConfig): Promise<{ vault: Keypair; ixns: TransactionInstruction[] }> {\n return this._vaultClient.createVaultIxs(vaultConfig);\n }\n\n /**\n * This method updates the vault reserve allocation cofnig for an exiting vault reserve, or adds a new reserve to the vault if it does not exist.\n * @param vault - vault to be updated\n * @param reserveAllocationConfig - new reserve allocation config\n * @returns - a list of instructions\n */\n async updateVaultReserveAllocationIxs(\n vault: KaminoVault,\n reserveAllocationConfig: ReserveAllocationConfig\n ): Promise<TransactionInstruction> {\n return this._vaultClient.updateReserveAllocationIxs(vault, reserveAllocationConfig);\n }\n\n /**\n * This method retruns the reserve config for a given reserve\n * @param reserve - reserve to get the config for\n * @returns - the reserve config\n */\n async getReserveConfig(reserve: PublicKey): Promise<ReserveConfig> {\n const reserveState = await Reserve.fetch(this._connection, reserve);\n if (!reserveState) {\n throw new Error('Reserve not found');\n }\n return reserveState.config;\n }\n\n /**\n * This function enables the update of the scope oracle configuration. In order to get a list of scope prices, getScopeOracleConfigs can be used\n * @param market - lending market which owns the reserve\n * @param reserve - reserve which to be updated\n * @param scopeOracleConfig - new scope oracle config\n * @param scopeTwapConfig - new scope twap config\n * @param maxAgeBufferSeconds - buffer to be added to onchain max_age - if oracle price is older than that, txns interacting with the reserve will fail\n * @returns - an array of instructions used update the oracle configuration\n */\n async updateReserveScopeOracleConfigurationIxs(\n market: MarketWithAddress,\n reserve: ReserveWithAddress,\n scopeOracleConfig: ScopeOracleConfig,\n scopeTwapConfig?: ScopeOracleConfig,\n maxAgeBufferSeconds: number = 20\n ): Promise<TransactionInstruction[]> {\n const reserveConfig = reserve.state.config;\n\n let scopeTwapId = U16_MAX;\n if (scopeTwapConfig) {\n scopeTwapId = scopeTwapConfig.oracleId;\n\n // if(scopeTwapConfig.twapSourceId !== scopeOracleConfig.oracleId) {\n // throw new Error('Twap source id must match oracle id');\n // }\n }\n\n const { scopeConfiguration } = getReserveOracleConfigs({\n scopePriceConfigAddress: scopeOracleConfig.scopePriceConfigAddress,\n scopeChain: [scopeOracleConfig.oracleId],\n scopeTwapChain: [scopeTwapId],\n });\n\n const newReserveConfig = new ReserveConfig({\n ...reserveConfig,\n tokenInfo: {\n ...reserveConfig.tokenInfo,\n scopeConfiguration: scopeConfiguration,\n // TODO: Decide if we want to keep this maxAge override for twap & price\n maxAgeTwapSeconds: scopeTwapConfig\n ? new BN(scopeTwapConfig.max_age + maxAgeBufferSeconds)\n : reserveConfig.tokenInfo.maxAgeTwapSeconds,\n maxAgePriceSeconds: new BN(scopeOracleConfig.max_age + maxAgeBufferSeconds),\n },\n });\n\n return this.updateReserveIxs(market, reserve.address, newReserveConfig, reserve.state);\n }\n\n /**\n * This function updates the given reserve with a new config. It can either update the entire reserve config or just update fields which differ between given reserve and existing reserve\n * @param marketWithAddress - the market that owns the reserve to be updated\n * @param reserve - the reserve to be updated\n * @param config - the new reserve configuration to be used for the update\n * @param reserveStateOverride - the reserve state, useful to provide, if already fetched outside this method, in order to avoid an extra rpc call to fetch it. Make sure the reserveConfig has not been updated since fetching the reserveState that you pass in.\n * @param updateEntireConfig - when set to false, it will only update fields that are different between @param config and reserveState.config, set to true it will always update entire reserve config. An entire reserveConfig update might be too large for a multisig transaction\n * @returns - an array of multiple update ixns. If there are many fields that are being updated without the updateEntireConfig=true, multiple transactions might be required to fit all ixns.\n */\n async updateReserveIxs(\n marketWithAddress: MarketWithAddress,\n reserve: PublicKey,\n config: ReserveConfig,\n reserveStateOverride?: Reserve,\n updateEntireConfig: boolean = false\n ): Promise<TransactionInstruction[]> {\n const reserveState = reserveStateOverride\n ? reserveStateOverride\n : (await Reserve.fetch(this._connection, reserve, this._kaminoLendProgramId))!;\n const ixns: TransactionInstruction[] = [];\n\n if (!reserveState || updateEntireConfig) {\n ixns.push(updateEntireReserveConfigIx(marketWithAddress, reserve, config, this._kaminoLendProgramId));\n } else {\n ixns.push(\n ...parseForChangesReserveConfigAndGetIxs(\n marketWithAddress,\n reserveState,\n reserve,\n config,\n this._kaminoLendProgramId\n )\n );\n }\n\n return ixns;\n }\n\n /**\n * This function creates instructions to deposit into a vault. It will also create ATA creation instructions for the vault shares that the user receives in return\n * @param user - user to deposit\n * @param vault - vault to deposit into\n * @param tokenAmount - token amount to be deposited, in decimals (will be converted in lamports)\n * @returns - an array of instructions to be used to be executed\n */\n async depositToVaultIxs(\n user: PublicKey,\n vault: KaminoVault,\n tokenAmount: Decimal\n ): Promise<TransactionInstruction[]> {\n return this._vaultClient.depositIxs(user, vault, tokenAmount);\n }\n\n /**\n * This function will return the missing ATA creation instructions, as well as one or multiple withdraw instructions, based on how many reserves it's needed to withdraw from. This might have to be split in multiple transactions\n * @param user - user to withdraw\n * @param vault - vault to withdraw from\n * @param shareAmount - share amount to withdraw, in order to withdraw everything, any value > user share amount\n * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault\n * @returns an array of instructions to be executed\n */\n async withdrawFromVaultIxs(\n user: PublicKey,\n vault: KaminoVault,\n shareAmount: Decimal,\n slot: number\n ): Promise<TransactionInstruction[]> {\n return this._vaultClient.withdrawIxs(user, vault, shareAmount, slot);\n }\n\n /**\n * This method calculates the token per share value. This will always change based on interest earned from the vault, but calculating it requires a bunch of rpc requests. Caching this for a short duration would be optimal\n * @param vault - vault to calculate tokensPerShare for\n * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault\n * @returns - token per share value\n */\n async getTokensPerShareSingleVault(vault: KaminoVault, slot: number): Promise<Decimal> {\n return this._vaultClient.getTokensPerShareSingleVault(vault, slot);\n }\n\n /**\n * This method returns the user shares balance for a given vault\n * @param user - user to calculate the shares balance for\n * @param vault - vault to calculate shares balance for\n * @returns - user share balance in decimal (not lamports)\n */\n async getUserSharesBalanceSingleVault(user: PublicKey, vault: KaminoVault): Promise<Decimal> {\n return this._vaultClient.getUserSharesBalanceSingleVault(user, vault);\n }\n\n /**\n * This method returns the user shares balance for all existing vaults\n * @param user - user to calculate the shares balance for\n * @param vaultsOverride - the kamino vaults if already fetched, in order to reduce rpc calls\n * @returns - hash map with keyh as vault address and value as user share balance in decimal (not lamports)\n */\n async getUserSharesBalanceAllVaults(\n user: PublicKey,\n vaultsOverride: KaminoVault[]\n ): Promise<PubkeyHashMap<PublicKey, Decimal>> {\n return this._vaultClient.getUserSharesBalanceAllVaults(user, vaultsOverride);\n }\n\n /**\n * @returns - the KaminoVault client\n */\n getKaminoVaultClient(): KaminoVaultClient {\n return this._vaultClient;\n }\n\n /**\n * This will trigger invest by balancing, based on weights, the reserve allocations of the vault. It can either withdraw or deposit into reserves to balance them. This is a function that should be cranked\n * @param kaminoVault - vault to invest from\n * @returns - an array of invest instructions for each invest action required for the vault reserves\n */\n async investAllReserves(kaminoVault: KaminoVault): Promise<TransactionInstruction[]> {\n return this._vaultClient.investAllReservesIxs(kaminoVault);\n }\n\n /**\n * This will trigger invest by balancing, based on weights, the reserve allocation of the vault. It can either withdraw or deposit into the given reserve to balance it\n * @param kaminoVault - vault to invest from\n * @param reserve - reserve to invest into or disinvest from\n * @returns - an array of invest instructions for each invest action required for the vault reserves\n */\n async investSingleReserve(\n kaminoVault: KaminoVault,\n reserveWithAddress: ReserveWithAddress\n ): Promise<TransactionInstruction> {\n return this._vaultClient.investSingleReserveIxs(kaminoVault, reserveWithAddress);\n }\n\n /**\n * This retruns an array of scope oracle configs to be used to set the scope price and twap oracles for a reserve\n * @param feed - scope feed to fetch prices from\n * @param cluster - cluster to fetch from, this should be left unchanged unless working on devnet or locally\n * @returns - an array of scope oracle configs\n */\n async getScopeOracleConfigs(\n feed: string = 'hubble',\n cluster: ENV = 'mainnet-beta'\n ): Promise<Array<ScopeOracleConfig>> {\n const scopeOracleConfigs: Array<ScopeOracleConfig> = [];\n\n const scope = new Scope(cluster, this._connection);\n const oracleMappings = await scope.getOracleMappings({ feed: feed });\n const [, feedConfig] = await scope.getFeedConfiguration({ feed: feed });\n const tokenMetadatas = await TokenMetadatas.fetch(this._connection, feedConfig.tokensMetadata);\n const decoder = new TextDecoder('utf-8');\n\n console.log('feedConfig.tokensMetadata', feedConfig.tokensMetadata);\n\n if (tokenMetadatas === null) {\n throw new Error('TokenMetadatas not found');\n }\n\n for (let index = 0; index < oracleMappings.priceInfoAccounts.length; index++) {\n if (!oracleMappings.priceInfoAccounts[index].equals(PublicKey.default)) {\n const name = decoder.decode(Uint8Array.from(tokenMetadatas.metadatasArray[index].name)).replace(/\\0/g, '');\n const oracleType = parseOracleType(oracleMappings.priceTypes[index]);\n\n scopeOracleConfigs.push({\n scopePriceConfigAddress: feedConfig.oraclePrices,\n name: name,\n oracleType: oracleType,\n oracleId: index,\n oracleAccount: oracleMappings.priceInfoAccounts[index],\n twapEnabled: oracleMappings.twapEnabled[index] === 1,\n twapSourceId: oracleMappings.twapSource[index],\n max_age: tokenMetadatas.metadatasArray[index].maxAgePriceSlots.toNumber(),\n });\n }\n }\n\n return scopeOracleConfigs;\n }\n} // KaminoManager\n"]}
1
+ {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/classes/manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6CAOyB;AACzB,mCAAoH;AACpH,gCAyBgB;AAChB,wDAAsD;AACtD,yDAA2E;AAC3E,kDAAuB;AACvB,gDAA8F;AAE9F,0DAA4C;AAE5C;;GAEG;AACH,MAAa,aAAa;IAOxB,YACE,UAAsB,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O,EAAE,CAAC;AACZ,CAAC;AAED,SAAS,uBAAuB,CAAC,cAA8B;IAC7D,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAChC,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC,sBAAsB,EAAE,CAAC,CAAC,CAAC;IAC/D,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5C,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAChD,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,uBAAuB,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACjE,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACvD,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,uBAAuB,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACjE,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAClD,MAAM,iBAAiB,GAAG,cAAc,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;IAChE,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAClC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n Connection,\n Keypair,\n PublicKey,\n SystemProgram,\n SYSVAR_RENT_PUBKEY,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { KaminoVault, KaminoVaultClient, KaminoVaultConfig, kaminoVaultId, ReserveAllocationConfig } from './vault';\nimport {\n AddAssetToMarketParams,\n CreateKaminoMarketParams,\n createReserveIxs,\n DEFAULT_RECENT_SLOT_DURATION_MS,\n ENV,\n getReserveOracleConfigs,\n initLendingMarket,\n InitLendingMarketAccounts,\n InitLendingMarketArgs,\n LendingMarket,\n lendingMarketAuthPda,\n MarketWithAddress,\n parseForChangesReserveConfigAndGetIxs,\n parseOracleType,\n PubkeyHashMap,\n Reserve,\n ReserveWithAddress,\n ScopeOracleConfig,\n updateEntireReserveConfigIx,\n updateLendingMarket,\n UpdateLendingMarketAccounts,\n UpdateLendingMarketArgs,\n updateLendingMarketOwner,\n UpdateLendingMarketOwnerAccounts,\n} from '../lib';\nimport { PROGRAM_ID } from '../idl_codegen/programId';\nimport { Scope, TokenMetadatas, U16_MAX } from '@hubbleprotocol/scope-sdk';\nimport BN from 'bn.js';\nimport { ElevationGroup, ReserveConfig, UpdateLendingMarketMode } from '../idl_codegen/types';\nimport Decimal from 'decimal.js';\nimport * as anchor from '@coral-xyz/anchor';\n\n/**\n * KaminoManager is a class that provides a high-level interface to interact with the Kamino Lend and Kamino Vault programs, in order to create and manage a market, as well as vaults\n */\nexport class KaminoManager {\n private readonly _connection: Connection;\n private readonly _kaminoVaultProgramId: PublicKey;\n private readonly _kaminoLendProgramId: PublicKey;\n private readonly _vaultClient: KaminoVaultClient;\n recentSlotDurationMs: number;\n\n constructor(\n connection: Connection,\n kaminoLendProgramId?: PublicKey,\n kaminoVaultProgramId?: PublicKey,\n recentSlotDurationMs?: number\n ) {\n this._connection = connection;\n this._kaminoVaultProgramId = kaminoVaultProgramId ? kaminoVaultProgramId : kaminoVaultId;\n this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : PROGRAM_ID;\n this.recentSlotDurationMs = recentSlotDurationMs ? recentSlotDurationMs : DEFAULT_RECENT_SLOT_DURATION_MS;\n this._vaultClient = new KaminoVaultClient(\n connection,\n this._kaminoVaultProgramId,\n this._kaminoLendProgramId,\n this.recentSlotDurationMs\n );\n }\n\n getConnection() {\n return this._connection;\n }\n\n getProgramID() {\n return this._kaminoVaultProgramId;\n }\n\n /**\n * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.\n * @param params.admin - the admin of the market\n * @returns market keypair - keypair used for market account creation -> to be signed with when executing the transaction\n * @returns ixns - an array of ixns for creating and initializing the market account\n */\n async createMarketIxs(\n params: CreateKaminoMarketParams\n ): Promise<{ market: Keypair; ixns: TransactionInstruction[] }> {\n const marketAccount = Keypair.generate();\n const size = LendingMarket.layout.span + 8;\n const [lendingMarketAuthority, _] = lendingMarketAuthPda(marketAccount.publicKey, this._kaminoLendProgramId);\n const createMarketIxns: TransactionInstruction[] = [];\n\n createMarketIxns.push(\n SystemProgram.createAccount({\n fromPubkey: params.admin,\n newAccountPubkey: marketAccount.publicKey,\n lamports: await this._connection.getMinimumBalanceForRentExemption(size),\n space: size,\n programId: this._kaminoLendProgramId,\n })\n );\n\n const accounts: InitLendingMarketAccounts = {\n lendingMarketOwner: params.admin,\n lendingMarket: marketAccount.publicKey,\n lendingMarketAuthority: lendingMarketAuthority,\n systemProgram: SystemProgram.programId,\n rent: SYSVAR_RENT_PUBKEY,\n };\n\n const args: InitLendingMarketArgs = {\n quoteCurrency: Array(32).fill(0),\n };\n\n createMarketIxns.push(initLendingMarket(args, accounts, this._kaminoLendProgramId));\n\n return { market: marketAccount, ixns: createMarketIxns };\n }\n\n /**\n * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.\n * @param params.admin - the admin of the reserve\n * @param params.marketAddress - the market to create a reserve for, only the market admin can create a reserve for the market\n * @param params.assetConfig - an object that helps generate a default reserve config with some inputs which have to be configured before calling this function\n * @returns reserve - keypair used for reserve creation -> to be signed with when executing the transaction\n * @returns txnIxns - an array of arrays of ixns -> first array for reserve creation, second for updating it with correct params\n */\n async addAssetToMarketIxs(\n params: AddAssetToMarketParams\n ): Promise<{ reserve: Keypair; txnIxns: TransactionInstruction[][] }> {\n const market = await LendingMarket.fetch(this._connection, params.marketAddress, this._kaminoLendProgramId);\n if (!market) {\n throw new Error('Market not found');\n }\n const marketWithAddress: MarketWithAddress = { address: params.marketAddress, state: market };\n\n const reserveAccount = Keypair.generate();\n\n const createReserveInstructions = await createReserveIxs(\n this._connection,\n params.admin,\n params.marketAddress,\n params.assetConfig.mint,\n reserveAccount.publicKey,\n this._kaminoLendProgramId\n );\n\n const updateReserveInstructions = await this.updateReserveIxs(\n marketWithAddress,\n reserveAccount.publicKey,\n params.assetConfig.getReserveConfig(),\n undefined,\n true\n );\n\n const txnIxns: TransactionInstruction[][] = [];\n txnIxns.push(createReserveInstructions);\n txnIxns.push(updateReserveInstructions);\n\n return { reserve: reserveAccount, txnIxns };\n }\n\n /**\n * 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\n * @param vaultConfig - the config object used to create a vault\n * @returns vault - keypair, should be used to sign the transaction which creates the vault account\n * @returns ixns - an array of instructions to create the vault\n */\n async createVaultIxs(vaultConfig: KaminoVaultConfig): Promise<{ vault: Keypair; ixns: TransactionInstruction[] }> {\n return this._vaultClient.createVaultIxs(vaultConfig);\n }\n\n /**\n * This method updates the vault reserve allocation cofnig for an exiting vault reserve, or adds a new reserve to the vault if it does not exist.\n * @param vault - vault to be updated\n * @param reserveAllocationConfig - new reserve allocation config\n * @returns - a list of instructions\n */\n async updateVaultReserveAllocationIxs(\n vault: KaminoVault,\n reserveAllocationConfig: ReserveAllocationConfig\n ): Promise<TransactionInstruction> {\n return this._vaultClient.updateReserveAllocationIxs(vault, reserveAllocationConfig);\n }\n\n /**\n * This method retruns the reserve config for a given reserve\n * @param reserve - reserve to get the config for\n * @returns - the reserve config\n */\n async getReserveConfig(reserve: PublicKey): Promise<ReserveConfig> {\n const reserveState = await Reserve.fetch(this._connection, reserve);\n if (!reserveState) {\n throw new Error('Reserve not found');\n }\n return reserveState.config;\n }\n\n /**\n * This function enables the update of the scope oracle configuration. In order to get a list of scope prices, getScopeOracleConfigs can be used\n * @param market - lending market which owns the reserve\n * @param reserve - reserve which to be updated\n * @param scopeOracleConfig - new scope oracle config\n * @param scopeTwapConfig - new scope twap config\n * @param maxAgeBufferSeconds - buffer to be added to onchain max_age - if oracle price is older than that, txns interacting with the reserve will fail\n * @returns - an array of instructions used update the oracle configuration\n */\n async updateReserveScopeOracleConfigurationIxs(\n market: MarketWithAddress,\n reserve: ReserveWithAddress,\n scopeOracleConfig: ScopeOracleConfig,\n scopeTwapConfig?: ScopeOracleConfig,\n maxAgeBufferSeconds: number = 20\n ): Promise<TransactionInstruction[]> {\n const reserveConfig = reserve.state.config;\n\n let scopeTwapId = U16_MAX;\n if (scopeTwapConfig) {\n scopeTwapId = scopeTwapConfig.oracleId;\n\n // if(scopeTwapConfig.twapSourceId !== scopeOracleConfig.oracleId) {\n // throw new Error('Twap source id must match oracle id');\n // }\n }\n\n const { scopeConfiguration } = getReserveOracleConfigs({\n scopePriceConfigAddress: scopeOracleConfig.scopePriceConfigAddress,\n scopeChain: [scopeOracleConfig.oracleId],\n scopeTwapChain: [scopeTwapId],\n });\n\n const newReserveConfig = new ReserveConfig({\n ...reserveConfig,\n tokenInfo: {\n ...reserveConfig.tokenInfo,\n scopeConfiguration: scopeConfiguration,\n // TODO: Decide if we want to keep this maxAge override for twap & price\n maxAgeTwapSeconds: scopeTwapConfig\n ? new BN(scopeTwapConfig.max_age + maxAgeBufferSeconds)\n : reserveConfig.tokenInfo.maxAgeTwapSeconds,\n maxAgePriceSeconds: new BN(scopeOracleConfig.max_age + maxAgeBufferSeconds),\n },\n });\n\n return this.updateReserveIxs(market, reserve.address, newReserveConfig, reserve.state);\n }\n\n /**\n * This function updates the given reserve with a new config. It can either update the entire reserve config or just update fields which differ between given reserve and existing reserve\n * @param marketWithAddress - the market that owns the reserve to be updated\n * @param reserve - the reserve to be updated\n * @param config - the new reserve configuration to be used for the update\n * @param reserveStateOverride - the reserve state, useful to provide, if already fetched outside this method, in order to avoid an extra rpc call to fetch it. Make sure the reserveConfig has not been updated since fetching the reserveState that you pass in.\n * @param updateEntireConfig - when set to false, it will only update fields that are different between @param config and reserveState.config, set to true it will always update entire reserve config. An entire reserveConfig update might be too large for a multisig transaction\n * @returns - an array of multiple update ixns. If there are many fields that are being updated without the updateEntireConfig=true, multiple transactions might be required to fit all ixns.\n */\n async updateReserveIxs(\n marketWithAddress: MarketWithAddress,\n reserve: PublicKey,\n config: ReserveConfig,\n reserveStateOverride?: Reserve,\n updateEntireConfig: boolean = false\n ): Promise<TransactionInstruction[]> {\n const reserveState = reserveStateOverride\n ? reserveStateOverride\n : (await Reserve.fetch(this._connection, reserve, this._kaminoLendProgramId))!;\n const ixns: TransactionInstruction[] = [];\n\n if (!reserveState || updateEntireConfig) {\n ixns.push(updateEntireReserveConfigIx(marketWithAddress, reserve, config, this._kaminoLendProgramId));\n } else {\n ixns.push(\n ...parseForChangesReserveConfigAndGetIxs(\n marketWithAddress,\n reserveState,\n reserve,\n config,\n this._kaminoLendProgramId\n )\n );\n }\n\n return ixns;\n }\n\n /**\n * This function creates instructions to deposit into a vault. It will also create ATA creation instructions for the vault shares that the user receives in return\n * @param user - user to deposit\n * @param vault - vault to deposit into\n * @param tokenAmount - token amount to be deposited, in decimals (will be converted in lamports)\n * @returns - an array of instructions to be used to be executed\n */\n async depositToVaultIxs(\n user: PublicKey,\n vault: KaminoVault,\n tokenAmount: Decimal\n ): Promise<TransactionInstruction[]> {\n return this._vaultClient.depositIxs(user, vault, tokenAmount);\n }\n\n /**\n * This function will return the missing ATA creation instructions, as well as one or multiple withdraw instructions, based on how many reserves it's needed to withdraw from. This might have to be split in multiple transactions\n * @param user - user to withdraw\n * @param vault - vault to withdraw from\n * @param shareAmount - share amount to withdraw, in order to withdraw everything, any value > user share amount\n * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault\n * @returns an array of instructions to be executed\n */\n async withdrawFromVaultIxs(\n user: PublicKey,\n vault: KaminoVault,\n shareAmount: Decimal,\n slot: number\n ): Promise<TransactionInstruction[]> {\n return this._vaultClient.withdrawIxs(user, vault, shareAmount, slot);\n }\n\n /**\n * This method calculates the token per share value. This will always change based on interest earned from the vault, but calculating it requires a bunch of rpc requests. Caching this for a short duration would be optimal\n * @param vault - vault to calculate tokensPerShare for\n * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault\n * @returns - token per share value\n */\n async getTokensPerShareSingleVault(vault: KaminoVault, slot: number): Promise<Decimal> {\n return this._vaultClient.getTokensPerShareSingleVault(vault, slot);\n }\n\n /**\n * This method returns the user shares balance for a given vault\n * @param user - user to calculate the shares balance for\n * @param vault - vault to calculate shares balance for\n * @returns - user share balance in decimal (not lamports)\n */\n async getUserSharesBalanceSingleVault(user: PublicKey, vault: KaminoVault): Promise<Decimal> {\n return this._vaultClient.getUserSharesBalanceSingleVault(user, vault);\n }\n\n /**\n * This method returns the user shares balance for all existing vaults\n * @param user - user to calculate the shares balance for\n * @param vaultsOverride - the kamino vaults if already fetched, in order to reduce rpc calls\n * @returns - hash map with keyh as vault address and value as user share balance in decimal (not lamports)\n */\n async getUserSharesBalanceAllVaults(\n user: PublicKey,\n vaultsOverride: KaminoVault[]\n ): Promise<PubkeyHashMap<PublicKey, Decimal>> {\n return this._vaultClient.getUserSharesBalanceAllVaults(user, vaultsOverride);\n }\n\n /**\n * @returns - the KaminoVault client\n */\n getKaminoVaultClient(): KaminoVaultClient {\n return this._vaultClient;\n }\n\n /**\n * This will trigger invest by balancing, based on weights, the reserve allocations of the vault. It can either withdraw or deposit into reserves to balance them. This is a function that should be cranked\n * @param kaminoVault - vault to invest from\n * @returns - an array of invest instructions for each invest action required for the vault reserves\n */\n async investAllReserves(kaminoVault: KaminoVault): Promise<TransactionInstruction[]> {\n return this._vaultClient.investAllReservesIxs(kaminoVault);\n }\n\n /**\n * This will trigger invest by balancing, based on weights, the reserve allocation of the vault. It can either withdraw or deposit into the given reserve to balance it\n * @param kaminoVault - vault to invest from\n * @param reserve - reserve to invest into or disinvest from\n * @returns - an array of invest instructions for each invest action required for the vault reserves\n */\n async investSingleReserve(\n kaminoVault: KaminoVault,\n reserveWithAddress: ReserveWithAddress\n ): Promise<TransactionInstruction> {\n return this._vaultClient.investSingleReserveIxs(kaminoVault, reserveWithAddress);\n }\n\n /**\n * This retruns an array of scope oracle configs to be used to set the scope price and twap oracles for a reserve\n * @param feed - scope feed to fetch prices from\n * @param cluster - cluster to fetch from, this should be left unchanged unless working on devnet or locally\n * @returns - an array of scope oracle configs\n */\n async getScopeOracleConfigs(\n feed: string = 'hubble',\n cluster: ENV = 'mainnet-beta'\n ): Promise<Array<ScopeOracleConfig>> {\n const scopeOracleConfigs: Array<ScopeOracleConfig> = [];\n\n const scope = new Scope(cluster, this._connection);\n const oracleMappings = await scope.getOracleMappings({ feed: feed });\n const [, feedConfig] = await scope.getFeedConfiguration({ feed: feed });\n const tokenMetadatas = await TokenMetadatas.fetch(this._connection, feedConfig.tokensMetadata);\n const decoder = new TextDecoder('utf-8');\n\n console.log('feedConfig.tokensMetadata', feedConfig.tokensMetadata);\n\n if (tokenMetadatas === null) {\n throw new Error('TokenMetadatas not found');\n }\n\n for (let index = 0; index < oracleMappings.priceInfoAccounts.length; index++) {\n if (!oracleMappings.priceInfoAccounts[index].equals(PublicKey.default)) {\n const name = decoder.decode(Uint8Array.from(tokenMetadatas.metadatasArray[index].name)).replace(/\\0/g, '');\n const oracleType = parseOracleType(oracleMappings.priceTypes[index]);\n\n scopeOracleConfigs.push({\n scopePriceConfigAddress: feedConfig.oraclePrices,\n name: name,\n oracleType: oracleType,\n oracleId: index,\n oracleAccount: oracleMappings.priceInfoAccounts[index],\n twapEnabled: oracleMappings.twapEnabled[index] === 1,\n twapSourceId: oracleMappings.twapSource[index],\n max_age: tokenMetadatas.metadatasArray[index].maxAgePriceSlots.toNumber(),\n });\n }\n }\n\n return scopeOracleConfigs;\n }\n\n /**\n * This retruns an array of instructions to be used to update the lending market configurations\n * @param marketWithAddress - the market address and market state object\n * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state\n * @returns - an array of instructions\n */\n updateLendingMarketIxs(marketWithAddress: MarketWithAddress, newMarket: LendingMarket): TransactionInstruction[] {\n return parseForChangesMarketConfigAndGetIxs(marketWithAddress, newMarket, this._kaminoLendProgramId);\n }\n\n /**\n * This retruns an instruction to be used to update the market owner. This can only be executed by the current lendingMarketOwnerCached\n * @param marketWithAddress - the market address and market state object\n * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state\n * @returns - an array of instructions\n */\n updateLendingMarketOwnerIxs(marketWithAddress: MarketWithAddress): TransactionInstruction {\n const accounts: UpdateLendingMarketOwnerAccounts = {\n lendingMarketOwnerCached: marketWithAddress.state.lendingMarketOwnerCached,\n lendingMarket: marketWithAddress.address,\n };\n\n return updateLendingMarketOwner(accounts, this._kaminoLendProgramId);\n }\n} // KaminoManager\n\nfunction parseForChangesMarketConfigAndGetIxs(\n marketWithAddress: MarketWithAddress,\n newMarket: LendingMarket,\n programId: PublicKey\n): TransactionInstruction[] {\n const market = marketWithAddress.state;\n const updateLendingMarketIxnsArgs: { mode: number; value: Buffer }[] = [];\n for (const key in market.toJSON()) {\n if (key === 'lendingMarketOwner') {\n if (!market.lendingMarketOwner.equals(newMarket.lendingMarketOwner)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateOwner.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateOwner.discriminator,\n newMarket.lendingMarketOwner\n ),\n });\n }\n } else if (key === 'lendingMarketOwnerCached') {\n if (!market.lendingMarketOwnerCached.equals(newMarket.lendingMarketOwnerCached)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateOwner.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateOwner.discriminator,\n newMarket.lendingMarketOwnerCached\n ),\n });\n }\n } else if (key === 'referralFeeBps') {\n if (market.referralFeeBps !== newMarket.referralFeeBps) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator,\n newMarket.referralFeeBps\n ),\n });\n }\n } else if (key === 'emergencyMode') {\n if (market.emergencyMode !== newMarket.emergencyMode) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateEmergencyMode.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateEmergencyMode.discriminator,\n newMarket.emergencyMode\n ),\n });\n }\n } else if (key === 'autodeleverageEnabled') {\n if (market.autodeleverageEnabled !== newMarket.autodeleverageEnabled) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator,\n newMarket.autodeleverageEnabled\n ),\n });\n }\n } else if (key === 'borrowDisabled') {\n if (market.borrowDisabled !== newMarket.borrowDisabled) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator,\n newMarket.borrowDisabled\n ),\n });\n }\n } else if (key === 'priceRefreshTriggerToMaxAgePct') {\n if (market.priceRefreshTriggerToMaxAgePct !== newMarket.priceRefreshTriggerToMaxAgePct) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator,\n newMarket.priceRefreshTriggerToMaxAgePct\n ),\n });\n }\n } else if (key === 'liquidationMaxDebtCloseFactorPct') {\n if (market.liquidationMaxDebtCloseFactorPct !== newMarket.liquidationMaxDebtCloseFactorPct) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator,\n newMarket.liquidationMaxDebtCloseFactorPct\n ),\n });\n }\n } else if (key === 'insolvencyRiskUnhealthyLtvPct') {\n if (market.insolvencyRiskUnhealthyLtvPct !== newMarket.insolvencyRiskUnhealthyLtvPct) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator,\n newMarket.insolvencyRiskUnhealthyLtvPct\n ),\n });\n }\n } else if (key === 'minFullLiquidationValueThreshold') {\n if (!market.minFullLiquidationValueThreshold.eq(newMarket.minFullLiquidationValueThreshold)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator,\n newMarket.minFullLiquidationValueThreshold.toNumber()\n ),\n });\n }\n } else if (key === 'maxLiquidatableDebtMarketValueAtOnce') {\n if (!market.maxLiquidatableDebtMarketValueAtOnce.eq(newMarket.maxLiquidatableDebtMarketValueAtOnce)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator,\n newMarket.maxLiquidatableDebtMarketValueAtOnce.toNumber()\n ),\n });\n }\n } else if (key === 'globalUnhealthyBorrowValue') {\n if (!market.globalUnhealthyBorrowValue.eq(newMarket.globalUnhealthyBorrowValue)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator,\n newMarket.globalUnhealthyBorrowValue.toNumber()\n ),\n });\n }\n } else if (key === 'globalAllowedBorrowValue') {\n if (!market.globalAllowedBorrowValue.eq(newMarket.globalAllowedBorrowValue)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator,\n newMarket.globalAllowedBorrowValue.toNumber()\n ),\n });\n }\n } else if (key === 'riskCouncil') {\n if (!market.riskCouncil.equals(newMarket.riskCouncil)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateRiskCouncil.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateRiskCouncil.discriminator,\n newMarket.riskCouncil\n ),\n });\n }\n } else if (key === 'multiplierPointsTagBoost') {\n for (let i = 0; i < market.multiplierPointsTagBoost.length; i++) {\n if (market.multiplierPointsTagBoost[i] !== newMarket.multiplierPointsTagBoost[i]) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator,\n newMarket.multiplierPointsTagBoost\n ),\n });\n }\n }\n } else if (key === 'minNetValueInObligationSf') {\n if (!market.minNetValueInObligationSf.eq(newMarket.minNetValueInObligationSf)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator,\n newMarket.minNetValueInObligationSf.toString()\n ),\n });\n }\n } else if (key === 'minValueSkipLiquidationLtvBfChecks') {\n if (!market.minValueSkipLiquidationLtvBfChecks.eq(newMarket.minValueSkipLiquidationLtvBfChecks)) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator,\n newMarket.minValueSkipLiquidationLtvBfChecks.toNumber()\n ),\n });\n }\n } else if (key === 'elevationGroups') {\n let elevationGroupsDiffs = 0;\n for (let i = 0; i < market.elevationGroups.length; i++) {\n if (\n market.elevationGroups[i].id !== newMarket.elevationGroups[i].id ||\n market.elevationGroups[i].maxLiquidationBonusBps !== newMarket.elevationGroups[i].maxLiquidationBonusBps ||\n market.elevationGroups[i].ltvPct !== newMarket.elevationGroups[i].ltvPct ||\n market.elevationGroups[i].liquidationThresholdPct !== newMarket.elevationGroups[i].liquidationThresholdPct ||\n market.elevationGroups[i].allowNewLoans !== newMarket.elevationGroups[i].allowNewLoans ||\n market.elevationGroups[i].maxReservesAsCollateral !== newMarket.elevationGroups[i].maxReservesAsCollateral ||\n !market.elevationGroups[i].debtReserve.equals(newMarket.elevationGroups[i].debtReserve)\n ) {\n updateLendingMarketIxnsArgs.push({\n mode: UpdateLendingMarketMode.UpdateElevationGroup.discriminator,\n value: updateMarketConfigEncodedValue(\n UpdateLendingMarketMode.UpdateElevationGroup.discriminator,\n newMarket.elevationGroups[i]\n ),\n });\n elevationGroupsDiffs++;\n }\n }\n if (elevationGroupsDiffs > 1) {\n throw new Error('Can only update 1 elevation group at a time');\n }\n }\n } // for loop\n\n const ixns: TransactionInstruction[] = [];\n\n updateLendingMarketIxnsArgs.forEach((updateLendingMarketConfigArgs) => {\n ixns.push(\n updateMarketConfigIx(\n marketWithAddress,\n updateLendingMarketConfigArgs.mode,\n updateLendingMarketConfigArgs.value,\n programId\n )\n );\n });\n\n return ixns;\n}\n\nfunction updateMarketConfigEncodedValue(\n discriminator: number,\n value: number | number[] | PublicKey | ElevationGroup | string\n): Buffer {\n let buffer: Buffer = Buffer.alloc(72);\n let valueArray: number[] = [];\n let pkBuffer: Buffer;\n let valueBigInt: bigint;\n\n switch (discriminator) {\n case UpdateLendingMarketMode.UpdateEmergencyMode.discriminator:\n case UpdateLendingMarketMode.UpdateLiquidationCloseFactor.discriminator:\n case UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.discriminator:\n case UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.discriminator:\n case UpdateLendingMarketMode.UpdateAutodeleverageEnabled.discriminator:\n case UpdateLendingMarketMode.UpdateBorrowingDisabled.discriminator:\n buffer.writeUIntLE(value as number, 0, 1);\n break;\n case UpdateLendingMarketMode.UpdateReferralFeeBps.discriminator:\n buffer.writeUInt16LE(value as number, 0);\n break;\n case UpdateLendingMarketMode.UpdateLiquidationMaxValue.discriminator:\n case UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.discriminator:\n case UpdateLendingMarketMode.UpdateGlobalUnhealthyBorrow.discriminator:\n case UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.discriminator:\n case UpdateLendingMarketMode.UpdateMinValueSkipPriorityLiqCheck.discriminator:\n value = value as number;\n buffer.writeBigUint64LE(BigInt(value), 0);\n break;\n case UpdateLendingMarketMode.UpdateMultiplierPoints.discriminator:\n valueArray = value as number[];\n for (let i = 0; i < valueArray.length; i++) {\n buffer.writeUIntLE(valueArray[i], i, 1);\n }\n break;\n case UpdateLendingMarketMode.UpdateOwner.discriminator:\n case UpdateLendingMarketMode.UpdateRiskCouncil.discriminator:\n pkBuffer = (value as PublicKey).toBuffer();\n pkBuffer.copy(buffer, 0);\n break;\n case UpdateLendingMarketMode.UpdateElevationGroup.discriminator:\n buffer = serializeElevationGroup(value as ElevationGroup);\n break;\n case UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.discriminator:\n valueBigInt = BigInt(value as string);\n for (let i = 0; i < 16; i++) {\n buffer[15 - i] = Number((valueBigInt >> BigInt(i * 8)) & BigInt(0xff));\n }\n break;\n default:\n break;\n }\n\n return buffer;\n}\n\nfunction updateMarketConfigIx(\n marketWithAddress: MarketWithAddress,\n modeDiscriminator: number,\n value: Buffer,\n programId: PublicKey\n): TransactionInstruction {\n value;\n const accounts: UpdateLendingMarketAccounts = {\n lendingMarketOwner: marketWithAddress.state.lendingMarketOwner,\n lendingMarket: marketWithAddress.address,\n };\n\n const args: UpdateLendingMarketArgs = {\n mode: new anchor.BN(modeDiscriminator),\n value: [...value],\n };\n\n const ix = updateLendingMarket(args, accounts, programId);\n\n return ix;\n}\n\nfunction serializeElevationGroup(elevationGroup: ElevationGroup): Buffer {\n const buffer = Buffer.alloc(72);\n buffer.writeUInt16LE(elevationGroup.maxLiquidationBonusBps, 0);\n buffer.writeUIntLE(elevationGroup.id, 2, 1);\n buffer.writeUIntLE(elevationGroup.ltvPct, 3, 1);\n buffer.writeUIntLE(elevationGroup.liquidationThresholdPct, 4, 1);\n buffer.writeUIntLE(elevationGroup.allowNewLoans, 5, 1);\n buffer.writeUIntLE(elevationGroup.maxReservesAsCollateral, 6, 1);\n buffer.writeUIntLE(elevationGroup.padding0, 7, 1);\n const debtReserveBuffer = elevationGroup.debtReserve.toBuffer();\n debtReserveBuffer.copy(buffer, 8);\n return buffer;\n}\n"]}