@glamsystems/glam-sdk 0.1.20 → 0.1.21

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/index.cjs.js CHANGED
@@ -6,7 +6,6 @@ var splToken = require('@solana/spl-token');
6
6
  var splTokenMetadata = require('@solana/spl-token-metadata');
7
7
  var DLMM = require('@meteora-ag/dlmm');
8
8
  var bytes = require('@coral-xyz/anchor/dist/cjs/utils/bytes');
9
- var sdk = require('@drift-labs/sdk');
10
9
  var marinadeTsSdk = require('@marinade.finance/marinade-ts-sdk');
11
10
  var splStakePool = require('@solana/spl-stake-pool');
12
11
  var borsh = require('@coral-xyz/borsh');
@@ -9216,16 +9215,21 @@ var errors = [
9216
9215
  },
9217
9216
  {
9218
9217
  code: 50004,
9218
+ name: "InvalidPlatformFeeForSwap",
9219
+ msg: "Invalid platform fee"
9220
+ },
9221
+ {
9222
+ code: 50005,
9219
9223
  name: "InvalidTokenAccount",
9220
9224
  msg: "Invalid token account"
9221
9225
  },
9222
9226
  {
9223
- code: 50005,
9227
+ code: 50006,
9224
9228
  name: "InvalidVoteSide",
9225
9229
  msg: "Invalid vote side"
9226
9230
  },
9227
9231
  {
9228
- code: 50006,
9232
+ code: 50007,
9229
9233
  name: "MultipleStakeAccountsDisallowed",
9230
9234
  msg: "Multiple stake accounts disallowed"
9231
9235
  },
@@ -12929,6 +12933,13 @@ const getErrorFromRPCResponse = (rpcResponse)=>{
12929
12933
  throw Error(error.toString());
12930
12934
  }
12931
12935
  };
12936
+ const setsAreEqual = (a, b)=>{
12937
+ if (a.size !== b.size) return false;
12938
+ for (let item of a){
12939
+ if (!b.has(item)) return false;
12940
+ }
12941
+ return true;
12942
+ };
12932
12943
 
12933
12944
  const ASSETS_MAINNET = new Map([
12934
12945
  [
@@ -13598,7 +13609,901 @@ class BaseClient {
13598
13609
  }
13599
13610
  }
13600
13611
 
13601
- const DRIFT_VAULT = new web3_js.PublicKey("JCNCMFXo5M5qwUPg2Utu1u6YWp3MbygxqBsBeXXJfrw");
13612
+ const ZERO = new anchor.BN(0);
13613
+ // # Utility Types / Enums / Constants
13614
+ var ExchangeStatus = /*#__PURE__*/ function(ExchangeStatus) {
13615
+ ExchangeStatus[ExchangeStatus["ACTIVE"] = 0] = "ACTIVE";
13616
+ ExchangeStatus[ExchangeStatus["DEPOSIT_PAUSED"] = 1] = "DEPOSIT_PAUSED";
13617
+ ExchangeStatus[ExchangeStatus["WITHDRAW_PAUSED"] = 2] = "WITHDRAW_PAUSED";
13618
+ ExchangeStatus[ExchangeStatus["AMM_PAUSED"] = 4] = "AMM_PAUSED";
13619
+ ExchangeStatus[ExchangeStatus["FILL_PAUSED"] = 8] = "FILL_PAUSED";
13620
+ ExchangeStatus[ExchangeStatus["LIQ_PAUSED"] = 16] = "LIQ_PAUSED";
13621
+ ExchangeStatus[ExchangeStatus["FUNDING_PAUSED"] = 32] = "FUNDING_PAUSED";
13622
+ ExchangeStatus[ExchangeStatus["SETTLE_PNL_PAUSED"] = 64] = "SETTLE_PNL_PAUSED";
13623
+ ExchangeStatus[ExchangeStatus["AMM_IMMEDIATE_FILL_PAUSED"] = 128] = "AMM_IMMEDIATE_FILL_PAUSED";
13624
+ ExchangeStatus[ExchangeStatus["PAUSED"] = 255] = "PAUSED";
13625
+ return ExchangeStatus;
13626
+ }({});
13627
+ class MarketStatus {
13628
+ }
13629
+ MarketStatus.INITIALIZED = {
13630
+ initialized: {}
13631
+ };
13632
+ MarketStatus.ACTIVE = {
13633
+ active: {}
13634
+ };
13635
+ MarketStatus.FUNDING_PAUSED = {
13636
+ fundingPaused: {}
13637
+ };
13638
+ MarketStatus.AMM_PAUSED = {
13639
+ ammPaused: {}
13640
+ };
13641
+ MarketStatus.FILL_PAUSED = {
13642
+ fillPaused: {}
13643
+ };
13644
+ MarketStatus.WITHDRAW_PAUSED = {
13645
+ withdrawPaused: {}
13646
+ };
13647
+ MarketStatus.REDUCE_ONLY = {
13648
+ reduceOnly: {}
13649
+ };
13650
+ MarketStatus.SETTLEMENT = {
13651
+ settlement: {}
13652
+ };
13653
+ MarketStatus.DELISTED = {
13654
+ delisted: {}
13655
+ };
13656
+ var PerpOperation = /*#__PURE__*/ function(PerpOperation) {
13657
+ PerpOperation[PerpOperation["UPDATE_FUNDING"] = 1] = "UPDATE_FUNDING";
13658
+ PerpOperation[PerpOperation["AMM_FILL"] = 2] = "AMM_FILL";
13659
+ PerpOperation[PerpOperation["FILL"] = 4] = "FILL";
13660
+ PerpOperation[PerpOperation["SETTLE_PNL"] = 8] = "SETTLE_PNL";
13661
+ PerpOperation[PerpOperation["SETTLE_PNL_WITH_POSITION"] = 16] = "SETTLE_PNL_WITH_POSITION";
13662
+ PerpOperation[PerpOperation["LIQUIDATION"] = 32] = "LIQUIDATION";
13663
+ return PerpOperation;
13664
+ }({});
13665
+ var SpotOperation = /*#__PURE__*/ function(SpotOperation) {
13666
+ SpotOperation[SpotOperation["UPDATE_CUMULATIVE_INTEREST"] = 1] = "UPDATE_CUMULATIVE_INTEREST";
13667
+ SpotOperation[SpotOperation["FILL"] = 2] = "FILL";
13668
+ SpotOperation[SpotOperation["DEPOSIT"] = 4] = "DEPOSIT";
13669
+ SpotOperation[SpotOperation["WITHDRAW"] = 8] = "WITHDRAW";
13670
+ SpotOperation[SpotOperation["LIQUIDATION"] = 16] = "LIQUIDATION";
13671
+ return SpotOperation;
13672
+ }({});
13673
+ var InsuranceFundOperation = /*#__PURE__*/ function(InsuranceFundOperation) {
13674
+ InsuranceFundOperation[InsuranceFundOperation["INIT"] = 1] = "INIT";
13675
+ InsuranceFundOperation[InsuranceFundOperation["ADD"] = 2] = "ADD";
13676
+ InsuranceFundOperation[InsuranceFundOperation["REQUEST_REMOVE"] = 4] = "REQUEST_REMOVE";
13677
+ InsuranceFundOperation[InsuranceFundOperation["REMOVE"] = 8] = "REMOVE";
13678
+ return InsuranceFundOperation;
13679
+ }({});
13680
+ var UserStatus = /*#__PURE__*/ function(UserStatus) {
13681
+ UserStatus[UserStatus["BEING_LIQUIDATED"] = 1] = "BEING_LIQUIDATED";
13682
+ UserStatus[UserStatus["BANKRUPT"] = 2] = "BANKRUPT";
13683
+ UserStatus[UserStatus["REDUCE_ONLY"] = 4] = "REDUCE_ONLY";
13684
+ UserStatus[UserStatus["ADVANCED_LP"] = 8] = "ADVANCED_LP";
13685
+ UserStatus[UserStatus["PROTECTED_MAKER"] = 16] = "PROTECTED_MAKER";
13686
+ return UserStatus;
13687
+ }({});
13688
+ class MarginMode {
13689
+ }
13690
+ MarginMode.DEFAULT = {
13691
+ default: {}
13692
+ };
13693
+ MarginMode.HIGH_LEVERAGE = {
13694
+ highLeverage: {}
13695
+ };
13696
+ class ContractType {
13697
+ }
13698
+ ContractType.PERPETUAL = {
13699
+ perpetual: {}
13700
+ };
13701
+ ContractType.FUTURE = {
13702
+ future: {}
13703
+ };
13704
+ ContractType.PREDICTION = {
13705
+ prediction: {}
13706
+ };
13707
+ class ContractTier {
13708
+ }
13709
+ ContractTier.A = {
13710
+ a: {}
13711
+ };
13712
+ ContractTier.B = {
13713
+ b: {}
13714
+ };
13715
+ ContractTier.C = {
13716
+ c: {}
13717
+ };
13718
+ ContractTier.SPECULATIVE = {
13719
+ speculative: {}
13720
+ };
13721
+ ContractTier.HIGHLY_SPECULATIVE = {
13722
+ highlySpeculative: {}
13723
+ };
13724
+ ContractTier.ISOLATED = {
13725
+ isolated: {}
13726
+ };
13727
+ class AssetTier {
13728
+ }
13729
+ AssetTier.COLLATERAL = {
13730
+ collateral: {}
13731
+ };
13732
+ AssetTier.PROTECTED = {
13733
+ protected: {}
13734
+ };
13735
+ AssetTier.CROSS = {
13736
+ cross: {}
13737
+ };
13738
+ AssetTier.ISOLATED = {
13739
+ isolated: {}
13740
+ };
13741
+ AssetTier.UNLISTED = {
13742
+ unlisted: {}
13743
+ };
13744
+ class SwapDirection {
13745
+ }
13746
+ SwapDirection.ADD = {
13747
+ add: {}
13748
+ };
13749
+ SwapDirection.REMOVE = {
13750
+ remove: {}
13751
+ };
13752
+ class SpotBalanceType {
13753
+ }
13754
+ SpotBalanceType.DEPOSIT = {
13755
+ deposit: {}
13756
+ };
13757
+ SpotBalanceType.BORROW = {
13758
+ borrow: {}
13759
+ };
13760
+ class PositionDirection {
13761
+ }
13762
+ PositionDirection.LONG = {
13763
+ long: {}
13764
+ };
13765
+ PositionDirection.SHORT = {
13766
+ short: {}
13767
+ };
13768
+ class DepositDirection {
13769
+ }
13770
+ DepositDirection.DEPOSIT = {
13771
+ deposit: {}
13772
+ };
13773
+ DepositDirection.WITHDRAW = {
13774
+ withdraw: {}
13775
+ };
13776
+ class OracleSource {
13777
+ static get(n) {
13778
+ const name = Object.entries(OracleSourceNum).find(([, v])=>v === n)?.[0];
13779
+ const source = Object.entries(OracleSource).find(([key, _])=>key.toLocaleLowerCase() === name?.toLocaleLowerCase())?.[1];
13780
+ if (!source) {
13781
+ throw new Error(`Invalid oracle source enum value: ${n}`);
13782
+ }
13783
+ return source;
13784
+ }
13785
+ }
13786
+ OracleSource.PYTH = {
13787
+ pyth: {}
13788
+ };
13789
+ OracleSource.PYTH_1K = {
13790
+ pyth1K: {}
13791
+ };
13792
+ OracleSource.PYTH_1M = {
13793
+ pyth1M: {}
13794
+ };
13795
+ OracleSource.PYTH_PULL = {
13796
+ pythPull: {}
13797
+ };
13798
+ OracleSource.PYTH_1K_PULL = {
13799
+ pyth1KPull: {}
13800
+ };
13801
+ OracleSource.PYTH_1M_PULL = {
13802
+ pyth1MPull: {}
13803
+ };
13804
+ OracleSource.SWITCHBOARD = {
13805
+ switchboard: {}
13806
+ };
13807
+ OracleSource.QUOTE_ASSET = {
13808
+ quoteAsset: {}
13809
+ };
13810
+ OracleSource.PYTH_STABLE_COIN = {
13811
+ pythStableCoin: {}
13812
+ };
13813
+ OracleSource.PYTH_STABLE_COIN_PULL = {
13814
+ pythStableCoinPull: {}
13815
+ };
13816
+ OracleSource.Prelaunch = {
13817
+ prelaunch: {}
13818
+ };
13819
+ OracleSource.SWITCHBOARD_ON_DEMAND = {
13820
+ switchboardOnDemand: {}
13821
+ };
13822
+ OracleSource.PYTH_LAZER = {
13823
+ pythLazer: {}
13824
+ };
13825
+ OracleSource.PYTH_LAZER_1K = {
13826
+ pythLazer1K: {}
13827
+ };
13828
+ OracleSource.PYTH_LAZER_1M = {
13829
+ pythLazer1M: {}
13830
+ };
13831
+ OracleSource.PYTH_LAZER_STABLE_COIN = {
13832
+ pythLazerStableCoin: {}
13833
+ };
13834
+ class OracleSourceNum {
13835
+ }
13836
+ OracleSourceNum.PYTH = 0;
13837
+ OracleSourceNum.PYTH_1K = 1;
13838
+ OracleSourceNum.PYTH_1M = 2;
13839
+ OracleSourceNum.PYTH_PULL = 3;
13840
+ OracleSourceNum.PYTH_1K_PULL = 4;
13841
+ OracleSourceNum.PYTH_1M_PULL = 5;
13842
+ OracleSourceNum.SWITCHBOARD = 6;
13843
+ OracleSourceNum.QUOTE_ASSET = 7;
13844
+ OracleSourceNum.PYTH_STABLE_COIN = 8;
13845
+ OracleSourceNum.PYTH_STABLE_COIN_PULL = 9;
13846
+ OracleSourceNum.PRELAUNCH = 10;
13847
+ OracleSourceNum.SWITCHBOARD_ON_DEMAND = 11;
13848
+ OracleSourceNum.PYTH_LAZER = 12;
13849
+ OracleSourceNum.PYTH_LAZER_1K = 13;
13850
+ OracleSourceNum.PYTH_LAZER_1M = 14;
13851
+ OracleSourceNum.PYTH_LAZER_STABLE_COIN = 15;
13852
+ class OrderType {
13853
+ }
13854
+ OrderType.LIMIT = {
13855
+ limit: {}
13856
+ };
13857
+ OrderType.TRIGGER_MARKET = {
13858
+ triggerMarket: {}
13859
+ };
13860
+ OrderType.TRIGGER_LIMIT = {
13861
+ triggerLimit: {}
13862
+ };
13863
+ OrderType.MARKET = {
13864
+ market: {}
13865
+ };
13866
+ OrderType.ORACLE = {
13867
+ oracle: {}
13868
+ };
13869
+ class MarketType {
13870
+ }
13871
+ MarketType.SPOT = {
13872
+ spot: {}
13873
+ };
13874
+ MarketType.PERP = {
13875
+ perp: {}
13876
+ };
13877
+ class OrderStatus {
13878
+ }
13879
+ OrderStatus.INIT = {
13880
+ init: {}
13881
+ };
13882
+ OrderStatus.OPEN = {
13883
+ open: {}
13884
+ };
13885
+ OrderStatus.FILLED = {
13886
+ filled: {}
13887
+ };
13888
+ OrderStatus.CANCELED = {
13889
+ canceled: {}
13890
+ };
13891
+ class OrderAction {
13892
+ }
13893
+ OrderAction.PLACE = {
13894
+ place: {}
13895
+ };
13896
+ OrderAction.CANCEL = {
13897
+ cancel: {}
13898
+ };
13899
+ OrderAction.EXPIRE = {
13900
+ expire: {}
13901
+ };
13902
+ OrderAction.FILL = {
13903
+ fill: {}
13904
+ };
13905
+ OrderAction.TRIGGER = {
13906
+ trigger: {}
13907
+ };
13908
+ class OrderActionExplanation {
13909
+ }
13910
+ OrderActionExplanation.NONE = {
13911
+ none: {}
13912
+ };
13913
+ OrderActionExplanation.INSUFFICIENT_FREE_COLLATERAL = {
13914
+ insufficientFreeCollateral: {}
13915
+ };
13916
+ OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
13917
+ oraclePriceBreachedLimitPrice: {}
13918
+ };
13919
+ OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
13920
+ marketOrderFilledToLimitPrice: {}
13921
+ };
13922
+ OrderActionExplanation.ORDER_EXPIRED = {
13923
+ orderExpired: {}
13924
+ };
13925
+ OrderActionExplanation.LIQUIDATION = {
13926
+ liquidation: {}
13927
+ };
13928
+ OrderActionExplanation.ORDER_FILLED_WITH_AMM = {
13929
+ orderFilledWithAmm: {}
13930
+ };
13931
+ OrderActionExplanation.ORDER_FILLED_WITH_AMM_JIT = {
13932
+ orderFilledWithAmmJit: {}
13933
+ };
13934
+ OrderActionExplanation.ORDER_FILLED_WITH_AMM_JIT_LP_SPLIT = {
13935
+ orderFilledWithAmmJitLpSplit: {}
13936
+ };
13937
+ OrderActionExplanation.ORDER_FILLED_WITH_LP_JIT = {
13938
+ orderFilledWithLpJit: {}
13939
+ };
13940
+ OrderActionExplanation.ORDER_FILLED_WITH_MATCH = {
13941
+ orderFilledWithMatch: {}
13942
+ };
13943
+ OrderActionExplanation.ORDER_FILLED_WITH_MATCH_JIT = {
13944
+ orderFilledWithMatchJit: {}
13945
+ };
13946
+ OrderActionExplanation.MARKET_EXPIRED = {
13947
+ marketExpired: {}
13948
+ };
13949
+ OrderActionExplanation.RISK_INCREASING_ORDER = {
13950
+ riskingIncreasingOrder: {}
13951
+ };
13952
+ OrderActionExplanation.ORDER_FILLED_WITH_SERUM = {
13953
+ orderFillWithSerum: {}
13954
+ };
13955
+ OrderActionExplanation.ORDER_FILLED_WITH_OPENBOOK_V2 = {
13956
+ orderFilledWithOpenbookV2: {}
13957
+ };
13958
+ OrderActionExplanation.ORDER_FILLED_WITH_PHOENIX = {
13959
+ orderFillWithPhoenix: {}
13960
+ };
13961
+ OrderActionExplanation.REDUCE_ONLY_ORDER_INCREASED_POSITION = {
13962
+ reduceOnlyOrderIncreasedPosition: {}
13963
+ };
13964
+ OrderActionExplanation.DERISK_LP = {
13965
+ deriskLp: {}
13966
+ };
13967
+ OrderActionExplanation.TRANSFER_PERP_POSITION = {
13968
+ transferPerpPosition: {}
13969
+ };
13970
+ class OrderTriggerCondition {
13971
+ }
13972
+ OrderTriggerCondition.ABOVE = {
13973
+ above: {}
13974
+ };
13975
+ OrderTriggerCondition.BELOW = {
13976
+ below: {}
13977
+ };
13978
+ OrderTriggerCondition.TRIGGERED_ABOVE = {
13979
+ triggeredAbove: {}
13980
+ } // above condition has been triggered
13981
+ ;
13982
+ OrderTriggerCondition.TRIGGERED_BELOW = {
13983
+ triggeredBelow: {}
13984
+ } // below condition has been triggered
13985
+ ;
13986
+ class SpotFulfillmentType {
13987
+ }
13988
+ SpotFulfillmentType.EXTERNAL = {
13989
+ external: {}
13990
+ };
13991
+ SpotFulfillmentType.MATCH = {
13992
+ match: {}
13993
+ };
13994
+ class SpotFulfillmentStatus {
13995
+ }
13996
+ SpotFulfillmentStatus.ENABLED = {
13997
+ enabled: {}
13998
+ };
13999
+ SpotFulfillmentStatus.DISABLED = {
14000
+ disabled: {}
14001
+ };
14002
+ class DepositExplanation {
14003
+ }
14004
+ DepositExplanation.NONE = {
14005
+ none: {}
14006
+ };
14007
+ DepositExplanation.TRANSFER = {
14008
+ transfer: {}
14009
+ };
14010
+ DepositExplanation.BORROW = {
14011
+ borrow: {}
14012
+ };
14013
+ DepositExplanation.REPAY_BORROW = {
14014
+ repayBorrow: {}
14015
+ };
14016
+ class SettlePnlExplanation {
14017
+ }
14018
+ SettlePnlExplanation.NONE = {
14019
+ none: {}
14020
+ };
14021
+ SettlePnlExplanation.EXPIRED_POSITION = {
14022
+ expiredPosition: {}
14023
+ };
14024
+ class SpotFulfillmentConfigStatus {
14025
+ }
14026
+ SpotFulfillmentConfigStatus.ENABLED = {
14027
+ enabled: {}
14028
+ };
14029
+ SpotFulfillmentConfigStatus.DISABLED = {
14030
+ disabled: {}
14031
+ };
14032
+ class StakeAction {
14033
+ }
14034
+ StakeAction.STAKE = {
14035
+ stake: {}
14036
+ };
14037
+ StakeAction.UNSTAKE_REQUEST = {
14038
+ unstakeRequest: {}
14039
+ };
14040
+ StakeAction.UNSTAKE_CANCEL_REQUEST = {
14041
+ unstakeCancelRequest: {}
14042
+ };
14043
+ StakeAction.UNSTAKE = {
14044
+ unstake: {}
14045
+ };
14046
+ StakeAction.UNSTAKE_TRANSFER = {
14047
+ unstakeTransfer: {}
14048
+ };
14049
+ StakeAction.STAKE_TRANSFER = {
14050
+ stakeTransfer: {}
14051
+ };
14052
+ class SettlePnlMode {
14053
+ }
14054
+ SettlePnlMode.TRY_SETTLE = {
14055
+ trySettle: {}
14056
+ };
14057
+ SettlePnlMode.MUST_SETTLE = {
14058
+ mustSettle: {}
14059
+ };
14060
+ function isVariant(object, type) {
14061
+ return object.hasOwnProperty(type);
14062
+ }
14063
+ function isOneOfVariant(object, types) {
14064
+ return types.reduce((result, type)=>{
14065
+ return result || object.hasOwnProperty(type);
14066
+ }, false);
14067
+ }
14068
+ function getVariant(object) {
14069
+ return Object.keys(object)[0];
14070
+ }
14071
+ var TradeSide = /*#__PURE__*/ function(TradeSide) {
14072
+ TradeSide[TradeSide["None"] = 0] = "None";
14073
+ TradeSide[TradeSide["Buy"] = 1] = "Buy";
14074
+ TradeSide[TradeSide["Sell"] = 2] = "Sell";
14075
+ return TradeSide;
14076
+ }({});
14077
+ class LPAction {
14078
+ }
14079
+ LPAction.ADD_LIQUIDITY = {
14080
+ addLiquidity: {}
14081
+ };
14082
+ LPAction.REMOVE_LIQUIDITY = {
14083
+ removeLiquidity: {}
14084
+ };
14085
+ LPAction.SETTLE_LIQUIDITY = {
14086
+ settleLiquidity: {}
14087
+ };
14088
+ LPAction.REMOVE_LIQUIDITY_DERISK = {
14089
+ removeLiquidityDerisk: {}
14090
+ };
14091
+ class LiquidationType {
14092
+ }
14093
+ LiquidationType.LIQUIDATE_PERP = {
14094
+ liquidatePerp: {}
14095
+ };
14096
+ LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
14097
+ liquidateBorrowForPerpPnl: {}
14098
+ };
14099
+ LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
14100
+ liquidatePerpPnlForDeposit: {}
14101
+ };
14102
+ LiquidationType.PERP_BANKRUPTCY = {
14103
+ perpBankruptcy: {}
14104
+ };
14105
+ LiquidationType.SPOT_BANKRUPTCY = {
14106
+ spotBankruptcy: {}
14107
+ };
14108
+ LiquidationType.LIQUIDATE_SPOT = {
14109
+ liquidateSpot: {}
14110
+ };
14111
+ class PostOnlyParams {
14112
+ }
14113
+ PostOnlyParams.NONE = {
14114
+ none: {}
14115
+ };
14116
+ PostOnlyParams.MUST_POST_ONLY = {
14117
+ mustPostOnly: {}
14118
+ } // Tx fails if order can't be post only
14119
+ ;
14120
+ PostOnlyParams.TRY_POST_ONLY = {
14121
+ tryPostOnly: {}
14122
+ } // Tx succeeds and order not placed if can't be post only
14123
+ ;
14124
+ PostOnlyParams.SLIDE = {
14125
+ slide: {}
14126
+ } // Modify price to be post only if can't be post only
14127
+ ;
14128
+ var ModifyOrderPolicy = /*#__PURE__*/ function(ModifyOrderPolicy) {
14129
+ ModifyOrderPolicy[ModifyOrderPolicy["MustModify"] = 1] = "MustModify";
14130
+ ModifyOrderPolicy[ModifyOrderPolicy["ExcludePreviousFill"] = 2] = "ExcludePreviousFill";
14131
+ return ModifyOrderPolicy;
14132
+ }({});
14133
+ const DefaultOrderParams = {
14134
+ orderType: OrderType.MARKET,
14135
+ marketType: MarketType.PERP,
14136
+ userOrderId: 0,
14137
+ direction: PositionDirection.LONG,
14138
+ baseAssetAmount: ZERO,
14139
+ price: ZERO,
14140
+ marketIndex: 0,
14141
+ reduceOnly: false,
14142
+ postOnly: PostOnlyParams.NONE,
14143
+ immediateOrCancel: false,
14144
+ triggerPrice: null,
14145
+ triggerCondition: OrderTriggerCondition.ABOVE,
14146
+ oraclePriceOffset: null,
14147
+ auctionDuration: null,
14148
+ maxTs: null,
14149
+ auctionStartPrice: null,
14150
+ auctionEndPrice: null
14151
+ };
14152
+ var ReferrerStatus = /*#__PURE__*/ function(ReferrerStatus) {
14153
+ ReferrerStatus[ReferrerStatus["IsReferrer"] = 1] = "IsReferrer";
14154
+ ReferrerStatus[ReferrerStatus["IsReferred"] = 2] = "IsReferred";
14155
+ return ReferrerStatus;
14156
+ }({});
14157
+ var FuelOverflowStatus = /*#__PURE__*/ function(FuelOverflowStatus) {
14158
+ FuelOverflowStatus[FuelOverflowStatus["Exists"] = 1] = "Exists";
14159
+ return FuelOverflowStatus;
14160
+ }({});
14161
+ var PlaceAndTakeOrderSuccessCondition = /*#__PURE__*/ function(PlaceAndTakeOrderSuccessCondition) {
14162
+ PlaceAndTakeOrderSuccessCondition[PlaceAndTakeOrderSuccessCondition["PartialFill"] = 1] = "PartialFill";
14163
+ PlaceAndTakeOrderSuccessCondition[PlaceAndTakeOrderSuccessCondition["FullFill"] = 2] = "FullFill";
14164
+ return PlaceAndTakeOrderSuccessCondition;
14165
+ }({});
14166
+ class SwapReduceOnly {
14167
+ }
14168
+ SwapReduceOnly.In = {
14169
+ in: {}
14170
+ };
14171
+ SwapReduceOnly.Out = {
14172
+ out: {}
14173
+ };
14174
+
14175
+ function readUnsignedBigInt64LE(buffer, offset) {
14176
+ return new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
14177
+ }
14178
+ function readSignedBigInt64LE(buffer, offset) {
14179
+ const unsignedValue = new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
14180
+ if (unsignedValue.testn(63)) {
14181
+ const inverted = unsignedValue.notn(64).addn(1);
14182
+ return inverted.neg();
14183
+ } else {
14184
+ return unsignedValue;
14185
+ }
14186
+ }
14187
+ function decodeUser(buffer) {
14188
+ let offset = 8;
14189
+ const authority = new web3_js.PublicKey(buffer.slice(offset, offset + 32));
14190
+ offset += 32;
14191
+ const delegate = new web3_js.PublicKey(buffer.slice(offset, offset + 32));
14192
+ offset += 32;
14193
+ const name = [];
14194
+ for(let i = 0; i < 32; i++){
14195
+ name.push(buffer.readUint8(offset + i));
14196
+ }
14197
+ offset += 32;
14198
+ const spotPositions = [];
14199
+ for(let i = 0; i < 8; i++){
14200
+ const scaledBalance = readUnsignedBigInt64LE(buffer, offset);
14201
+ const openOrders = buffer.readUInt8(offset + 35);
14202
+ if (scaledBalance.eq(ZERO) && openOrders === 0) {
14203
+ offset += 40;
14204
+ continue;
14205
+ }
14206
+ offset += 8;
14207
+ const openBids = readSignedBigInt64LE(buffer, offset);
14208
+ offset += 8;
14209
+ const openAsks = readSignedBigInt64LE(buffer, offset);
14210
+ offset += 8;
14211
+ const cumulativeDeposits = readSignedBigInt64LE(buffer, offset);
14212
+ offset += 8;
14213
+ const marketIndex = buffer.readUInt16LE(offset);
14214
+ offset += 2;
14215
+ const balanceTypeNum = buffer.readUInt8(offset);
14216
+ let balanceType;
14217
+ if (balanceTypeNum === 0) {
14218
+ balanceType = SpotBalanceType.DEPOSIT;
14219
+ } else {
14220
+ balanceType = SpotBalanceType.BORROW;
14221
+ }
14222
+ offset += 6;
14223
+ spotPositions.push({
14224
+ scaledBalance,
14225
+ openBids,
14226
+ openAsks,
14227
+ cumulativeDeposits,
14228
+ marketIndex,
14229
+ balanceType,
14230
+ openOrders
14231
+ });
14232
+ }
14233
+ const perpPositions = [];
14234
+ for(let i = 0; i < 8; i++){
14235
+ const baseAssetAmount = readSignedBigInt64LE(buffer, offset + 8);
14236
+ const quoteAssetAmount = readSignedBigInt64LE(buffer, offset + 16);
14237
+ const lpShares = readUnsignedBigInt64LE(buffer, offset + 64);
14238
+ const openOrders = buffer.readUInt8(offset + 94);
14239
+ if (baseAssetAmount.eq(ZERO) && openOrders === 0 && quoteAssetAmount.eq(ZERO) && lpShares.eq(ZERO)) {
14240
+ offset += 96;
14241
+ continue;
14242
+ }
14243
+ const lastCumulativeFundingRate = readSignedBigInt64LE(buffer, offset);
14244
+ offset += 24;
14245
+ const quoteBreakEvenAmount = readSignedBigInt64LE(buffer, offset);
14246
+ offset += 8;
14247
+ const quoteEntryAmount = readSignedBigInt64LE(buffer, offset);
14248
+ offset += 8;
14249
+ const openBids = readSignedBigInt64LE(buffer, offset);
14250
+ offset += 8;
14251
+ const openAsks = readSignedBigInt64LE(buffer, offset);
14252
+ offset += 8;
14253
+ const settledPnl = readSignedBigInt64LE(buffer, offset);
14254
+ offset += 16;
14255
+ const lastBaseAssetAmountPerLp = readSignedBigInt64LE(buffer, offset);
14256
+ offset += 8;
14257
+ const lastQuoteAssetAmountPerLp = readSignedBigInt64LE(buffer, offset);
14258
+ offset += 8;
14259
+ const remainderBaseAssetAmount = buffer.readInt32LE(offset);
14260
+ offset += 4;
14261
+ const marketIndex = buffer.readUInt16LE(offset);
14262
+ offset += 3;
14263
+ const perLpBase = buffer.readUInt8(offset);
14264
+ offset += 1;
14265
+ perpPositions.push({
14266
+ lastCumulativeFundingRate,
14267
+ baseAssetAmount,
14268
+ quoteAssetAmount,
14269
+ quoteBreakEvenAmount,
14270
+ quoteEntryAmount,
14271
+ openBids,
14272
+ openAsks,
14273
+ settledPnl,
14274
+ lpShares,
14275
+ lastBaseAssetAmountPerLp,
14276
+ lastQuoteAssetAmountPerLp,
14277
+ remainderBaseAssetAmount,
14278
+ marketIndex,
14279
+ openOrders,
14280
+ perLpBase
14281
+ });
14282
+ }
14283
+ const orders = [];
14284
+ for(let i = 0; i < 32; i++){
14285
+ // skip order if it's not open
14286
+ if (buffer.readUint8(offset + 82) !== 1) {
14287
+ offset += 96;
14288
+ continue;
14289
+ }
14290
+ const slot = readUnsignedBigInt64LE(buffer, offset);
14291
+ offset += 8;
14292
+ const price = readUnsignedBigInt64LE(buffer, offset);
14293
+ offset += 8;
14294
+ const baseAssetAmount = readUnsignedBigInt64LE(buffer, offset);
14295
+ offset += 8;
14296
+ const baseAssetAmountFilled = readUnsignedBigInt64LE(buffer, offset);
14297
+ offset += 8;
14298
+ const quoteAssetAmountFilled = readUnsignedBigInt64LE(buffer, offset);
14299
+ offset += 8;
14300
+ const triggerPrice = readUnsignedBigInt64LE(buffer, offset);
14301
+ offset += 8;
14302
+ const auctionStartPrice = readSignedBigInt64LE(buffer, offset);
14303
+ offset += 8;
14304
+ const auctionEndPrice = readSignedBigInt64LE(buffer, offset);
14305
+ offset += 8;
14306
+ const maxTs = readSignedBigInt64LE(buffer, offset);
14307
+ offset += 8;
14308
+ const oraclePriceOffset = buffer.readInt32LE(offset);
14309
+ offset += 4;
14310
+ const orderId = buffer.readUInt32LE(offset);
14311
+ offset += 4;
14312
+ const marketIndex = buffer.readUInt16LE(offset);
14313
+ offset += 2;
14314
+ const orderStatusNum = buffer.readUInt8(offset);
14315
+ let status = OrderStatus.INIT;
14316
+ if (orderStatusNum === 0) {
14317
+ status = OrderStatus.INIT;
14318
+ } else if (orderStatusNum === 1) {
14319
+ status = OrderStatus.OPEN;
14320
+ } else if (orderStatusNum === 2) {
14321
+ status = OrderStatus.FILLED;
14322
+ } else if (orderStatusNum === 3) {
14323
+ status = OrderStatus.CANCELED;
14324
+ }
14325
+ offset += 1;
14326
+ const orderTypeNum = buffer.readUInt8(offset);
14327
+ let orderType = OrderType.MARKET;
14328
+ if (orderTypeNum === 0) {
14329
+ orderType = OrderType.MARKET;
14330
+ } else if (orderTypeNum === 1) {
14331
+ orderType = OrderType.LIMIT;
14332
+ } else if (orderTypeNum === 2) {
14333
+ orderType = OrderType.TRIGGER_MARKET;
14334
+ } else if (orderTypeNum === 3) {
14335
+ orderType = OrderType.TRIGGER_LIMIT;
14336
+ } else if (orderTypeNum === 4) {
14337
+ orderType = OrderType.ORACLE;
14338
+ }
14339
+ offset += 1;
14340
+ const marketTypeNum = buffer.readUInt8(offset);
14341
+ let marketType;
14342
+ if (marketTypeNum === 0) {
14343
+ marketType = MarketType.SPOT;
14344
+ } else {
14345
+ marketType = MarketType.PERP;
14346
+ }
14347
+ offset += 1;
14348
+ const userOrderId = buffer.readUint8(offset);
14349
+ offset += 1;
14350
+ const existingPositionDirectionNum = buffer.readUInt8(offset);
14351
+ let existingPositionDirection;
14352
+ if (existingPositionDirectionNum === 0) {
14353
+ existingPositionDirection = PositionDirection.LONG;
14354
+ } else {
14355
+ existingPositionDirection = PositionDirection.SHORT;
14356
+ }
14357
+ offset += 1;
14358
+ const positionDirectionNum = buffer.readUInt8(offset);
14359
+ let direction;
14360
+ if (positionDirectionNum === 0) {
14361
+ direction = PositionDirection.LONG;
14362
+ } else {
14363
+ direction = PositionDirection.SHORT;
14364
+ }
14365
+ offset += 1;
14366
+ const reduceOnly = buffer.readUInt8(offset) === 1;
14367
+ offset += 1;
14368
+ const postOnly = buffer.readUInt8(offset) === 1;
14369
+ offset += 1;
14370
+ const immediateOrCancel = buffer.readUInt8(offset) === 1;
14371
+ offset += 1;
14372
+ const triggerConditionNum = buffer.readUInt8(offset);
14373
+ let triggerCondition = OrderTriggerCondition.ABOVE;
14374
+ if (triggerConditionNum === 0) {
14375
+ triggerCondition = OrderTriggerCondition.ABOVE;
14376
+ } else if (triggerConditionNum === 1) {
14377
+ triggerCondition = OrderTriggerCondition.BELOW;
14378
+ } else if (triggerConditionNum === 2) {
14379
+ triggerCondition = OrderTriggerCondition.TRIGGERED_ABOVE;
14380
+ } else if (triggerConditionNum === 3) {
14381
+ triggerCondition = OrderTriggerCondition.TRIGGERED_BELOW;
14382
+ }
14383
+ offset += 1;
14384
+ const auctionDuration = buffer.readUInt8(offset);
14385
+ offset += 1;
14386
+ const postedSlotTail = buffer.readUint8(offset);
14387
+ offset += 1;
14388
+ const bitFlags = buffer.readUint8(offset);
14389
+ offset += 1;
14390
+ offset += 1; // padding
14391
+ orders.push({
14392
+ slot,
14393
+ price,
14394
+ baseAssetAmount,
14395
+ quoteAssetAmount: undefined,
14396
+ baseAssetAmountFilled,
14397
+ quoteAssetAmountFilled,
14398
+ triggerPrice,
14399
+ auctionStartPrice,
14400
+ auctionEndPrice,
14401
+ maxTs,
14402
+ oraclePriceOffset,
14403
+ orderId,
14404
+ marketIndex,
14405
+ status,
14406
+ orderType,
14407
+ marketType,
14408
+ userOrderId,
14409
+ existingPositionDirection,
14410
+ direction,
14411
+ reduceOnly,
14412
+ postOnly,
14413
+ immediateOrCancel,
14414
+ triggerCondition,
14415
+ auctionDuration,
14416
+ bitFlags,
14417
+ postedSlotTail
14418
+ });
14419
+ }
14420
+ const lastAddPerpLpSharesTs = readSignedBigInt64LE(buffer, offset);
14421
+ offset += 8;
14422
+ const totalDeposits = readUnsignedBigInt64LE(buffer, offset);
14423
+ offset += 8;
14424
+ const totalWithdraws = readUnsignedBigInt64LE(buffer, offset);
14425
+ offset += 8;
14426
+ const totalSocialLoss = readUnsignedBigInt64LE(buffer, offset);
14427
+ offset += 8;
14428
+ const settledPerpPnl = readSignedBigInt64LE(buffer, offset);
14429
+ offset += 8;
14430
+ const cumulativeSpotFees = readSignedBigInt64LE(buffer, offset);
14431
+ offset += 8;
14432
+ const cumulativePerpFunding = readSignedBigInt64LE(buffer, offset);
14433
+ offset += 8;
14434
+ const liquidationMarginFreed = readUnsignedBigInt64LE(buffer, offset);
14435
+ offset += 8;
14436
+ const lastActiveSlot = readUnsignedBigInt64LE(buffer, offset);
14437
+ offset += 8;
14438
+ const nextOrderId = buffer.readUInt32LE(offset);
14439
+ offset += 4;
14440
+ const maxMarginRatio = buffer.readUInt32LE(offset);
14441
+ offset += 4;
14442
+ const nextLiquidationId = buffer.readUInt16LE(offset);
14443
+ offset += 2;
14444
+ const subAccountId = buffer.readUInt16LE(offset);
14445
+ offset += 2;
14446
+ const status = buffer.readUInt8(offset);
14447
+ offset += 1;
14448
+ const isMarginTradingEnabled = buffer.readUInt8(offset) === 1;
14449
+ offset += 1;
14450
+ const idle = buffer.readUInt8(offset) === 1;
14451
+ offset += 1;
14452
+ const openOrders = buffer.readUInt8(offset);
14453
+ offset += 1;
14454
+ const hasOpenOrder = buffer.readUInt8(offset) === 1;
14455
+ offset += 1;
14456
+ const openAuctions = buffer.readUInt8(offset);
14457
+ offset += 1;
14458
+ const hasOpenAuction = buffer.readUInt8(offset) === 1;
14459
+ offset += 1;
14460
+ let marginMode;
14461
+ const marginModeNum = buffer.readUInt8(offset);
14462
+ if (marginModeNum === 0) {
14463
+ marginMode = MarginMode.DEFAULT;
14464
+ } else {
14465
+ marginMode = MarginMode.HIGH_LEVERAGE;
14466
+ }
14467
+ offset += 1;
14468
+ const poolId = buffer.readUint8(offset);
14469
+ offset += 1;
14470
+ offset += 3; // padding
14471
+ const lastFuelBonusUpdateTs = buffer.readUint32LE(offset);
14472
+ offset += 4;
14473
+ return {
14474
+ authority,
14475
+ delegate,
14476
+ name,
14477
+ spotPositions,
14478
+ perpPositions,
14479
+ orders,
14480
+ lastAddPerpLpSharesTs,
14481
+ totalDeposits,
14482
+ totalWithdraws,
14483
+ totalSocialLoss,
14484
+ settledPerpPnl,
14485
+ cumulativeSpotFees,
14486
+ cumulativePerpFunding,
14487
+ liquidationMarginFreed,
14488
+ lastActiveSlot,
14489
+ nextOrderId,
14490
+ maxMarginRatio,
14491
+ nextLiquidationId,
14492
+ subAccountId,
14493
+ status,
14494
+ isMarginTradingEnabled,
14495
+ idle,
14496
+ openOrders,
14497
+ hasOpenOrder,
14498
+ openAuctions,
14499
+ hasOpenAuction,
14500
+ marginMode,
14501
+ poolId,
14502
+ lastFuelBonusUpdateTs
14503
+ };
14504
+ }
14505
+
14506
+ const DRIFT_SIGNER = new web3_js.PublicKey("JCNCMFXo5M5qwUPg2Utu1u6YWp3MbygxqBsBeXXJfrw");
13602
14507
  const DRIFT_MARGIN_PRECISION = 10000;
13603
14508
  class DriftClient {
13604
14509
  /*
@@ -13623,89 +14528,268 @@ class DriftClient {
13623
14528
  const tx = await this.deleteUserTx(new web3_js.PublicKey(statePda), subAccountId, txOptions);
13624
14529
  return await this.base.sendAndConfirm(tx);
13625
14530
  }
13626
- async deposit(statePda, amount, marketIndex = 1, subAccountId = 0, marketConfigs, txOptions = {}) {
13627
- const tx = await this.depositTx(new web3_js.PublicKey(statePda), amount, marketIndex, subAccountId, marketConfigs, txOptions);
14531
+ async deposit(statePda, amount, marketIndex = 1, subAccountId = 0, txOptions = {}) {
14532
+ const tx = await this.depositTx(new web3_js.PublicKey(statePda), amount, marketIndex, subAccountId, txOptions);
13628
14533
  return await this.base.sendAndConfirm(tx);
13629
14534
  }
13630
- async withdraw(statePda, amount, marketIndex = 1, subAccountId = 0, marketConfigs, txOptions = {}) {
13631
- const tx = await this.withdrawTx(new web3_js.PublicKey(statePda), amount, marketIndex, subAccountId, marketConfigs, txOptions);
14535
+ async withdraw(statePda, amount, marketIndex = 1, subAccountId = 0, txOptions = {}) {
14536
+ const tx = await this.withdrawTx(new web3_js.PublicKey(statePda), amount, marketIndex, subAccountId, txOptions);
13632
14537
  return await this.base.sendAndConfirm(tx);
13633
14538
  }
13634
- async placeOrder(statePda, orderParams, subAccountId = 0, marketConfigs, txOptions = {}) {
13635
- const tx = await this.placeOrderTx(new web3_js.PublicKey(statePda), orderParams, subAccountId, marketConfigs, txOptions);
14539
+ async placeOrder(statePda, orderParams, subAccountId = 0, txOptions = {}) {
14540
+ const tx = await this.placeOrderTx(new web3_js.PublicKey(statePda), orderParams, subAccountId, txOptions);
13636
14541
  return await this.base.sendAndConfirm(tx);
13637
14542
  }
13638
- async modifyOrder(statePda, modifyOrderParams, subAccountId = 0, marketConfigs, txOptions = {}) {
13639
- const tx = await this.modifyOrderTx(new web3_js.PublicKey(statePda), modifyOrderParams, subAccountId, marketConfigs, txOptions);
14543
+ async modifyOrder(statePda, modifyOrderParams, subAccountId = 0, txOptions = {}) {
14544
+ const tx = await this.modifyOrderTx(new web3_js.PublicKey(statePda), modifyOrderParams, subAccountId, txOptions);
13640
14545
  return await this.base.sendAndConfirm(tx);
13641
14546
  }
13642
- async cancelOrders(statePda, marketType, marketIndex, direction, subAccountId = 0, marketConfigs, txOptions = {}) {
13643
- const tx = await this.cancelOrdersTx(new web3_js.PublicKey(statePda), marketType, marketIndex, direction, subAccountId, marketConfigs, txOptions);
14547
+ async cancelOrders(statePda, marketType, marketIndex, direction, subAccountId = 0, txOptions = {}) {
14548
+ const tx = await this.cancelOrdersTx(new web3_js.PublicKey(statePda), marketType, marketIndex, direction, subAccountId, txOptions);
13644
14549
  return await this.base.sendAndConfirm(tx);
13645
14550
  }
13646
- async cancelOrdersByIds(statePda, orderIds, subAccountId = 0, marketConfigs, txOptions = {}) {
13647
- const tx = await this.cancelOrdersByIdsTx(new web3_js.PublicKey(statePda), orderIds, subAccountId, marketConfigs, txOptions);
14551
+ async cancelOrdersByIds(statePda, orderIds, subAccountId = 0, txOptions = {}) {
14552
+ const tx = await this.cancelOrdersByIdsTx(new web3_js.PublicKey(statePda), orderIds, subAccountId, txOptions);
13648
14553
  return await this.base.sendAndConfirm(tx);
13649
14554
  }
13650
- async settlePnl(statePda, marketIndex, subAccountId = 0, marketConfigs, txOptions = {}) {
13651
- const tx = await this.settlePnlTx(new web3_js.PublicKey(statePda), marketIndex, subAccountId, marketConfigs, txOptions);
14555
+ async settlePnl(statePda, marketIndex, subAccountId = 0, txOptions = {}) {
14556
+ const tx = await this.settlePnlTx(new web3_js.PublicKey(statePda), marketIndex, subAccountId, txOptions);
13652
14557
  return await this.base.sendAndConfirm(tx);
13653
14558
  }
13654
- async priceDrift(statePda, marketConfigs, priceDenom, txOptions = {}) {
13655
- const tx = await this.priceDriftTx(new web3_js.PublicKey(statePda), marketConfigs, priceDenom, txOptions);
14559
+ async priceDrift(statePda, priceDenom, txOptions = {}) {
14560
+ const tx = await this.priceDriftTx(new web3_js.PublicKey(statePda), priceDenom, txOptions);
13656
14561
  return await this.base.sendAndConfirm(tx);
13657
14562
  }
13658
- /*
13659
- * Utils
13660
- */ getUser(statePda, subAccountId = 0) {
14563
+ getGlamReferrerPdas() {
14564
+ return {
14565
+ user: this.getUserPda(GLAM_REFERRER, 0),
14566
+ userStats: this.getUserStatsPda(GLAM_REFERRER)
14567
+ };
14568
+ }
14569
+ parsePerpMarket(data) {
14570
+ const marketPda = new web3_js.PublicKey(data.subarray(8, 40));
14571
+ const oracle = new web3_js.PublicKey(data.subarray(40, 72));
14572
+ const name = this.charsToName(data.subarray(1000, 1032));
14573
+ const oralceEnum = data.subarray(926, 927).readUint8();
14574
+ const oracleSource = OracleSource.get(oralceEnum);
14575
+ const marketIndex = data.subarray(1160, 1162).readUint16LE();
14576
+ return {
14577
+ name,
14578
+ marketPda,
14579
+ marketIndex,
14580
+ oracle,
14581
+ oracleSource
14582
+ };
14583
+ }
14584
+ parseSpotMarket(data) {
14585
+ const marketPda = new web3_js.PublicKey(data.subarray(8, 40));
14586
+ const oracle = new web3_js.PublicKey(data.subarray(40, 72));
14587
+ const mint = new web3_js.PublicKey(data.subarray(72, 104));
14588
+ const vault = new web3_js.PublicKey(data.subarray(104, 136));
14589
+ const name = this.charsToName(data.subarray(136, 168));
14590
+ const cumulativeDepositInterest = new anchor.BN(data.subarray(464, 480), "le");
14591
+ const cumulativeBorrowInterest = new anchor.BN(data.subarray(480, 496), "le");
14592
+ const decimals = data.subarray(680, 684).readUint32LE();
14593
+ const marketIndex = data.subarray(684, 686).readUint16LE();
14594
+ const oralceEnum = data.subarray(687, 688).readUint8();
14595
+ const oracleSource = OracleSource.get(oralceEnum);
14596
+ const tokenProgram = data.subarray(734, 735).readUint8() == 0 ? splToken.TOKEN_PROGRAM_ID : splToken.TOKEN_2022_PROGRAM_ID;
14597
+ return {
14598
+ name,
14599
+ marketIndex,
14600
+ marketPda,
14601
+ oracle,
14602
+ oracleSource,
14603
+ vault,
14604
+ mint,
14605
+ decimals,
14606
+ tokenProgram,
14607
+ cumulativeDepositInterest,
14608
+ cumulativeBorrowInterest
14609
+ };
14610
+ }
14611
+ async calcSpotBalance(marketIndex, scaledBalance, scaledBalanceType) {
14612
+ const { decimals, cumulativeDepositInterest, cumulativeBorrowInterest } = await this.fetchAndParseSpotMarket(marketIndex);
14613
+ const precisionAdjustment = new anchor.BN(10 ** (19 - decimals));
14614
+ let interest = cumulativeDepositInterest;
14615
+ if (scaledBalanceType === SpotBalanceType.BORROW) {
14616
+ interest = cumulativeBorrowInterest;
14617
+ }
14618
+ const balance = scaledBalance.mul(interest).div(precisionAdjustment);
14619
+ const amount = scaledBalanceType === SpotBalanceType.BORROW ? balance.neg().toNumber() : balance.toNumber();
14620
+ const uiAmount = amount / 10 ** decimals;
14621
+ return {
14622
+ amount,
14623
+ uiAmount
14624
+ };
14625
+ }
14626
+ getDriftUserPdas(statePda, subAccountId = 0) {
13661
14627
  const vault = this.base.getVaultPda(new web3_js.PublicKey(statePda));
13662
- return [
13663
- sdk.getUserAccountPublicKeySync(DRIFT_PROGRAM_ID, vault, subAccountId),
13664
- sdk.getUserStatsAccountPublicKey(DRIFT_PROGRAM_ID, vault)
13665
- ];
14628
+ return {
14629
+ user: this.getUserPda(vault, subAccountId),
14630
+ userStats: this.getUserStatsPda(vault)
14631
+ };
13666
14632
  }
13667
- getGlamReferrer() {
13668
- return [
13669
- sdk.getUserAccountPublicKeySync(DRIFT_PROGRAM_ID, GLAM_REFERRER, 0),
13670
- sdk.getUserStatsAccountPublicKey(DRIFT_PROGRAM_ID, GLAM_REFERRER)
13671
- ];
14633
+ get driftStatePda() {
14634
+ return web3_js.PublicKey.findProgramAddressSync([
14635
+ Buffer.from("drift_state")
14636
+ ], DRIFT_PROGRAM_ID)[0];
13672
14637
  }
13673
- async fetchMarketConfigs() {
13674
- const response = await fetch("https://api.glam.systems/v0/drift/market_configs/");
13675
- if (!response.ok) {
13676
- throw new Error(`Failed to fetch market configs: ${response.status}`);
14638
+ async fetchAndParseSpotMarket(marketIndex) {
14639
+ const markets = await this.fetchAndParseSpotMarkets([
14640
+ marketIndex
14641
+ ]);
14642
+ if (!markets || markets.length === 0) {
14643
+ throw new Error(`Spot market not found at index ${marketIndex}`);
13677
14644
  }
13678
- const data = await response.json();
13679
- return data;
14645
+ return markets[0];
14646
+ }
14647
+ async fetchAndParseSpotMarkets(marketIndexes) {
14648
+ const indexesToFetch = marketIndexes.filter((marketIndex)=>!this.spotMarkets.has(marketIndex));
14649
+ if (indexesToFetch.length > 0) {
14650
+ console.log("Fetching spot markets:", indexesToFetch);
14651
+ const marketPdas = indexesToFetch.map((marketIndex)=>this.getMarketPda(MarketType.SPOT, marketIndex));
14652
+ const accounts = await this.base.provider.connection.getMultipleAccountsInfo(marketPdas);
14653
+ accounts.forEach((account)=>{
14654
+ if (account) {
14655
+ const spotMarket = this.parseSpotMarket(account.data);
14656
+ this.spotMarkets.set(spotMarket.marketIndex, spotMarket);
14657
+ }
14658
+ });
14659
+ }
14660
+ // At this point this.spotMarkets has all the requested markets
14661
+ return marketIndexes.map((marketIndex)=>this.spotMarkets.get(marketIndex)).filter((m)=>m);
13680
14662
  }
13681
- async fetchGlamDriftUser(glamState, subAccountId = 0) {
13682
- const vault = this.base.getVaultPda(new web3_js.PublicKey(glamState));
13683
- const response = await fetch(`https://api.glam.systems/v0/drift/user?authority=${vault.toBase58()}&accountId=${subAccountId}`);
13684
- const data = await response.json();
13685
- if (!data) {
13686
- throw new Error("Failed to fetch drift user.");
14663
+ async fetchAndParsePerpMarket(marketIndex) {
14664
+ const markets = await this.fetchAndParsePerpMarkets([
14665
+ marketIndex
14666
+ ]);
14667
+ if (!markets || markets.length === 0) {
14668
+ throw new Error(`Perp market not found at index ${marketIndex}`);
13687
14669
  }
13688
- return data;
14670
+ return markets[0];
14671
+ }
14672
+ async fetchAndParsePerpMarkets(marketIndexes) {
14673
+ const indexesToFetch = marketIndexes.filter((marketIndex)=>!this.perpMarkets.has(marketIndex));
14674
+ if (indexesToFetch.length > 0) {
14675
+ console.log("Fetching perp markets:", indexesToFetch);
14676
+ const marketPdas = marketIndexes.map((marketIndex)=>this.getMarketPda(MarketType.PERP, marketIndex));
14677
+ const accounts = await this.base.provider.connection.getMultipleAccountsInfo(marketPdas);
14678
+ accounts.forEach((account)=>{
14679
+ if (account) {
14680
+ const perpMarket = this.parsePerpMarket(account.data);
14681
+ this.perpMarkets.set(perpMarket.marketIndex, perpMarket);
14682
+ }
14683
+ });
14684
+ } else {
14685
+ console.log("Requested perp markets already cached:", marketIndexes);
14686
+ }
14687
+ return marketIndexes.map((marketIndex)=>this.perpMarkets.get(marketIndex)).filter((m)=>m);
13689
14688
  }
13690
- async getPositions(statePda, subAccountId = 0) {
13691
- const { spotPositions, perpPositions } = await this.fetchGlamDriftUser(new web3_js.PublicKey(statePda), subAccountId);
14689
+ async fetchMarketConfigs() {
14690
+ // const response = await fetch(
14691
+ // "https://api.glam.systems/v0/drift/market_configs/",
14692
+ // );
14693
+ // if (!response.ok) {
14694
+ // throw new Error(`Failed to fetch market configs: ${response.status}`);
14695
+ // }
14696
+ // const data = await response.json();
14697
+ // const { orderConstants, perp, spot } = data;
14698
+ // // Transform perp market from API to `PerpMarket` type
14699
+ // const perpMarkets = perp.map((m: any) => ({
14700
+ // marketIndex: m.marketIndex,
14701
+ // marketPda: m.marketPDA,
14702
+ // oracle: new PublicKey(m.oracle),
14703
+ // }));
14704
+ // // Transform spot market from API to `SpotMarket` type
14705
+ // const spotMarkets = spot.map((m: any) => ({
14706
+ // marketIndex: m.marketIndex,
14707
+ // marketPda: m.marketPDA,
14708
+ // oracle: new PublicKey(m.oracle),
14709
+ // mint: new PublicKey(m.mint),
14710
+ // vault: new PublicKey(m.vaultPDA),
14711
+ // decimals: m.decimals,
14712
+ // }));
14713
+ if (!this.marketConfigs) {
14714
+ const perpMarkets = await this.fetchAndParsePerpMarkets(Array.from(Array(100).keys()));
14715
+ const spotMarkets = await this.fetchAndParseSpotMarkets(Array.from(Array(100).keys()));
14716
+ this.marketConfigs = {
14717
+ orderConstants: {
14718
+ perpBaseScale: 9,
14719
+ quoteScale: 6
14720
+ },
14721
+ perpMarkets,
14722
+ spotMarkets
14723
+ };
14724
+ }
14725
+ return this.marketConfigs;
14726
+ }
14727
+ // public async fetchGlamDriftUser(
14728
+ // glamState: PublicKey | string,
14729
+ // subAccountId: number = 0,
14730
+ // ): Promise<GlamDriftUser> {
14731
+ // const vault = this.base.getVaultPda(new PublicKey(glamState));
14732
+ // const response = await fetch(
14733
+ // `https://api.glam.systems/v0/drift/user?authority=${vault.toBase58()}&accountId=${subAccountId}`,
14734
+ // );
14735
+ // const data = await response.json();
14736
+ // if (!data) {
14737
+ // throw new Error("Failed to fetch drift user.");
14738
+ // }
14739
+ // return data as GlamDriftUser;
14740
+ // }
14741
+ charsToName(chars) {
14742
+ return String.fromCharCode(...chars).replace(/\0/g, "").trim();
14743
+ }
14744
+ async fetchDriftUser(statePda, subAccountId = 0) {
14745
+ const { user } = this.getDriftUserPdas(new web3_js.PublicKey(statePda), subAccountId);
14746
+ const accountInfo = await this.base.provider.connection.getAccountInfo(user);
14747
+ if (!accountInfo) {
14748
+ return null;
14749
+ }
14750
+ const { delegate, name, spotPositions, marginMode, perpPositions, isMarginTradingEnabled, maxMarginRatio, orders } = decodeUser(accountInfo.data);
14751
+ // Prefetch market configs
14752
+ const marketConfigs = await this.fetchMarketConfigs();
14753
+ const spotPositionsExt = await Promise.all(spotPositions.map(async (p)=>{
14754
+ const { amount, uiAmount } = await this.calcSpotBalance(p.marketIndex, p.scaledBalance, p.balanceType);
14755
+ const spotMarket = marketConfigs.spotMarkets.find((m)=>m.marketIndex === p.marketIndex);
14756
+ return {
14757
+ ...p,
14758
+ amount,
14759
+ uiAmount,
14760
+ mint: spotMarket.mint,
14761
+ decimals: spotMarket.decimals,
14762
+ marketName: spotMarket.name
14763
+ };
14764
+ }));
13692
14765
  return {
13693
- spotPositions,
13694
- perpPositions
14766
+ delegate,
14767
+ name: this.charsToName(name),
14768
+ spotPositions: spotPositionsExt,
14769
+ perpPositions,
14770
+ orders,
14771
+ marginMode,
14772
+ subAccountId,
14773
+ isMarginTradingEnabled,
14774
+ maxMarginRatio
13695
14775
  };
13696
14776
  }
14777
+ // async getPositions(statePda: PublicKey | string, subAccountId: number = 0) {
14778
+ // const driftUser = await this.fetchDriftUser(
14779
+ // new PublicKey(statePda),
14780
+ // subAccountId,
14781
+ // );
14782
+ // if (!driftUser) {
14783
+ // return { spotPositions: [], perpPositions: [] };
14784
+ // }
14785
+ // const marketConfigs = await this.fetchMarketConfigs();
14786
+ // const { spotPositions, perpPositions } = driftUser;
14787
+ // return { spotPositions, perpPositions };
14788
+ // }
13697
14789
  async fetchPolicyConfig(glamState) {
13698
- let driftUserAccount;
13699
- if (glamState && glamState.id) {
13700
- const [driftUserAddress] = this.getUser(glamState.id);
13701
- const connection = this.base.provider.connection;
13702
- const info = await connection.getAccountInfo(driftUserAddress, connection.commitment);
13703
- if (info) {
13704
- driftUserAccount = sdk.decodeUser(info.data);
13705
- }
13706
- }
14790
+ const driftUserAccount = glamState && glamState.id && await this.fetchDriftUser(glamState.id);
13707
14791
  let delegate = driftUserAccount?.delegate;
13708
- if (delegate && delegate.equals(new web3_js.PublicKey(0))) {
14792
+ if (delegate && delegate.equals(web3_js.PublicKey.default)) {
13709
14793
  delegate = undefined;
13710
14794
  }
13711
14795
  return {
@@ -13718,26 +14802,33 @@ class DriftClient {
13718
14802
  driftMarketIndexesSpot: glamState?.driftMarketIndexesSpot || []
13719
14803
  };
13720
14804
  }
13721
- async composeRemainingAccounts(glamState, subAccountId, marketConfigs, marketType, marketIndex) {
13722
- const { spotPositions, perpPositions } = await this.getPositions(glamState, subAccountId);
14805
+ async composeRemainingAccounts(glamState, subAccountId, marketType, marketIndex) {
14806
+ const driftUser = await this.fetchDriftUser(glamState, subAccountId);
14807
+ if (!driftUser) {
14808
+ throw new Error("Drift user not found");
14809
+ }
14810
+ const { spotPositions, perpPositions } = driftUser;
13723
14811
  const spotMarketIndexes = spotPositions.map((p)=>p.marketIndex);
13724
14812
  const perpMarketIndexes = perpPositions.map((p)=>p.marketIndex);
13725
14813
  // Note that marketIndex is could be 0, need to explicitly check undefined
13726
- if (this.marketTypeEquals(marketType, sdk.MarketType.SPOT) && marketIndex !== undefined && !spotMarketIndexes.includes(marketIndex)) {
14814
+ if (this.marketTypeEquals(marketType, MarketType.SPOT) && marketIndex !== undefined && !spotMarketIndexes.includes(marketIndex)) {
13727
14815
  spotMarketIndexes.push(marketIndex);
13728
- } else if (this.marketTypeEquals(marketType, sdk.MarketType.PERP) && marketIndex !== undefined && !perpMarketIndexes.includes(marketIndex)) {
14816
+ } else if (this.marketTypeEquals(marketType, MarketType.PERP) && marketIndex !== undefined && !perpMarketIndexes.includes(marketIndex)) {
13729
14817
  perpMarketIndexes.push(marketIndex);
13730
14818
  }
13731
14819
  // Also include USDC spot market if we're composing remaining accounts for spot or perp orders
13732
- if (this.marketTypeEquals(marketType, sdk.MarketType.PERP) || this.marketTypeEquals(marketType, sdk.MarketType.SPOT)) {
14820
+ if (this.marketTypeEquals(marketType, MarketType.PERP) || this.marketTypeEquals(marketType, MarketType.SPOT)) {
13733
14821
  if (!spotMarketIndexes.includes(0)) {
13734
14822
  spotMarketIndexes.push(0);
13735
14823
  }
13736
14824
  }
13737
- const oracles = spotMarketIndexes.map((i)=>marketConfigs.spot[i].oracle).concat(perpMarketIndexes.map((i)=>marketConfigs.perp[i].oracle));
13738
- const markets = spotMarketIndexes.map((i)=>marketConfigs.spot[i].marketPDA).concat(perpMarketIndexes.map((i)=>marketConfigs.perp[i].marketPDA));
13739
- console.log("[composeRemainingAccounts] markets:", markets);
13740
- console.log("[composeRemainingAccounts] oracles:", oracles);
14825
+ const spotMarkets = await this.fetchAndParseSpotMarkets(spotMarketIndexes);
14826
+ const perpMarkets = await this.fetchAndParsePerpMarkets(perpMarketIndexes);
14827
+ console.log("[composeRemainingAccounts] perpMarkets:", perpMarkets);
14828
+ const oracles = spotMarkets.map((m)=>m.oracle).concat(perpMarkets.map((m)=>m.oracle));
14829
+ const markets = spotMarkets.map((m)=>m.marketPda).concat(perpMarkets.map((m)=>m.marketPda));
14830
+ console.log("[composeRemainingAccounts] markets:", markets.map((m)=>m.toBase58()));
14831
+ console.log("[composeRemainingAccounts] oracles:", oracles.map((o)=>o.toBase58()));
13741
14832
  return oracles.map((o)=>({
13742
14833
  pubkey: new web3_js.PublicKey(o),
13743
14834
  isWritable: false,
@@ -13749,30 +14840,36 @@ class DriftClient {
13749
14840
  })));
13750
14841
  }
13751
14842
  async initializeUserStatsIx(glamState, glamSigner) {
13752
- const [_, userStats] = this.getUser(glamState);
13753
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
14843
+ const { userStats } = this.getDriftUserPdas(glamState);
13754
14844
  // @ts-ignore
13755
14845
  return await this.base.program.methods.driftInitializeUserStats().accounts({
13756
14846
  glamState,
13757
14847
  glamSigner,
13758
- state,
14848
+ state: this.driftStatePda,
13759
14849
  userStats
13760
14850
  }).instruction();
13761
14851
  }
13762
14852
  async initializeUserIx(glamState, glamSigner, subAccountId) {
13763
14853
  const name = `GLAM *.+ ${subAccountId}`.split("").map((char)=>char.charCodeAt(0)).concat(Array(24).fill(0));
13764
- const [user, userStats] = this.getUser(glamState, subAccountId);
13765
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13766
- const remainingAccounts = this.getGlamReferrer().map((p)=>({
13767
- pubkey: p,
14854
+ const { user, userStats } = this.getDriftUserPdas(glamState, subAccountId);
14855
+ const { user: referrer, userStats: referrerStats } = this.getGlamReferrerPdas();
14856
+ const remainingAccounts = [
14857
+ {
14858
+ pubkey: referrer,
13768
14859
  isWritable: true,
13769
14860
  isSigner: false
13770
- }));
14861
+ },
14862
+ {
14863
+ pubkey: referrerStats,
14864
+ isWritable: true,
14865
+ isSigner: false
14866
+ }
14867
+ ];
13771
14868
  return await this.base.program.methods.driftInitializeUser(subAccountId, name).accounts({
13772
14869
  glamState,
13773
14870
  user,
13774
14871
  userStats,
13775
- state,
14872
+ state: this.driftStatePda,
13776
14873
  glamSigner
13777
14874
  }).remainingAccounts(remainingAccounts).instruction();
13778
14875
  }
@@ -13780,7 +14877,7 @@ class DriftClient {
13780
14877
  const glamSigner = txOptions.signer || this.base.getSigner();
13781
14878
  const tx = new web3_js.Transaction();
13782
14879
  // Create userStats account if it doesn't exist
13783
- const [_, userStats] = this.getUser(glamState);
14880
+ const { userStats } = this.getDriftUserPdas(glamState);
13784
14881
  const userStatsInfo = await this.base.provider.connection.getAccountInfo(userStats);
13785
14882
  if (!userStatsInfo) {
13786
14883
  tx.add(await this.initializeUserStatsIx(glamState, glamSigner));
@@ -13791,7 +14888,7 @@ class DriftClient {
13791
14888
  }
13792
14889
  async updateUserCustomMarginRatioIx(glamState, maxLeverage, subAccountId = 0, txOptions = {}) {
13793
14890
  const glamSigner = txOptions.signer || this.base.getSigner();
13794
- const [user] = this.getUser(glamState, subAccountId);
14891
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
13795
14892
  // https://github.com/drift-labs/protocol-v2/blob/babed162b08b1fe34e49a81c5aa3e4ec0a88ecdf/programs/drift/src/math/constants.rs#L183-L184
13796
14893
  const marginRatio = DRIFT_MARGIN_PRECISION / maxLeverage;
13797
14894
  return await this.base.program.methods.driftUpdateUserCustomMarginRatio(subAccountId, marginRatio).accounts({
@@ -13806,7 +14903,7 @@ class DriftClient {
13806
14903
  }
13807
14904
  async updateUserMarginTradingEnabledIx(glamState, marginTradingEnabled, subAccountId = 0, txOptions = {}) {
13808
14905
  const glamSigner = txOptions.signer || this.base.getSigner();
13809
- const [user] = this.getUser(glamState, subAccountId);
14906
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
13810
14907
  return await this.base.program.methods.driftUpdateUserMarginTradingEnabled(subAccountId, marginTradingEnabled).accounts({
13811
14908
  glamState,
13812
14909
  glamSigner,
@@ -13819,7 +14916,7 @@ class DriftClient {
13819
14916
  }
13820
14917
  async updateUserDelegateIx(glamState, delegate, subAccountId = 0, txOptions = {}) {
13821
14918
  const glamSigner = txOptions.signer || this.base.getSigner();
13822
- const [user] = this.getUser(glamState, subAccountId);
14919
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
13823
14920
  return await this.base.program.methods.driftUpdateUserDelegate(subAccountId, new web3_js.PublicKey(delegate)).accounts({
13824
14921
  glamState,
13825
14922
  glamSigner,
@@ -13832,32 +14929,28 @@ class DriftClient {
13832
14929
  }
13833
14930
  async deleteUserTx(glamState, subAccountId = 0, txOptions = {}) {
13834
14931
  const glamSigner = txOptions.signer || this.base.getSigner();
13835
- const [user, userStats] = this.getUser(glamState, subAccountId);
13836
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
14932
+ const { user, userStats } = this.getDriftUserPdas(glamState, subAccountId);
13837
14933
  const tx = await this.base.program.methods.driftDeleteUser().accounts({
13838
14934
  glamState,
13839
- state,
14935
+ state: this.driftStatePda,
13840
14936
  user,
13841
14937
  userStats,
13842
14938
  glamSigner
13843
14939
  }).transaction();
13844
14940
  return await this.base.intoVersionedTransaction(tx, txOptions);
13845
14941
  }
13846
- async depositTx(glamState, amount, marketIndex = 1, subAccountId = 0, marketConfigs, txOptions = {}) {
14942
+ async depositTx(glamState, amount, marketIndex = 1, subAccountId = 0, txOptions = {}) {
13847
14943
  const glamSigner = txOptions.signer || this.base.getSigner();
13848
- const [user, userStats] = this.getUser(glamState, subAccountId);
13849
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13850
- const { mint, oracle, marketPDA, vaultPDA } = marketConfigs.spot[marketIndex];
13851
- console.log("mint, oracle, marketPDA, vaultPDA", mint, oracle, marketPDA, vaultPDA);
14944
+ const { user, userStats } = this.getDriftUserPdas(glamState, subAccountId);
14945
+ const { mint, oracle, tokenProgram, marketPda, vault: driftVault } = await this.fetchAndParseSpotMarket(marketIndex);
14946
+ console.log(`Spot market ${marketIndex} mint ${mint}, oracle: ${oracle}, marketPda: ${marketPda}, vault: ${driftVault}`);
13852
14947
  const preInstructions = [];
13853
14948
  const postInstructions = [];
13854
14949
  // If drift user doesn't exist, prepend initializeUserStats and initializeUser instructions
13855
- try {
13856
- await this.fetchGlamDriftUser(glamState, subAccountId);
13857
- } catch (_) {
14950
+ if (!await this.fetchDriftUser(glamState, subAccountId)) {
13858
14951
  preInstructions.push(await this.initializeUserStatsIx(glamState, glamSigner), await this.initializeUserIx(glamState, glamSigner, subAccountId));
13859
14952
  }
13860
- if (mint === WSOL.toBase58()) {
14953
+ if (mint.equals(WSOL)) {
13861
14954
  const wrapSolIxs = await this.base.maybeWrapSol(glamState, amount, glamSigner);
13862
14955
  preInstructions.push(...wrapSolIxs);
13863
14956
  // If we need to wrap SOL, it means the wSOL balance will be drained,
@@ -13871,79 +14964,97 @@ class DriftClient {
13871
14964
  }).instruction();
13872
14965
  postInstructions.push(closeTokenAccountIx);
13873
14966
  }
13874
- const tx = await this.base.program.methods.driftDeposit(marketIndex, amount, false).accounts({
13875
- glamState,
13876
- state,
13877
- user,
13878
- userStats,
13879
- spotMarketVault: new web3_js.PublicKey(vaultPDA),
13880
- userTokenAccount: this.base.getVaultAta(glamState, new web3_js.PublicKey(mint)),
13881
- glamSigner,
13882
- tokenProgram: splToken.TOKEN_PROGRAM_ID
13883
- }).remainingAccounts([
14967
+ const remainingAccounts = [
13884
14968
  {
13885
14969
  pubkey: new web3_js.PublicKey(oracle),
13886
14970
  isSigner: false,
13887
14971
  isWritable: false
13888
14972
  },
13889
14973
  {
13890
- pubkey: new web3_js.PublicKey(marketPDA),
14974
+ pubkey: new web3_js.PublicKey(marketPda),
13891
14975
  isSigner: false,
13892
14976
  isWritable: true
13893
14977
  }
13894
- ]).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
14978
+ ];
14979
+ if (tokenProgram.equals(splToken.TOKEN_2022_PROGRAM_ID)) {
14980
+ remainingAccounts.push({
14981
+ pubkey: mint,
14982
+ isSigner: false,
14983
+ isWritable: false
14984
+ });
14985
+ }
14986
+ const tx = await this.base.program.methods.driftDeposit(marketIndex, amount, false).accounts({
14987
+ glamState,
14988
+ state: this.driftStatePda,
14989
+ user,
14990
+ userStats,
14991
+ spotMarketVault: driftVault,
14992
+ userTokenAccount: this.base.getVaultAta(glamState, mint, tokenProgram),
14993
+ glamSigner,
14994
+ tokenProgram
14995
+ }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
13895
14996
  return await this.base.intoVersionedTransaction(tx, txOptions);
13896
14997
  }
13897
- async withdrawTx(statePda, amount, marketIndex = 1, subAccountId = 0, marketConfigs, txOptions = {}) {
14998
+ async withdrawTx(statePda, amount, marketIndex = 1, subAccountId = 0, txOptions = {}) {
13898
14999
  const glamSigner = txOptions.signer || this.base.getSigner();
13899
- const [user, userStats] = this.getUser(statePda, subAccountId);
13900
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13901
- const { mint: m, vaultPDA: d } = marketConfigs.spot[marketIndex];
13902
- const mint = new web3_js.PublicKey(m);
13903
- const driftAta = new web3_js.PublicKey(d); // drift vault ata
13904
- const vault = this.base.getVaultPda(statePda);
13905
- const vaultAta = this.base.getVaultAta(statePda, mint); // glam vault ata
13906
- const remainingAccounts = await this.composeRemainingAccounts(statePda, subAccountId, marketConfigs, sdk.MarketType.SPOT, marketIndex);
13907
- const { tokenProgram } = await this.base.fetchMintWithOwner(mint);
15000
+ const { user, userStats } = this.getDriftUserPdas(statePda, subAccountId);
15001
+ const { mint, tokenProgram, vault: driftVault } = await this.fetchAndParseSpotMarket(marketIndex);
15002
+ const glamVault = this.base.getVaultPda(statePda);
15003
+ const glamVaultAta = this.base.getVaultAta(statePda, mint, tokenProgram);
15004
+ const remainingAccounts = await this.composeRemainingAccounts(statePda, subAccountId, MarketType.SPOT, marketIndex);
15005
+ if (tokenProgram.equals(splToken.TOKEN_2022_PROGRAM_ID)) {
15006
+ remainingAccounts.push({
15007
+ pubkey: mint,
15008
+ isSigner: false,
15009
+ isWritable: false
15010
+ });
15011
+ }
13908
15012
  // Create vault ata in case it doesn't exist
13909
15013
  const preInstructions = [
13910
- splToken.createAssociatedTokenAccountIdempotentInstruction(glamSigner, vaultAta, vault, mint, tokenProgram)
15014
+ splToken.createAssociatedTokenAccountIdempotentInstruction(glamSigner, glamVaultAta, glamVault, mint, tokenProgram)
13911
15015
  ];
13912
15016
  const tx = await this.base.program.methods.driftWithdraw(marketIndex, amount, false).accounts({
13913
15017
  glamState: statePda,
13914
- state,
15018
+ state: this.driftStatePda,
13915
15019
  user,
13916
15020
  userStats,
13917
15021
  glamSigner,
13918
- spotMarketVault: driftAta,
13919
- userTokenAccount: vaultAta,
13920
- driftSigner: DRIFT_VAULT,
13921
- tokenProgram: splToken.TOKEN_PROGRAM_ID
15022
+ spotMarketVault: driftVault,
15023
+ userTokenAccount: glamVaultAta,
15024
+ driftSigner: DRIFT_SIGNER,
15025
+ tokenProgram
13922
15026
  }).remainingAccounts(remainingAccounts).preInstructions(preInstructions).transaction();
13923
15027
  return await this.base.intoVersionedTransaction(tx, txOptions);
13924
15028
  }
13925
- async placeOrderTx(glamState, orderParams, subAccountId = 0, marketConfigs, txOptions = {}) {
15029
+ async placeOrderTx(glamState, orderParams, subAccountId = 0, txOptions = {}) {
13926
15030
  const { marketIndex, marketType } = orderParams;
13927
- const remainingAccounts = (await this.composeRemainingAccounts(glamState, subAccountId, marketConfigs, marketType, marketIndex)).concat(this.getGlamReferrer().map((p)=>({
13928
- pubkey: p,
15031
+ const { user: referrer, userStats: referrerStats } = this.getGlamReferrerPdas();
15032
+ const remainingAccounts = (await this.composeRemainingAccounts(glamState, subAccountId, marketType, marketIndex)).concat([
15033
+ {
15034
+ pubkey: referrer,
13929
15035
  isWritable: true,
13930
15036
  isSigner: false
13931
- })));
15037
+ },
15038
+ {
15039
+ pubkey: referrerStats,
15040
+ isWritable: true,
15041
+ isSigner: false
15042
+ }
15043
+ ]);
13932
15044
  const glamSigner = txOptions.signer || this.base.getSigner();
13933
- const [user] = this.getUser(glamState, subAccountId);
13934
- const state = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13935
- const tx = await this.base.program.methods// @ts-ignore
13936
- .driftPlaceOrders([
15045
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
15046
+ // @ts-ignore
15047
+ const tx = await this.base.program.methods.driftPlaceOrders([
13937
15048
  orderParams
13938
15049
  ]).accounts({
13939
15050
  glamState,
13940
15051
  user,
13941
- state,
15052
+ state: this.driftStatePda,
13942
15053
  glamSigner
13943
15054
  }).remainingAccounts(remainingAccounts).transaction();
13944
15055
  return await this.base.intoVersionedTransaction(tx, txOptions);
13945
15056
  }
13946
- async modifyOrderTx(statePda, modifyOrderParams, subAccountId = 0, marketConfigs, txOptions = {}) {
15057
+ async modifyOrderTx(statePda, modifyOrderParams, subAccountId = 0, txOptions = {}) {
13947
15058
  // const { marketIndex, marketType } = orderParams;
13948
15059
  // const remainingAccounts = await this.composeRemainingAccounts(
13949
15060
  // statePda,
@@ -13953,65 +15064,62 @@ class DriftClient {
13953
15064
  // marketIndex,
13954
15065
  // );
13955
15066
  const signer = txOptions.signer || this.base.getSigner();
13956
- const [user] = this.getUser(statePda, subAccountId);
13957
- const driftState = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
15067
+ const { user } = this.getDriftUserPdas(statePda, subAccountId);
13958
15068
  const tx = await this.base.program.methods// @ts-ignore
13959
15069
  .driftModifyOrder(1, modifyOrderParams).accounts({
13960
15070
  glamState: statePda,
13961
15071
  glamSigner: signer,
13962
15072
  user,
13963
- state: driftState
15073
+ state: this.driftStatePda
13964
15074
  })// .remainingAccounts(remainingAccounts)
13965
15075
  .transaction();
13966
15076
  return await this.base.intoVersionedTransaction(tx, txOptions);
13967
15077
  }
13968
- async cancelOrdersTx(glamState, marketType, marketIndex, direction, subAccountId = 0, marketConfigs, txOptions = {}) {
15078
+ async cancelOrdersTx(glamState, marketType, marketIndex, direction, subAccountId = 0, txOptions = {}) {
13969
15079
  const glamSigner = txOptions.signer || this.base.getSigner();
13970
- const [user] = this.getUser(glamState, subAccountId);
13971
- const driftState = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13972
- const remainingAccounts = await this.composeRemainingAccounts(glamState, subAccountId, marketConfigs, marketType, marketIndex);
15080
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
15081
+ const remainingAccounts = await this.composeRemainingAccounts(glamState, subAccountId, marketType, marketIndex);
13973
15082
  // @ts-ignore
13974
15083
  const tx = await this.base.program.methods.driftCancelOrders(marketType, marketIndex, direction).accounts({
13975
15084
  glamState,
13976
15085
  glamSigner,
13977
15086
  user,
13978
- state: driftState
15087
+ state: this.driftStatePda
13979
15088
  }).remainingAccounts(remainingAccounts).transaction();
13980
15089
  return await this.base.intoVersionedTransaction(tx, txOptions);
13981
15090
  }
13982
- async cancelOrdersByIdsTx(glamState, orderIds, subAccountId = 0, marketConfigs, txOptions = {}) {
15091
+ async cancelOrdersByIdsTx(glamState, orderIds, subAccountId = 0, txOptions = {}) {
13983
15092
  const glamSigner = txOptions.signer || this.base.getSigner();
13984
- const [user] = this.getUser(glamState, subAccountId);
13985
- const driftState = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13986
- const remainingAccounts = await this.composeRemainingAccounts(glamState, subAccountId, marketConfigs);
15093
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
15094
+ const remainingAccounts = await this.composeRemainingAccounts(glamState, subAccountId);
15095
+ // @ts-ignore
13987
15096
  const tx = await this.base.program.methods.driftCancelOrdersByIds(orderIds).accounts({
13988
15097
  glamState,
13989
15098
  glamSigner,
13990
15099
  user,
13991
- state: driftState
15100
+ state: this.driftStatePda
13992
15101
  }).remainingAccounts(remainingAccounts).transaction();
13993
15102
  return await this.base.intoVersionedTransaction(tx, txOptions);
13994
15103
  }
13995
- async settlePnlTx(glamState, marketIndex, subAccountId = 0, marketConfigs, txOptions = {}) {
15104
+ async settlePnlTx(glamState, marketIndex, subAccountId = 0, txOptions = {}) {
13996
15105
  const glamSigner = txOptions.signer || this.base.getSigner();
13997
- const [user] = this.getUser(glamState, subAccountId);
13998
- const driftState = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
13999
- const { vaultPDA } = marketConfigs.spot[marketIndex];
15106
+ const { user } = this.getDriftUserPdas(glamState, subAccountId);
15107
+ const { vault: driftVault } = await this.fetchAndParseSpotMarket(marketIndex);
15108
+ // @ts-ignore
14000
15109
  const tx = await this.base.program.methods.driftSettlePnl(marketIndex).accounts({
14001
15110
  glamState,
14002
15111
  glamSigner,
14003
15112
  user,
14004
- state: driftState,
14005
- spotMarketVault: new web3_js.PublicKey(vaultPDA)
15113
+ state: this.driftStatePda,
15114
+ spotMarketVault: driftVault
14006
15115
  }).transaction();
14007
15116
  return await this.base.intoVersionedTransaction(tx, txOptions);
14008
15117
  }
14009
- async priceDriftTx(glamState, marketConfigs, priceDenom, txOptions = {}) {
15118
+ async priceDriftTx(glamState, priceDenom, txOptions = {}) {
14010
15119
  const signer = txOptions.signer || this.base.getSigner();
14011
15120
  const glamVault = this.base.getVaultPda(glamState);
14012
- const [user, userStats] = this.getUser(glamState);
14013
- const driftState = await sdk.getDriftStateAccountPublicKey(DRIFT_PROGRAM_ID);
14014
- const remainingAccounts = await this.composeRemainingAccounts(glamState, 0, marketConfigs);
15121
+ const { user, userStats } = this.getDriftUserPdas(glamState);
15122
+ const remainingAccounts = await this.composeRemainingAccounts(glamState, 0);
14015
15123
  const tx = await this.base.program.methods.priceDrift(priceDenom).accounts({
14016
15124
  glamState,
14017
15125
  signer,
@@ -14019,12 +15127,30 @@ class DriftClient {
14019
15127
  user,
14020
15128
  userStats,
14021
15129
  solOracle: SOL_ORACLE,
14022
- state: driftState
15130
+ state: this.driftStatePda
14023
15131
  }).remainingAccounts(remainingAccounts).transaction();
14024
15132
  return await this.base.intoVersionedTransaction(tx, txOptions);
14025
15133
  }
14026
15134
  constructor(base){
14027
15135
  this.base = base;
15136
+ this.spotMarkets = new Map();
15137
+ this.perpMarkets = new Map();
15138
+ this.marketConfigs = null;
15139
+ this./*
15140
+ * Utils
15141
+ */ getMarketPda = (marketType, marketIndex)=>web3_js.PublicKey.findProgramAddressSync([
15142
+ Buffer.from(`${marketType === MarketType.PERP ? "perp" : "spot"}_market`),
15143
+ new anchor__namespace.BN(marketIndex).toArrayLike(Buffer, "le", 2)
15144
+ ], DRIFT_PROGRAM_ID)[0];
15145
+ this.getUserPda = (authority, subAccountId = 0)=>web3_js.PublicKey.findProgramAddressSync([
15146
+ Buffer.from("user"),
15147
+ authority.toBuffer(),
15148
+ new anchor__namespace.BN(subAccountId).toArrayLike(Buffer, "le", 2)
15149
+ ], DRIFT_PROGRAM_ID)[0];
15150
+ this.getUserStatsPda = (authority)=>web3_js.PublicKey.findProgramAddressSync([
15151
+ Buffer.from("user_stats"),
15152
+ authority.toBuffer()
15153
+ ], DRIFT_PROGRAM_ID)[0];
14028
15154
  this.marketTypeEquals = (a, b)=>a && Object.keys(a)[0] === Object.keys(b)[0];
14029
15155
  }
14030
15156
  }
@@ -17387,15 +18513,58 @@ const getPriorityFeeEstimate = async (heliusApiKey, tx, accountKeys, priorityLev
17387
18513
  return data.result.priorityFeeEstimate;
17388
18514
  };
17389
18515
 
18516
+ function getLimitOrderParams(params) {
18517
+ return getOrderParams(Object.assign({}, params, {
18518
+ orderType: OrderType.LIMIT
18519
+ }));
18520
+ }
18521
+ function getTriggerMarketOrderParams(params) {
18522
+ return getOrderParams(Object.assign({}, params, {
18523
+ orderType: OrderType.TRIGGER_MARKET
18524
+ }));
18525
+ }
18526
+ function getTriggerLimitOrderParams(params) {
18527
+ return getOrderParams(Object.assign({}, params, {
18528
+ orderType: OrderType.TRIGGER_LIMIT
18529
+ }));
18530
+ }
18531
+ function getMarketOrderParams(params) {
18532
+ return getOrderParams(Object.assign({}, params, {
18533
+ orderType: OrderType.MARKET
18534
+ }));
18535
+ }
18536
+ /**
18537
+ * Creates an OrderParams object with the given OptionalOrderParams and any params to override.
18538
+ *
18539
+ * example:
18540
+ * ```
18541
+ * const orderParams = getOrderParams(optionalOrderParams, { marketType: MarketType.PERP });
18542
+ * ```
18543
+ *
18544
+ * @param optionalOrderParams
18545
+ * @param overridingParams
18546
+ * @returns
18547
+ */ function getOrderParams(optionalOrderParams, overridingParams = {}) {
18548
+ return Object.assign({}, DefaultOrderParams, optionalOrderParams, overridingParams);
18549
+ }
18550
+
17390
18551
  exports.ASSETS_MAINNET = ASSETS_MAINNET;
17391
18552
  exports.ASSETS_TESTS = ASSETS_TESTS;
18553
+ exports.AssetTier = AssetTier;
17392
18554
  exports.BaseClient = BaseClient;
17393
18555
  exports.ClusterNetwork = ClusterNetwork;
17394
18556
  exports.CompanyModel = CompanyModel;
18557
+ exports.ContractTier = ContractTier;
18558
+ exports.ContractType = ContractType;
17395
18559
  exports.CreatedModel = CreatedModel;
17396
18560
  exports.DRIFT_PROGRAM_ID = DRIFT_PROGRAM_ID;
18561
+ exports.DefaultOrderParams = DefaultOrderParams;
17397
18562
  exports.DelegateAcl = DelegateAcl;
18563
+ exports.DepositDirection = DepositDirection;
18564
+ exports.DepositExplanation = DepositExplanation;
17398
18565
  exports.DriftClient = DriftClient;
18566
+ exports.ExchangeStatus = ExchangeStatus;
18567
+ exports.FuelOverflowStatus = FuelOverflowStatus;
17399
18568
  exports.FundOpenfundsModel = FundOpenfundsModel;
17400
18569
  exports.GLAM_REFERRER = GLAM_REFERRER;
17401
18570
  exports.GOVERNANCE_PROGRAM_ID = GOVERNANCE_PROGRAM_ID;
@@ -17405,6 +18574,7 @@ exports.GlamIdl = GlamIdl;
17405
18574
  exports.GlamIntegrations = GlamIntegrations;
17406
18575
  exports.GlamPermissions = GlamPermissions;
17407
18576
  exports.GlamProtocolIdlJson = GlamProtocolIdlJson;
18577
+ exports.InsuranceFundOperation = InsuranceFundOperation;
17408
18578
  exports.JITOSOL = JITOSOL;
17409
18579
  exports.JITO_STAKE_POOL = JITO_STAKE_POOL;
17410
18580
  exports.JITO_TIP_DEFAULT = JITO_TIP_DEFAULT;
@@ -17418,6 +18588,8 @@ exports.JupiterVoteClient = JupiterVoteClient;
17418
18588
  exports.KAMINO_FARM_PROGRAM = KAMINO_FARM_PROGRAM;
17419
18589
  exports.KAMINO_LENDING_PROGRAM = KAMINO_LENDING_PROGRAM;
17420
18590
  exports.KAMINO_OBTRIGATION_SIZE = KAMINO_OBTRIGATION_SIZE;
18591
+ exports.LPAction = LPAction;
18592
+ exports.LiquidationType = LiquidationType;
17421
18593
  exports.MARINADE_PROGRAM_ID = MARINADE_PROGRAM_ID;
17422
18594
  exports.MARINADE_TICKET_SIZE = MARINADE_TICKET_SIZE;
17423
18595
  exports.MEMO_PROGRAM = MEMO_PROGRAM;
@@ -17426,11 +18598,27 @@ exports.METEORA_DLMM_PROGRAM = METEORA_DLMM_PROGRAM;
17426
18598
  exports.METEORA_POSITION_SIZE = METEORA_POSITION_SIZE;
17427
18599
  exports.MSOL = MSOL;
17428
18600
  exports.ManagerModel = ManagerModel;
18601
+ exports.MarginMode = MarginMode;
18602
+ exports.MarketStatus = MarketStatus;
18603
+ exports.MarketType = MarketType;
17429
18604
  exports.Metadata = Metadata;
17430
18605
  exports.MintIdlModel = MintIdlModel;
17431
18606
  exports.MintModel = MintModel;
17432
18607
  exports.MintOpenfundsModel = MintOpenfundsModel;
18608
+ exports.ModifyOrderPolicy = ModifyOrderPolicy;
18609
+ exports.OracleSource = OracleSource;
18610
+ exports.OracleSourceNum = OracleSourceNum;
18611
+ exports.OrderAction = OrderAction;
18612
+ exports.OrderActionExplanation = OrderActionExplanation;
18613
+ exports.OrderStatus = OrderStatus;
18614
+ exports.OrderTriggerCondition = OrderTriggerCondition;
18615
+ exports.OrderType = OrderType;
18616
+ exports.PerpOperation = PerpOperation;
18617
+ exports.PlaceAndTakeOrderSuccessCondition = PlaceAndTakeOrderSuccessCondition;
18618
+ exports.PositionDirection = PositionDirection;
18619
+ exports.PostOnlyParams = PostOnlyParams;
17433
18620
  exports.PriceDenom = PriceDenom;
18621
+ exports.ReferrerStatus = ReferrerStatus;
17434
18622
  exports.SANCTUM_STAKE_POOL_PROGRAM_ID = SANCTUM_STAKE_POOL_PROGRAM_ID;
17435
18623
  exports.SEED_ESCROW = SEED_ESCROW;
17436
18624
  exports.SEED_METADATA = SEED_METADATA;
@@ -17439,20 +18627,43 @@ exports.SEED_STATE = SEED_STATE;
17439
18627
  exports.SEED_VAULT = SEED_VAULT;
17440
18628
  exports.SOL_ORACLE = SOL_ORACLE;
17441
18629
  exports.STAKE_ACCOUNT_SIZE = STAKE_ACCOUNT_SIZE;
18630
+ exports.SettlePnlExplanation = SettlePnlExplanation;
18631
+ exports.SettlePnlMode = SettlePnlMode;
18632
+ exports.SpotBalanceType = SpotBalanceType;
18633
+ exports.SpotFulfillmentConfigStatus = SpotFulfillmentConfigStatus;
18634
+ exports.SpotFulfillmentStatus = SpotFulfillmentStatus;
18635
+ exports.SpotFulfillmentType = SpotFulfillmentType;
18636
+ exports.SpotOperation = SpotOperation;
18637
+ exports.StakeAction = StakeAction;
17442
18638
  exports.StateIdlModel = StateIdlModel;
17443
18639
  exports.StateModel = StateModel;
18640
+ exports.SwapDirection = SwapDirection;
18641
+ exports.SwapReduceOnly = SwapReduceOnly;
17444
18642
  exports.TRANSFER_HOOK_PROGRAM = TRANSFER_HOOK_PROGRAM;
18643
+ exports.TradeSide = TradeSide;
17445
18644
  exports.USDC = USDC;
18645
+ exports.UserStatus = UserStatus;
17446
18646
  exports.WBTC = WBTC;
17447
18647
  exports.WETH = WETH;
17448
18648
  exports.WSOL = WSOL;
18649
+ exports.ZERO = ZERO;
18650
+ exports.decodeUser = decodeUser;
17449
18651
  exports.fetchKaminoObligations = fetchKaminoObligations;
17450
18652
  exports.fetchMarinadeTicketAccounts = fetchMarinadeTicketAccounts;
17451
18653
  exports.fetchMeteoraPositions = fetchMeteoraPositions;
17452
18654
  exports.fetchStakeAccounts = fetchStakeAccounts;
17453
18655
  exports.getGlamProgram = getGlamProgram;
17454
18656
  exports.getGlamProgramId = getGlamProgramId;
18657
+ exports.getLimitOrderParams = getLimitOrderParams;
18658
+ exports.getMarketOrderParams = getMarketOrderParams;
18659
+ exports.getOrderParams = getOrderParams;
17455
18660
  exports.getPriorityFeeEstimate = getPriorityFeeEstimate;
17456
18661
  exports.getSimulationComputeUnits = getSimulationComputeUnits;
18662
+ exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
18663
+ exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
18664
+ exports.getVariant = getVariant;
17457
18665
  exports.isBrowser = isBrowser;
18666
+ exports.isOneOfVariant = isOneOfVariant;
18667
+ exports.isVariant = isVariant;
17458
18668
  exports.parseMeteoraPosition = parseMeteoraPosition;
18669
+ exports.setsAreEqual = setsAreEqual;