@drift-labs/sdk 0.2.0-master.3 → 0.2.0-master.6

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.
package/lib/admin.d.ts CHANGED
@@ -5,7 +5,7 @@ import { BN } from '@project-serum/anchor';
5
5
  import { ClearingHouse } from './clearingHouse';
6
6
  export declare class Admin extends ClearingHouse {
7
7
  initialize(usdcMint: PublicKey, adminControlsPrices: boolean): Promise<[TransactionSignature]>;
8
- initializeBank(mint: PublicKey, optimalUtilization: BN, optimalRate: BN, maxRate: BN, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: BN, maintenanceAssetWeight: BN, initialLiabilityWeight: BN, maintenanceLiabilityWeight: BN): Promise<TransactionSignature>;
8
+ initializeBank(mint: PublicKey, optimalUtilization: BN, optimalRate: BN, maxRate: BN, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: BN, maintenanceAssetWeight: BN, initialLiabilityWeight: BN, maintenanceLiabilityWeight: BN, imfFactor?: BN): Promise<TransactionSignature>;
9
9
  initializeMarket(priceOracle: PublicKey, baseAssetReserve: BN, quoteAssetReserve: BN, periodicity: BN, pegMultiplier?: BN, oracleSource?: OracleSource, marginRatioInitial?: number, marginRatioPartial?: number, marginRatioMaintenance?: number): Promise<TransactionSignature>;
10
10
  moveAmmPrice(baseAssetReserve: BN, quoteAssetReserve: BN, marketIndex: BN): Promise<TransactionSignature>;
11
11
  updateK(sqrtK: BN, marketIndex: BN): Promise<TransactionSignature>;
@@ -14,7 +14,7 @@ export declare class Admin extends ClearingHouse {
14
14
  updateAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
15
15
  resetAmmOracleTwap(marketIndex: BN): Promise<TransactionSignature>;
16
16
  withdrawFromInsuranceVault(amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
17
- withdrawFees(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
17
+ withdrawFromMarketToInsuranceVault(marketIndex: BN, amount: BN, recipient: PublicKey): Promise<TransactionSignature>;
18
18
  withdrawFromInsuranceVaultToMarket(marketIndex: BN, amount: BN): Promise<TransactionSignature>;
19
19
  updateAdmin(admin: PublicKey): Promise<TransactionSignature>;
20
20
  updateCurveUpdateIntensity(marketIndex: BN, curveUpdateIntensity: number): Promise<TransactionSignature>;
@@ -38,5 +38,7 @@ export declare class Admin extends ClearingHouse {
38
38
  updateFundingPaused(fundingPaused: boolean): Promise<TransactionSignature>;
39
39
  updateExchangePaused(exchangePaused: boolean): Promise<TransactionSignature>;
40
40
  disableAdminControlsPrices(): Promise<TransactionSignature>;
41
- updateOrderAuctionTime(time: BN | number): Promise<TransactionSignature>;
41
+ updateAuctionDuration(minDuration: BN | number, maxDuration: BN | number): Promise<TransactionSignature>;
42
+ updateMaxBaseAssetAmountRatio(marketIndex: BN, maxBaseAssetAmountRatio: number): Promise<TransactionSignature>;
43
+ updateMaxSlippageRatio(marketIndex: BN, maxSlippageRatio: number): Promise<TransactionSignature>;
42
44
  }
package/lib/admin.js CHANGED
@@ -58,12 +58,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
58
58
  const { txSig: initializeTxSig } = await this.txSender.send(initializeTx, [], this.opts);
59
59
  return [initializeTxSig];
60
60
  }
61
- async initializeBank(mint, optimalUtilization, optimalRate, maxRate, oracle, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight) {
61
+ async initializeBank(mint, optimalUtilization, optimalRate, maxRate, oracle, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor = new anchor_1.BN(0)) {
62
62
  const bankIndex = this.getStateAccount().numberOfBanks;
63
63
  const bank = await (0, pda_1.getBankPublicKey)(this.program.programId, bankIndex);
64
64
  const bankVault = await (0, pda_1.getBankVaultPublicKey)(this.program.programId, bankIndex);
65
65
  const bankVaultAuthority = await (0, pda_1.getBankVaultAuthorityPublicKey)(this.program.programId, bankIndex);
66
- const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, {
66
+ const initializeTx = await this.program.transaction.initializeBank(optimalUtilization, optimalRate, maxRate, oracleSource, initialAssetWeight, maintenanceAssetWeight, initialLiabilityWeight, maintenanceLiabilityWeight, imfFactor, {
67
67
  accounts: {
68
68
  admin: this.wallet.publicKey,
69
69
  state: await this.getStatePublicKey(),
@@ -177,10 +177,12 @@ class Admin extends clearingHouse_1.ClearingHouse {
177
177
  }
178
178
  async withdrawFromInsuranceVault(amount, recipient) {
179
179
  const state = await this.getStateAccount();
180
+ const bank = this.getQuoteAssetBankAccount();
180
181
  return await this.program.rpc.withdrawFromInsuranceVault(amount, {
181
182
  accounts: {
182
183
  admin: this.wallet.publicKey,
183
184
  state: await this.getStatePublicKey(),
185
+ bank: bank.pubkey,
184
186
  insuranceVault: state.insuranceVault,
185
187
  insuranceVaultAuthority: state.insuranceVaultAuthority,
186
188
  recipient: recipient,
@@ -188,10 +190,10 @@ class Admin extends clearingHouse_1.ClearingHouse {
188
190
  },
189
191
  });
190
192
  }
191
- async withdrawFees(marketIndex, amount, recipient) {
193
+ async withdrawFromMarketToInsuranceVault(marketIndex, amount, recipient) {
192
194
  const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex);
193
195
  const bank = this.getQuoteAssetBankAccount();
194
- return await this.program.rpc.withdrawFees(amount, {
196
+ return await this.program.rpc.withdrawFromMarketToInsuranceVault(amount, {
195
197
  accounts: {
196
198
  admin: this.wallet.publicKey,
197
199
  state: await this.getStatePublicKey(),
@@ -206,6 +208,7 @@ class Admin extends clearingHouse_1.ClearingHouse {
206
208
  }
207
209
  async withdrawFromInsuranceVaultToMarket(marketIndex, amount) {
208
210
  const state = await this.getStateAccount();
211
+ const bank = this.getQuoteAssetBankAccount();
209
212
  return await this.program.rpc.withdrawFromInsuranceVaultToMarket(amount, {
210
213
  accounts: {
211
214
  admin: this.wallet.publicKey,
@@ -213,7 +216,9 @@ class Admin extends clearingHouse_1.ClearingHouse {
213
216
  market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
214
217
  insuranceVault: state.insuranceVault,
215
218
  insuranceVaultAuthority: state.insuranceVaultAuthority,
216
- bankVault: this.getQuoteAssetBankAccount().vault,
219
+ bank: bank.pubkey,
220
+ bankVault: bank.vault,
221
+ bankVaultAuthority: bank.vaultAuthority,
217
222
  tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
218
223
  },
219
224
  });
@@ -403,11 +408,29 @@ class Admin extends clearingHouse_1.ClearingHouse {
403
408
  },
404
409
  });
405
410
  }
406
- async updateOrderAuctionTime(time) {
407
- return await this.program.rpc.updateOrderAuctionTime(typeof time === 'number' ? time : time.toNumber, {
411
+ async updateAuctionDuration(minDuration, maxDuration) {
412
+ return await this.program.rpc.updateAuctionDuration(typeof minDuration === 'number' ? minDuration : minDuration.toNumber(), typeof maxDuration === 'number' ? maxDuration : maxDuration.toNumber(), {
413
+ accounts: {
414
+ admin: this.wallet.publicKey,
415
+ state: await this.getStatePublicKey(),
416
+ },
417
+ });
418
+ }
419
+ async updateMaxBaseAssetAmountRatio(marketIndex, maxBaseAssetAmountRatio) {
420
+ return await this.program.rpc.updateMaxBaseAssetAmountRatio(maxBaseAssetAmountRatio, {
421
+ accounts: {
422
+ admin: this.wallet.publicKey,
423
+ state: await this.getStatePublicKey(),
424
+ market: this.getMarketAccount(marketIndex).pubkey,
425
+ },
426
+ });
427
+ }
428
+ async updateMaxSlippageRatio(marketIndex, maxSlippageRatio) {
429
+ return await this.program.rpc.updateMaxSlippageRatio(maxSlippageRatio, {
408
430
  accounts: {
409
431
  admin: this.wallet.publicKey,
410
432
  state: await this.getStatePublicKey(),
433
+ market: this.getMarketAccount(marketIndex).pubkey,
411
434
  },
412
435
  });
413
436
  }
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="bn.js" />
3
3
  import { AnchorProvider, BN, Program } from '@project-serum/anchor';
4
- import { StateAccount, IWallet, PositionDirection, UserAccount, MarketAccount, OrderParams, Order, BankAccount, UserBankBalance, MakerInfo } from './types';
4
+ import { StateAccount, IWallet, PositionDirection, UserAccount, MarketAccount, OrderParams, Order, BankAccount, UserBankBalance, MakerInfo, TakerInfo, OptionalOrderParams } from './types';
5
5
  import { Connection, PublicKey, TransactionSignature, ConfirmOptions, TransactionInstruction, AccountMeta } from '@solana/web3.js';
6
6
  import { MockUSDCFaucet } from './mockUSDCFaucet';
7
7
  import { EventEmitter } from 'events';
@@ -95,8 +95,9 @@ export declare class ClearingHouse {
95
95
  updateBankCumulativeInterest(bankIndex: BN): Promise<TransactionSignature>;
96
96
  updateBankCumulativeInterestIx(bankIndex: BN): Promise<TransactionInstruction>;
97
97
  openPosition(direction: PositionDirection, amount: BN, marketIndex: BN, limitPrice?: BN): Promise<TransactionSignature>;
98
- placeOrder(orderParams: OrderParams): Promise<TransactionSignature>;
99
- getPlaceOrderIx(orderParams: OrderParams): Promise<TransactionInstruction>;
98
+ placeOrder(orderParams: OptionalOrderParams): Promise<TransactionSignature>;
99
+ getOrderParams(optionalOrderParams: OptionalOrderParams): OrderParams;
100
+ getPlaceOrderIx(orderParams: OptionalOrderParams): Promise<TransactionInstruction>;
100
101
  updateAMMs(marketIndexes: BN[]): Promise<TransactionSignature>;
101
102
  getUpdateAMMsIx(marketIndexes: BN[]): Promise<TransactionInstruction>;
102
103
  cancelOrder(orderId?: BN): Promise<TransactionSignature>;
@@ -107,8 +108,10 @@ export declare class ClearingHouse {
107
108
  getFillOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Order, makerInfo?: MakerInfo): Promise<TransactionInstruction>;
108
109
  triggerOrder(userAccountPublicKey: PublicKey, user: UserAccount, order: Order): Promise<TransactionSignature>;
109
110
  getTriggerOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Order): Promise<TransactionInstruction>;
110
- placeAndTake(orderParams: OrderParams, makerInfo?: MakerInfo): Promise<TransactionSignature>;
111
- getPlaceAndTakeIx(orderParams: OrderParams, makerInfo?: MakerInfo): Promise<TransactionInstruction>;
111
+ placeAndTake(orderParams: OptionalOrderParams, makerInfo?: MakerInfo): Promise<TransactionSignature>;
112
+ getPlaceAndTakeIx(orderParams: OptionalOrderParams, makerInfo?: MakerInfo): Promise<TransactionInstruction>;
113
+ placeAndMake(orderParams: OptionalOrderParams, takerInfo: TakerInfo): Promise<TransactionSignature>;
114
+ getPlaceAndMakeIx(orderParams: OptionalOrderParams, takerInfo: TakerInfo): Promise<TransactionInstruction>;
112
115
  /**
113
116
  * Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
114
117
  * @param marketIndex
@@ -29,6 +29,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.ClearingHouse = void 0;
30
30
  const anchor_1 = require("@project-serum/anchor");
31
31
  const spl_token_1 = require("@solana/spl-token");
32
+ const types_1 = require("./types");
32
33
  const anchor = __importStar(require("@project-serum/anchor"));
33
34
  const clearing_house_json_1 = __importDefault(require("./idl/clearing_house.json"));
34
35
  const web3_js_1 = require("@solana/web3.js");
@@ -42,7 +43,6 @@ const pollingClearingHouseAccountSubscriber_1 = require("./accounts/pollingClear
42
43
  const webSocketClearingHouseAccountSubscriber_1 = require("./accounts/webSocketClearingHouseAccountSubscriber");
43
44
  const retryTxSender_1 = require("./tx/retryTxSender");
44
45
  const clearingHouseUser_1 = require("./clearingHouseUser");
45
- const orderParams_1 = require("./orderParams");
46
46
  const config_1 = require("./config");
47
47
  /**
48
48
  * # ClearingHouse
@@ -371,13 +371,19 @@ class ClearingHouse {
371
371
  });
372
372
  }
373
373
  else {
374
- remainingAccounts = [
375
- {
376
- pubkey: this.getBankAccount(bankIndex).pubkey,
374
+ const bankAccount = this.getBankAccount(bankIndex);
375
+ if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
376
+ remainingAccounts.push({
377
+ pubkey: bankAccount.oracle,
377
378
  isSigner: false,
378
- isWritable: true,
379
- },
380
- ];
379
+ isWritable: false,
380
+ });
381
+ }
382
+ remainingAccounts.push({
383
+ pubkey: bankAccount.pubkey,
384
+ isSigner: false,
385
+ isWritable: true,
386
+ });
381
387
  }
382
388
  const bank = this.getBankAccount(bankIndex);
383
389
  return await this.program.instruction.deposit(bankIndex, amount, reduceOnly, {
@@ -482,14 +488,24 @@ class ClearingHouse {
482
488
  });
483
489
  }
484
490
  async openPosition(direction, amount, marketIndex, limitPrice) {
485
- return await this.placeAndTake((0, orderParams_1.getMarketOrderParams)(marketIndex, direction, numericConstants_1.ZERO, amount, false, limitPrice));
491
+ return await this.placeAndTake({
492
+ orderType: types_1.OrderType.MARKET,
493
+ marketIndex,
494
+ direction,
495
+ baseAssetAmount: amount,
496
+ price: limitPrice,
497
+ });
486
498
  }
487
499
  async placeOrder(orderParams) {
488
500
  const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
489
501
  this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
490
502
  return txSig;
491
503
  }
504
+ getOrderParams(optionalOrderParams) {
505
+ return Object.assign({}, types_1.DefaultOrderParams, optionalOrderParams);
506
+ }
492
507
  async getPlaceOrderIx(orderParams) {
508
+ orderParams = this.getOrderParams(orderParams);
493
509
  const userAccountPublicKey = await this.getUserAccountPublicKey();
494
510
  const remainingAccounts = this.getRemainingAccounts({
495
511
  writableMarketIndex: orderParams.marketIndex,
@@ -580,44 +596,57 @@ class ClearingHouse {
580
596
  const fillerPublicKey = await this.getUserAccountPublicKey();
581
597
  const marketIndex = order.marketIndex;
582
598
  const marketAccount = this.getMarketAccount(marketIndex);
583
- const bankAccountInfos = [
584
- {
585
- pubkey: this.getQuoteAssetBankAccount().pubkey,
586
- isSigner: false,
587
- isWritable: true,
588
- },
589
- ];
590
- const marketAccountInfos = [
591
- {
592
- pubkey: marketAccount.pubkey,
593
- isWritable: true,
594
- isSigner: false,
595
- },
596
- ];
597
- const oracleAccountInfos = [
598
- {
599
- pubkey: marketAccount.amm.oracle,
600
- isWritable: false,
601
- isSigner: false,
602
- },
603
- ];
599
+ const oracleAccountMap = new Map();
600
+ const bankAccountMap = new Map();
601
+ const marketAccountMap = new Map();
602
+ marketAccountMap.set(marketIndex.toNumber(), {
603
+ pubkey: marketAccount.pubkey,
604
+ isWritable: true,
605
+ isSigner: false,
606
+ });
607
+ oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
608
+ pubkey: marketAccount.amm.oracle,
609
+ isWritable: false,
610
+ isSigner: false,
611
+ });
612
+ for (const bankBalance of userAccount.bankBalances) {
613
+ if (!bankBalance.balance.eq(numericConstants_1.ZERO)) {
614
+ const bankAccount = this.getBankAccount(bankBalance.bankIndex);
615
+ bankAccountMap.set(bankBalance.bankIndex.toNumber(), {
616
+ pubkey: bankAccount.pubkey,
617
+ isSigner: false,
618
+ isWritable: false,
619
+ });
620
+ if (!bankAccount.oracle.equals(web3_js_1.PublicKey.default)) {
621
+ oracleAccountMap.set(bankAccount.oracle.toString(), {
622
+ pubkey: bankAccount.oracle,
623
+ isSigner: false,
624
+ isWritable: false,
625
+ });
626
+ }
627
+ }
628
+ }
604
629
  for (const position of userAccount.positions) {
605
630
  if (!(0, position_1.positionIsAvailable)(position) &&
606
631
  !position.marketIndex.eq(order.marketIndex)) {
607
632
  const market = this.getMarketAccount(position.marketIndex);
608
- marketAccountInfos.push({
633
+ marketAccountMap.set(position.marketIndex.toNumber(), {
609
634
  pubkey: market.pubkey,
610
- isWritable: false,
635
+ isWritable: true,
611
636
  isSigner: false,
612
637
  });
613
- oracleAccountInfos.push({
638
+ oracleAccountMap.set(market.amm.oracle.toString(), {
614
639
  pubkey: market.amm.oracle,
615
640
  isWritable: false,
616
641
  isSigner: false,
617
642
  });
618
643
  }
619
644
  }
620
- const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
645
+ const remainingAccounts = [
646
+ ...oracleAccountMap.values(),
647
+ ...bankAccountMap.values(),
648
+ ...marketAccountMap.values(),
649
+ ];
621
650
  if (makerInfo) {
622
651
  remainingAccounts.push({
623
652
  pubkey: makerInfo.maker,
@@ -700,6 +729,7 @@ class ClearingHouse {
700
729
  return txSig;
701
730
  }
702
731
  async getPlaceAndTakeIx(orderParams, makerInfo) {
732
+ orderParams = this.getOrderParams(orderParams);
703
733
  const userAccountPublicKey = await this.getUserAccountPublicKey();
704
734
  const remainingAccounts = this.getRemainingAccounts({
705
735
  writableMarketIndex: orderParams.marketIndex,
@@ -723,6 +753,34 @@ class ClearingHouse {
723
753
  remainingAccounts,
724
754
  });
725
755
  }
756
+ async placeAndMake(orderParams, takerInfo) {
757
+ const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndMakeIx(orderParams, takerInfo)), [], this.opts);
758
+ this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
759
+ return txSig;
760
+ }
761
+ async getPlaceAndMakeIx(orderParams, takerInfo) {
762
+ orderParams = this.getOrderParams(orderParams);
763
+ const userAccountPublicKey = await this.getUserAccountPublicKey();
764
+ const remainingAccounts = this.getRemainingAccounts({
765
+ writableMarketIndex: orderParams.marketIndex,
766
+ writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
767
+ });
768
+ const takerOrderId = takerInfo.order.orderId;
769
+ remainingAccounts.push({
770
+ pubkey: takerInfo.taker,
771
+ isSigner: false,
772
+ isWritable: true,
773
+ });
774
+ return await this.program.instruction.placeAndMake(orderParams, takerOrderId, {
775
+ accounts: {
776
+ state: await this.getStatePublicKey(),
777
+ user: userAccountPublicKey,
778
+ taker: takerInfo.taker,
779
+ authority: this.wallet.publicKey,
780
+ },
781
+ remainingAccounts,
782
+ });
783
+ }
726
784
  /**
727
785
  * Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
728
786
  * @param marketIndex
@@ -733,7 +791,13 @@ class ClearingHouse {
733
791
  if (!userPosition) {
734
792
  throw Error(`No position in market ${marketIndex.toString()}`);
735
793
  }
736
- return await this.placeAndTake((0, orderParams_1.getMarketOrderParams)(marketIndex, (0, position_1.findDirectionToClose)(userPosition), numericConstants_1.ZERO, userPosition.baseAssetAmount, true, undefined));
794
+ return await this.placeAndTake({
795
+ orderType: types_1.OrderType.MARKET,
796
+ marketIndex,
797
+ direction: (0, position_1.findDirectionToClose)(userPosition),
798
+ baseAssetAmount: userPosition.baseAssetAmount,
799
+ reduceOnly: true,
800
+ });
737
801
  }
738
802
  async settlePNLs(users, marketIndex) {
739
803
  const ixs = [];
package/lib/config.js CHANGED
@@ -7,7 +7,7 @@ exports.configs = {
7
7
  devnet: {
8
8
  ENV: 'devnet',
9
9
  PYTH_ORACLE_MAPPING_ADDRESS: 'BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2',
10
- CLEARING_HOUSE_PROGRAM_ID: '9jwr5nC2f9yAraXrg4UzHXmCX3vi9FQkjD6p9e8bRqNa',
10
+ CLEARING_HOUSE_PROGRAM_ID: 'BMow898PH56jD8z4EaqxicoGXkR1HhN17qrER6Uc4AYq',
11
11
  USDC_MINT_ADDRESS: '8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2',
12
12
  MARKETS: markets_1.DevnetMarkets,
13
13
  BANKS: banks_1.DevnetBanks,