@glamsystems/glam-sdk 1.0.5 → 1.0.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/index.cjs.js CHANGED
@@ -42723,7 +42723,15 @@ const getStakeAccountsWithStates = async (connection, withdrawAuthority)=>{
42723
42723
  1,
42724
42724
  0,
42725
42725
  0,
42726
- 0
42726
+ 0,
42727
+ 0xff,
42728
+ 0xff,
42729
+ 0xff,
42730
+ 0xff,
42731
+ 0xff,
42732
+ 0xff,
42733
+ 0xff,
42734
+ 0xff
42727
42735
  ])
42728
42736
  }
42729
42737
  },
@@ -43575,8 +43583,28 @@ const getErrorFromRpcResponse = (rpcResponse)=>{
43575
43583
  }
43576
43584
  };
43577
43585
 
43586
+ function readUnsignedBigInt64LE(buffer, offset) {
43587
+ return new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
43588
+ }
43589
+ function readSignedBigInt64LE(buffer, offset) {
43590
+ const unsignedValue = new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
43591
+ if (unsignedValue.testn(63)) {
43592
+ const inverted = unsignedValue.notn(64).addn(1);
43593
+ return inverted.neg();
43594
+ } else {
43595
+ return unsignedValue;
43596
+ }
43597
+ }
43598
+ function readI128LE(buffer, offset) {
43599
+ const lo = buffer.readBigUInt64LE(offset);
43600
+ const hi = buffer.readBigUInt64LE(offset + 8);
43601
+ let v = (hi << 64n) + lo;
43602
+ if ((hi & 1n << 63n) !== 0n) {
43603
+ v -= 1n << 128n;
43604
+ }
43605
+ return new anchor.BN(v.toString());
43606
+ }
43578
43607
  const ZERO = new anchor.BN(0);
43579
- // # Utility Types / Enums / Constants
43580
43608
  var ExchangeStatus = /*#__PURE__*/ function(ExchangeStatus) {
43581
43609
  ExchangeStatus[ExchangeStatus["ACTIVE"] = 0] = "ACTIVE";
43582
43610
  ExchangeStatus[ExchangeStatus["DEPOSIT_PAUSED"] = 1] = "DEPOSIT_PAUSED";
@@ -44019,65 +44047,6 @@ StakeAction.UNSTAKE_TRANSFER = {
44019
44047
  StakeAction.STAKE_TRANSFER = {
44020
44048
  stakeTransfer: {}
44021
44049
  };
44022
- class SettlePnlMode {
44023
- }
44024
- SettlePnlMode.TRY_SETTLE = {
44025
- trySettle: {}
44026
- };
44027
- SettlePnlMode.MUST_SETTLE = {
44028
- mustSettle: {}
44029
- };
44030
- function isVariant(object, type) {
44031
- return object.hasOwnProperty(type);
44032
- }
44033
- function isOneOfVariant(object, types) {
44034
- return types.reduce((result, type)=>{
44035
- return result || object.hasOwnProperty(type);
44036
- }, false);
44037
- }
44038
- function getVariant(object) {
44039
- return Object.keys(object)[0];
44040
- }
44041
- var TradeSide = /*#__PURE__*/ function(TradeSide) {
44042
- TradeSide[TradeSide["None"] = 0] = "None";
44043
- TradeSide[TradeSide["Buy"] = 1] = "Buy";
44044
- TradeSide[TradeSide["Sell"] = 2] = "Sell";
44045
- return TradeSide;
44046
- }({});
44047
- class LPAction {
44048
- }
44049
- LPAction.ADD_LIQUIDITY = {
44050
- addLiquidity: {}
44051
- };
44052
- LPAction.REMOVE_LIQUIDITY = {
44053
- removeLiquidity: {}
44054
- };
44055
- LPAction.SETTLE_LIQUIDITY = {
44056
- settleLiquidity: {}
44057
- };
44058
- LPAction.REMOVE_LIQUIDITY_DERISK = {
44059
- removeLiquidityDerisk: {}
44060
- };
44061
- class LiquidationType {
44062
- }
44063
- LiquidationType.LIQUIDATE_PERP = {
44064
- liquidatePerp: {}
44065
- };
44066
- LiquidationType.LIQUIDATE_BORROW_FOR_PERP_PNL = {
44067
- liquidateBorrowForPerpPnl: {}
44068
- };
44069
- LiquidationType.LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
44070
- liquidatePerpPnlForDeposit: {}
44071
- };
44072
- LiquidationType.PERP_BANKRUPTCY = {
44073
- perpBankruptcy: {}
44074
- };
44075
- LiquidationType.SPOT_BANKRUPTCY = {
44076
- spotBankruptcy: {}
44077
- };
44078
- LiquidationType.LIQUIDATE_SPOT = {
44079
- liquidateSpot: {}
44080
- };
44081
44050
  class PostOnlyParams {
44082
44051
  }
44083
44052
  PostOnlyParams.NONE = {
@@ -44116,28 +44085,6 @@ const DefaultOrderParams = {
44116
44085
  auctionStartPrice: null,
44117
44086
  auctionEndPrice: null
44118
44087
  };
44119
- var ReferrerStatus = /*#__PURE__*/ function(ReferrerStatus) {
44120
- ReferrerStatus[ReferrerStatus["IsReferrer"] = 1] = "IsReferrer";
44121
- ReferrerStatus[ReferrerStatus["IsReferred"] = 2] = "IsReferred";
44122
- return ReferrerStatus;
44123
- }({});
44124
- var FuelOverflowStatus = /*#__PURE__*/ function(FuelOverflowStatus) {
44125
- FuelOverflowStatus[FuelOverflowStatus["Exists"] = 1] = "Exists";
44126
- return FuelOverflowStatus;
44127
- }({});
44128
- var PlaceAndTakeOrderSuccessCondition = /*#__PURE__*/ function(PlaceAndTakeOrderSuccessCondition) {
44129
- PlaceAndTakeOrderSuccessCondition[PlaceAndTakeOrderSuccessCondition["PartialFill"] = 1] = "PartialFill";
44130
- PlaceAndTakeOrderSuccessCondition[PlaceAndTakeOrderSuccessCondition["FullFill"] = 2] = "FullFill";
44131
- return PlaceAndTakeOrderSuccessCondition;
44132
- }({});
44133
- class SwapReduceOnly {
44134
- }
44135
- SwapReduceOnly.In = {
44136
- in: {}
44137
- };
44138
- SwapReduceOnly.Out = {
44139
- out: {}
44140
- };
44141
44088
 
44142
44089
  function getLimitOrderParams(params) {
44143
44090
  return getOrderParams(Object.assign({}, params, {
@@ -44174,19 +44121,6 @@ function getMarketOrderParams(params) {
44174
44121
  return Object.assign({}, DefaultOrderParams, optionalOrderParams, overridingParams);
44175
44122
  }
44176
44123
 
44177
- function readUnsignedBigInt64LE(buffer, offset) {
44178
- return new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
44179
- }
44180
- function readSignedBigInt64LE(buffer, offset) {
44181
- const unsignedValue = new anchor.BN(buffer.subarray(offset, offset + 8), 10, "le");
44182
- if (unsignedValue.testn(63)) {
44183
- const inverted = unsignedValue.notn(64).addn(1);
44184
- return inverted.neg();
44185
- } else {
44186
- return unsignedValue;
44187
- }
44188
- }
44189
-
44190
44124
  const FractionDecimal = Decimal.clone({
44191
44125
  precision: 40
44192
44126
  });
@@ -44564,6 +44498,18 @@ class StateAccountType {
44564
44498
  static equals(a, b) {
44565
44499
  return Object.keys(a)[0] === Object.keys(b)[0];
44566
44500
  }
44501
+ static from(s) {
44502
+ if (s === "vault") {
44503
+ return StateAccountType.VAULT;
44504
+ }
44505
+ if (s === "tokenizedVault") {
44506
+ return StateAccountType.TOKENIZED_VAULT;
44507
+ }
44508
+ if (s === "mint") {
44509
+ return StateAccountType.MINT;
44510
+ }
44511
+ throw new Error(`Invalid state account type: ${s}`);
44512
+ }
44567
44513
  }
44568
44514
  StateAccountType.VAULT = {
44569
44515
  vault: {}
@@ -45097,10 +45043,11 @@ class BaseClient {
45097
45043
  });
45098
45044
  anchor__namespace.setProvider(this.provider);
45099
45045
  }
45100
- this.cluster = config?.cluster || exports.ClusterNetwork.fromUrl(this.provider.connection.rpcEndpoint);
45101
45046
  if (config?.statePda) {
45102
45047
  this.statePda = config.statePda;
45103
45048
  }
45049
+ this.cluster = config?.cluster || exports.ClusterNetwork.fromUrl(this.provider.connection.rpcEndpoint);
45050
+ this.jupiterApiKey = config?.jupiterApiKey;
45104
45051
  this.blockhashWithCache = new BlockhashWithCache(this.provider);
45105
45052
  }
45106
45053
  }
@@ -45124,9 +45071,6 @@ class BaseClient {
45124
45071
  }
45125
45072
  }
45126
45073
 
45127
- const DRIFT_SIGNER = new web3_js.PublicKey("JCNCMFXo5M5qwUPg2Utu1u6YWp3MbygxqBsBeXXJfrw");
45128
- const DRIFT_MARGIN_PRECISION = 10000;
45129
-
45130
45074
  /**
45131
45075
  * Base class for decodable on-chain account structures.
45132
45076
  *
@@ -45148,16 +45092,97 @@ const DRIFT_MARGIN_PRECISION = 10000;
45148
45092
  }
45149
45093
  }
45150
45094
 
45151
- function readI128LE(buffer, offset) {
45152
- const lo = buffer.readBigUInt64LE(offset);
45153
- const hi = buffer.readBigUInt64LE(offset + 8);
45154
- let v = (hi << 64n) + lo;
45155
- if ((hi & 1n << 63n) !== 0n) {
45156
- v -= 1n << 128n;
45095
+ class SpotPosition {
45096
+ get marketPda() {
45097
+ return web3_js.PublicKey.findProgramAddressSync([
45098
+ Buffer.from("spot_market"),
45099
+ new anchor.BN(this.marketIndex).toArrayLike(Buffer, "le", 2)
45100
+ ], DRIFT_PROGRAM_ID)[0];
45101
+ }
45102
+ calcBalance(decimals, cumulativeDepositInterest, cumulativeBorrowInterest) {
45103
+ const precisionAdjustment = new anchor.BN(10 ** (19 - decimals));
45104
+ const balance = this.scaledBalance.mul(this._interest(cumulativeDepositInterest, cumulativeBorrowInterest)).div(precisionAdjustment);
45105
+ const amount = this.balanceType === SpotBalanceType.BORROW ? balance.neg().toNumber() : balance.toNumber();
45106
+ const uiAmount = amount / 10 ** decimals;
45107
+ return {
45108
+ amount,
45109
+ uiAmount
45110
+ };
45111
+ }
45112
+ calcBalanceBn(decimals, cumulativeDepositInterest, cumulativeBorrowInterest) {
45113
+ const precisionAdjustment = new anchor.BN(10 ** (19 - decimals));
45114
+ const sign = this.balanceType === SpotBalanceType.BORROW ? new anchor.BN(-1) : new anchor.BN(1);
45115
+ return this.scaledBalance.mul(this._interest(cumulativeDepositInterest, cumulativeBorrowInterest)).div(precisionAdjustment).mul(sign);
45116
+ }
45117
+ _interest(cumulativeDepositInterest, cumulativeBorrowInterest) {
45118
+ return this.balanceType === SpotBalanceType.BORROW ? cumulativeBorrowInterest : cumulativeDepositInterest;
45119
+ }
45120
+ get direction() {
45121
+ return this.balanceType === SpotBalanceType.BORROW ? "borrow" : "deposit";
45122
+ }
45123
+ constructor(data){
45124
+ this.marketIndex = data?.marketIndex;
45125
+ this.balanceType = data?.balanceType;
45126
+ this.scaledBalance = data?.scaledBalance;
45127
+ this.openOrders = data?.openOrders;
45128
+ this.openBids = data?.openBids;
45129
+ this.openAsks = data?.openAsks;
45130
+ this.cumulativeDeposits = data?.cumulativeDeposits;
45131
+ }
45132
+ }
45133
+ class PerpPosition {
45134
+ get marketPda() {
45135
+ return web3_js.PublicKey.findProgramAddressSync([
45136
+ Buffer.from("perp_market"),
45137
+ new anchor.BN(this.marketIndex).toArrayLike(Buffer, "le", 2)
45138
+ ], DRIFT_PROGRAM_ID)[0];
45139
+ }
45140
+ baseAssetValue(oraclePrice) {
45141
+ return this.baseAssetAmount.mul(oraclePrice).div(new anchor.BN(1000000000));
45142
+ }
45143
+ unrealizedPnl(oraclePrice) {
45144
+ return this.baseAssetValue(oraclePrice).add(this.quoteAssetAmount);
45145
+ }
45146
+ getUsdValueScaled(oraclePrice, cumulativeFundingRateLong, cumulativeFundingRateShort) {
45147
+ const unrealizedPnl = this.unrealizedPnl(oraclePrice);
45148
+ const fundingPayment = this.calcFundingPayment(cumulativeFundingRateLong, cumulativeFundingRateShort);
45149
+ return unrealizedPnl.add(fundingPayment);
45150
+ }
45151
+ calcFundingPayment(cumulativeFundingRateLong, cumulativeFundingRateShort) {
45152
+ const fundingRate = this.baseAssetAmount.isNeg() ? cumulativeFundingRateShort : cumulativeFundingRateLong;
45153
+ const fundingRateDelta = fundingRate.sub(this.lastCumulativeFundingRate);
45154
+ if (fundingRateDelta.eq(new anchor.BN(0))) {
45155
+ return new anchor.BN(0);
45156
+ }
45157
+ const fundingRateDeltaSign = fundingRateDelta.isNeg() ? -1 : 1;
45158
+ const usdPricePrecision = new anchor.BN(1000000);
45159
+ const fundingRatePaymentMagnitude = fundingRateDelta.abs().mul(this.baseAssetAmount.abs()).div(usdPricePrecision).div(new anchor.BN(1000));
45160
+ const fundingRatePaymentSign = this.baseAssetAmount.isNeg() ? 1 : -1;
45161
+ const sign = fundingRatePaymentSign * fundingRateDeltaSign;
45162
+ return sign < 0 ? fundingRatePaymentMagnitude.neg() : fundingRatePaymentMagnitude;
45163
+ }
45164
+ constructor(data){
45165
+ this.baseAssetAmount = data?.baseAssetAmount;
45166
+ this.lastCumulativeFundingRate = data?.lastCumulativeFundingRate;
45167
+ this.marketIndex = data?.marketIndex;
45168
+ this.quoteAssetAmount = data?.quoteAssetAmount;
45169
+ this.quoteEntryAmount = data?.quoteEntryAmount;
45170
+ this.quoteBreakEvenAmount = data?.quoteBreakEvenAmount;
45171
+ this.openOrders = data?.openOrders;
45172
+ this.openBids = data?.openBids;
45173
+ this.openAsks = data?.openAsks;
45174
+ this.settledPnl = data?.settledPnl;
45175
+ this.lpShares = data?.lpShares;
45176
+ this.remainderBaseAssetAmount = data?.remainderBaseAssetAmount;
45177
+ this.lastBaseAssetAmountPerLp = data?.lastBaseAssetAmountPerLp;
45178
+ this.lastQuoteAssetAmountPerLp = data?.lastQuoteAssetAmountPerLp;
45179
+ this.perLpBase = data?.perLpBase;
45157
45180
  }
45158
- return new anchor.BN(v.toString());
45159
45181
  }
45160
45182
  class DriftVaultDepositor extends Decodable {
45183
+ get netShares() {
45184
+ return this.vaultShares.sub(this.lastWithdrawRequest.shares);
45185
+ }
45161
45186
  }
45162
45187
  DriftVaultDepositor._layout = borsh.struct([
45163
45188
  borsh.array(borsh.u8(), 8, "discriminator"),
@@ -45195,21 +45220,15 @@ class DriftVault extends Decodable {
45195
45220
  }
45196
45221
  aum(spotPositions, perpPositions, spotMarketsMap, perpMarketsMap) {
45197
45222
  const positionBalances = [];
45198
- for (const { marketIndex, scaledBalance, balanceType } of spotPositions){
45199
- const marketPda = this.marketPda(MarketType.SPOT, marketIndex);
45200
- const spotMarket = spotMarketsMap.get(marketPda);
45201
- const amount = spotMarket.calcSpotBalanceBn(scaledBalance, balanceType);
45202
- const balance = amount.mul(spotMarket.lastOraclePrice).div(new anchor.BN(10 ** spotMarket.decimals));
45223
+ for (const spotPosition of spotPositions){
45224
+ const { decimals, lastOraclePrice, cumulativeDepositInterest, cumulativeBorrowInterest } = spotMarketsMap.get(spotPosition.marketPda);
45225
+ const amount = spotPosition.calcBalanceBn(decimals, cumulativeDepositInterest, cumulativeBorrowInterest);
45226
+ const balance = amount.mul(lastOraclePrice).div(new anchor.BN(10 ** decimals));
45203
45227
  positionBalances.push(balance);
45204
45228
  }
45205
45229
  for (const perpPosition of perpPositions){
45206
- const { baseAssetAmount, quoteAssetAmount, marketIndex } = perpPosition;
45207
- const marketPda = this.marketPda(MarketType.PERP, marketIndex);
45208
- const perpMarket = perpMarketsMap.get(marketPda);
45209
- const baseAssetValue = baseAssetAmount.mul(perpMarket.lastOraclePrice).div(new anchor.BN(1000000000));
45210
- const unrealizedPnl = baseAssetValue.add(quoteAssetAmount);
45211
- const fundingPayment = perpMarket.calcFundingPayment(perpPosition);
45212
- positionBalances.push(unrealizedPnl.add(fundingPayment));
45230
+ const { lastOraclePrice, cumulativeFundingRateLong, cumulativeFundingRateShort } = perpMarketsMap.get(perpPosition.marketPda);
45231
+ positionBalances.push(perpPosition.getUsdValueScaled(lastOraclePrice, cumulativeFundingRateLong, cumulativeFundingRateShort));
45213
45232
  }
45214
45233
  return positionBalances.reduce((a, b)=>a.add(b), new anchor.BN(0));
45215
45234
  }
@@ -45323,15 +45342,15 @@ class DriftUser {
45323
45342
  balanceType = SpotBalanceType.BORROW;
45324
45343
  }
45325
45344
  offset += 6;
45326
- spotPositions.push({
45345
+ spotPositions.push(new SpotPosition({
45346
+ marketIndex,
45347
+ balanceType,
45327
45348
  scaledBalance,
45349
+ openOrders,
45328
45350
  openBids,
45329
45351
  openAsks,
45330
- cumulativeDeposits,
45331
- marketIndex,
45332
- balanceType,
45333
- openOrders
45334
- });
45352
+ cumulativeDeposits
45353
+ }));
45335
45354
  }
45336
45355
  const perpPositions = [];
45337
45356
  for(let i = 0; i < 8; i++){
@@ -45365,23 +45384,23 @@ class DriftUser {
45365
45384
  offset += 3;
45366
45385
  const perLpBase = buffer.readUInt8(offset);
45367
45386
  offset += 1;
45368
- perpPositions.push({
45369
- lastCumulativeFundingRate,
45387
+ perpPositions.push(new PerpPosition({
45370
45388
  baseAssetAmount,
45389
+ lastCumulativeFundingRate,
45390
+ marketIndex,
45371
45391
  quoteAssetAmount,
45372
- quoteBreakEvenAmount,
45373
45392
  quoteEntryAmount,
45393
+ quoteBreakEvenAmount,
45394
+ openOrders,
45374
45395
  openBids,
45375
45396
  openAsks,
45376
45397
  settledPnl,
45377
45398
  lpShares,
45399
+ remainderBaseAssetAmount,
45378
45400
  lastBaseAssetAmountPerLp,
45379
45401
  lastQuoteAssetAmountPerLp,
45380
- remainderBaseAssetAmount,
45381
- marketIndex,
45382
- openOrders,
45383
45402
  perLpBase
45384
- });
45403
+ }));
45385
45404
  }
45386
45405
  const orders = [];
45387
45406
  for(let i = 0; i < 32; i++){
@@ -45628,24 +45647,6 @@ class DriftSpotMarket extends Decodable {
45628
45647
  get tokenProgramId() {
45629
45648
  return this.tokenProgram === 0 ? splToken.TOKEN_PROGRAM_ID : splToken.TOKEN_2022_PROGRAM_ID;
45630
45649
  }
45631
- calcSpotBalance(scaledBalance, scaledBalanceType) {
45632
- const precisionAdjustment = new anchor.BN(10 ** (19 - this.decimals));
45633
- const balance = scaledBalance.mul(this._interest(scaledBalanceType)).div(precisionAdjustment);
45634
- const amount = scaledBalanceType === SpotBalanceType.BORROW ? balance.neg().toNumber() : balance.toNumber();
45635
- const uiAmount = amount / 10 ** this.decimals;
45636
- return {
45637
- amount,
45638
- uiAmount
45639
- };
45640
- }
45641
- calcSpotBalanceBn(scaledBalance, scaledBalanceType) {
45642
- const precisionAdjustment = new anchor.BN(10 ** (19 - this.decimals));
45643
- const sign = scaledBalanceType === SpotBalanceType.BORROW ? new anchor.BN(-1) : new anchor.BN(1);
45644
- return scaledBalance.mul(this._interest(scaledBalanceType)).div(precisionAdjustment).mul(sign);
45645
- }
45646
- _interest(balanceType) {
45647
- return balanceType === SpotBalanceType.BORROW ? this.cumulativeBorrowInterest : this.cumulativeDepositInterest;
45648
- }
45649
45650
  }
45650
45651
  DriftSpotMarket._layout = borsh.struct([
45651
45652
  borsh.array(borsh.u8(), 8, "discriminator"),
@@ -45685,19 +45686,6 @@ class DriftPerpMarket extends Decodable {
45685
45686
  get oracleSource() {
45686
45687
  return OracleSource.get(this.oracleSourceOrd);
45687
45688
  }
45688
- calcFundingPayment(perpPosition) {
45689
- const fundingRate = perpPosition.baseAssetAmount.isNeg() ? this.cumulativeFundingRateShort : this.cumulativeFundingRateLong;
45690
- const fundingRateDelta = fundingRate.sub(perpPosition.lastCumulativeFundingRate);
45691
- if (fundingRateDelta.eq(new anchor.BN(0))) {
45692
- return new anchor.BN(0);
45693
- }
45694
- const fundingRateDeltaSign = fundingRateDelta.isNeg() ? -1 : 1;
45695
- const usdPricePrecision = new anchor.BN(1000000);
45696
- const fundingRatePaymentMagnitude = fundingRateDelta.abs().mul(perpPosition.baseAssetAmount.abs()).div(usdPricePrecision).div(new anchor.BN(1000));
45697
- const fundingRatePaymentSign = perpPosition.baseAssetAmount.isNeg() ? 1 : -1;
45698
- const sign = fundingRatePaymentSign * fundingRateDeltaSign;
45699
- return sign < 0 ? fundingRatePaymentMagnitude.neg() : fundingRatePaymentMagnitude;
45700
- }
45701
45689
  }
45702
45690
  DriftPerpMarket._layout = borsh.struct([
45703
45691
  borsh.array(borsh.u8(), 8, "discriminator"),
@@ -45714,6 +45702,8 @@ DriftPerpMarket._layout = borsh.struct([
45714
45702
  borsh.u16("quoteSpotMarketIndex")
45715
45703
  ]);
45716
45704
 
45705
+ const DRIFT_SIGNER = new web3_js.PublicKey("JCNCMFXo5M5qwUPg2Utu1u6YWp3MbygxqBsBeXXJfrw");
45706
+ const DRIFT_MARGIN_PRECISION = 10000;
45717
45707
  let TxBuilder$g = class TxBuilder extends BaseTxBuilder {
45718
45708
  async initializeUserStatsIx(glamSigner) {
45719
45709
  const { userStats } = this.client.getDriftUserPdas();
@@ -46181,7 +46171,7 @@ class DriftProtocolClient {
46181
46171
  }
46182
46172
  const perpMarkets = marketIndexes.map((marketIndex)=>this.perpMarkets.get(marketIndex)).filter((m)=>m !== undefined);
46183
46173
  const invalidIndexes = marketIndexes.filter((marketIndex)=>!this.perpMarkets.has(marketIndex));
46184
- if (invalidIndexes.length > 0) {
46174
+ if (invalidIndexes.length > 0 && process.env.NODE_ENV === "development") {
46185
46175
  console.warn(`The following perp markets could not be found: ${invalidIndexes.join(", ")}`);
46186
46176
  }
46187
46177
  return perpMarkets;
@@ -47074,7 +47064,9 @@ class JupiterSwapClient {
47074
47064
  this.base = base;
47075
47065
  this.vault = vault;
47076
47066
  this.txBuilder = new TxBuilder$e(this);
47077
- this.jupApi = new JupiterApiClient();
47067
+ this.jupApi = new JupiterApiClient({
47068
+ apiKey: this.base.jupiterApiKey
47069
+ });
47078
47070
  }
47079
47071
  }
47080
47072
 
@@ -49545,6 +49537,7 @@ class PriceClient {
49545
49537
  const { integrationAcls, externalPositions } = await this.base.fetchStateAccount(); // fetch state account only, don't need to build entire state model
49546
49538
  const externalPositionsSet = new PkSet(externalPositions);
49547
49539
  let glamDriftUserSpotMarketsMap = new PkMap(); // glam-controlled drift user -> spot markets map
49540
+ let glamDriftUserPerpMarketsMap = new PkMap(); // glam-controlled drift user -> perp markets map
49548
49541
  let dvaultDepositorsAndVaults = new PkMap(); // dvault depositor -> drift vault map
49549
49542
  let dvaultUserSpotMarketsMap = new PkMap(); // dvault drift user -> spot markets map
49550
49543
  let dvaultUserPerpMarketsMap = new PkMap(); // dvault drift user -> perp markets map
@@ -49560,6 +49553,7 @@ class PriceClient {
49560
49553
  return user;
49561
49554
  });
49562
49555
  glamDriftUserSpotMarketsMap = await this.getPubkeysForSpotHoldings(userPdas, commitment);
49556
+ glamDriftUserPerpMarketsMap = await this.getPubkeysForPerpHoldings(userPdas, commitment);
49563
49557
  }
49564
49558
  if (driftIntegrationAcl.protocolsBitmask & 0b10) {
49565
49559
  // 1. find all depositors
@@ -49596,6 +49590,9 @@ class PriceClient {
49596
49590
  const glamDriftSpotMarkets = [
49597
49591
  ...glamDriftUserSpotMarketsMap.values()
49598
49592
  ].map((s)=>Array.from(s.pkValues())).flat();
49593
+ const glamDriftPerpMarkets = [
49594
+ ...glamDriftUserPerpMarketsMap.values()
49595
+ ].map((s)=>Array.from(s.pkValues())).flat();
49599
49596
  const dvaultDepositors = Array.from(dvaultDepositorsAndVaults.pkKeys());
49600
49597
  const dvaultUsers = [
49601
49598
  ...dvaultDepositorsAndVaults.values()
@@ -49616,6 +49613,7 @@ class PriceClient {
49616
49613
  ...tokenPubkeys,
49617
49614
  ...glamDriftUsers,
49618
49615
  ...glamDriftSpotMarkets,
49616
+ ...glamDriftPerpMarkets,
49619
49617
  ...dvaultDepositors,
49620
49618
  ...dvaultUsers,
49621
49619
  ...dvaultUserSpotMarkets,
@@ -49655,6 +49653,13 @@ class PriceClient {
49655
49653
  }
49656
49654
  // Build a map of parsed drift perp markets
49657
49655
  const driftPerpMarketsMap = new PkMap();
49656
+ for (const marketPda of glamDriftPerpMarkets){
49657
+ const data = accountsDataMap.get(marketPda);
49658
+ if (data) {
49659
+ const market = DriftPerpMarket.decode(marketPda, data);
49660
+ driftPerpMarketsMap.set(marketPda, market);
49661
+ }
49662
+ }
49658
49663
  for (const marketPda of dvaultUserPerpMarkets){
49659
49664
  const data = accountsDataMap.get(marketPda);
49660
49665
  if (data) {
@@ -49688,7 +49693,7 @@ class PriceClient {
49688
49693
  tokenPricesMap.set(tokenMint, item);
49689
49694
  });
49690
49695
  const tokenHoldings = this.getTokenHoldings(tokenPubkeys, accountsDataMap, tokenPricesMap, "Jupiter");
49691
- const driftSpotHoldings = this.getDriftSpotHoldings(glamDriftUserSpotMarketsMap.pkKeys(), driftSpotMarketsMap, accountsDataMap, tokenPricesMap, "Jupiter");
49696
+ const driftSpotHoldings = this.getDriftHoldings(glamDriftUserSpotMarketsMap.pkKeys(), driftSpotMarketsMap, driftPerpMarketsMap, accountsDataMap, tokenPricesMap, "Jupiter");
49692
49697
  const dvaultHoldings = this.getDriftVaultsHoldings(dvaultDepositorsAndVaults, dvaultDepositorsMap, driftSpotMarketsMap, driftPerpMarketsMap, accountsDataMap, tokenPricesMap, "Jupiter");
49693
49698
  const kaminoLendHoldings = this.getKaminoLendHoldings(kaminoPubkeys.pkKeys(), kaminoReservesMap, accountsDataMap, tokenPricesMap, "Jupiter");
49694
49699
  const kaminoVaultsHoldings = this.getKaminoVaultsHoldings(kvaultAtasAndStates, kaminoReservesMap, accountsDataMap, tokenPricesMap, "Jupiter");
@@ -49824,28 +49829,39 @@ class PriceClient {
49824
49829
  }
49825
49830
  return holdings;
49826
49831
  }
49827
- getDriftSpotHoldings(userPubkeys, spotMarketsMap, accountsDataMap, tokenPricesMap, priceSource) {
49832
+ getDriftHoldings(userPubkeys, spotMarketsMap, perpMarketsMap, accountsDataMap, tokenPricesMap, priceSource) {
49828
49833
  const holdings = [];
49829
49834
  for (const userPda of userPubkeys){
49830
49835
  const userData = accountsDataMap.get(userPda);
49831
- if (!userData) continue;
49832
- const { spotPositions } = DriftUser.decode(userPda, userData);
49833
- for (const { marketIndex, scaledBalance, balanceType } of spotPositions){
49834
- const marketPda = this.drift.getMarketPda(MarketType.SPOT, marketIndex);
49835
- const spotMarket = spotMarketsMap.get(marketPda);
49836
- if (!spotMarket) continue;
49837
- const amount = spotMarket.calcSpotBalanceBn(scaledBalance, balanceType).abs();
49838
- const direction = Object.keys(balanceType)[0];
49839
- const tokenPrice = tokenPricesMap.get(spotMarket.mint);
49840
- if (!tokenPrice) continue;
49836
+ const { spotPositions, perpPositions } = DriftUser.decode(userPda, userData);
49837
+ for (const spotPosition of spotPositions){
49838
+ const { marketIndex, mint, decimals, cumulativeDepositInterest, cumulativeBorrowInterest } = spotMarketsMap.get(spotPosition.marketPda);
49839
+ const amount = spotPosition.calcBalanceBn(decimals, cumulativeDepositInterest, cumulativeBorrowInterest).abs();
49840
+ const { usdPrice, slot } = tokenPricesMap.get(mint);
49841
+ const holding = new Holding(mint, decimals, amount, usdPrice, {
49842
+ slot,
49843
+ source: priceSource
49844
+ }, "DriftProtocol", {
49845
+ user: userPda,
49846
+ marketIndex,
49847
+ direction: spotPosition.direction,
49848
+ marketType: "spot"
49849
+ });
49850
+ holdings.push(holding);
49851
+ }
49852
+ for (const perpPosition of perpPositions){
49853
+ const { marketIndex, marketPda } = perpPosition;
49854
+ const { lastOraclePrice, cumulativeFundingRateLong, cumulativeFundingRateShort } = perpMarketsMap.get(marketPda);
49855
+ const amount = perpPosition.getUsdValueScaled(lastOraclePrice, cumulativeFundingRateLong, cumulativeFundingRateShort);
49856
+ const tokenPrice = tokenPricesMap.get(USDC);
49841
49857
  const { usdPrice, slot } = tokenPrice;
49842
- const holding = new Holding(spotMarket.mint, spotMarket.decimals, amount, usdPrice, {
49858
+ const holding = new Holding(USDC, 6, amount, usdPrice, {
49843
49859
  slot,
49844
49860
  source: priceSource
49845
49861
  }, "DriftProtocol", {
49846
49862
  user: userPda,
49847
49863
  marketIndex,
49848
- direction
49864
+ marketType: "perp"
49849
49865
  });
49850
49866
  holdings.push(holding);
49851
49867
  }
@@ -49859,7 +49875,7 @@ class PriceClient {
49859
49875
  const dvaultUserData = accountsDataMap.get(dvault.user);
49860
49876
  const { spotPositions, perpPositions } = DriftUser.decode(dvault.user, dvaultUserData);
49861
49877
  const aum = dvault.aumInBaseAsset(spotPositions, perpPositions, spotMarketsMap, perpMarketsMap);
49862
- const amount = depositor.vaultShares.mul(aum).div(dvault.totalShares);
49878
+ const amount = depositor.netShares.mul(aum).div(dvault.totalShares).add(depositor.lastWithdrawRequest.value);
49863
49879
  const { mint, decimals } = dvault.getBaseAsset(spotMarketsMap);
49864
49880
  const tokenPrice = tokenPricesMap.get(mint);
49865
49881
  if (!tokenPrice) continue;
@@ -51527,6 +51543,7 @@ const MESSAGE_RECEIVED_EVENT_DISCM = new Uint8Array([
51527
51543
  0x9d,
51528
51544
  0xa6
51529
51545
  ]);
51546
+ const CCTP_DOMAIN_SOLANA = 5;
51530
51547
  class CctpBridgeEvent {
51531
51548
  constructor(amount, sourceDomain, sourceAddress, destinationDomain, destinationAddress, attestation, nonce, status, txHash){
51532
51549
  this.amount = amount;
@@ -51878,9 +51895,6 @@ class CctpClient {
51878
51895
  ...options.commitment ? {
51879
51896
  commitment: options.commitment
51880
51897
  } : {},
51881
- ...options.minSlot ? {
51882
- minContextSlot: options.minSlot
51883
- } : {},
51884
51898
  filters: [
51885
51899
  {
51886
51900
  dataSize: 428
@@ -51952,16 +51966,16 @@ class CctpClient {
51952
51966
  * 2. Filter transactions that contain the bridge events
51953
51967
  * 3. Parse the bridge events from the transactions
51954
51968
  */ async getIncomingBridgeEvents(options) {
51955
- const { batchSize = 1, commitment = "confirmed", minSlot } = options;
51969
+ const { batchSize = 1, commitment = "confirmed", minSlot = 0 } = options;
51956
51970
  const txHashes = new Set(options.txHashes ?? []);
51971
+ const txSlots = new Map();
51957
51972
  // If no txHashes provided, find transactions involving vault's USDC token account
51958
51973
  if (txHashes.size === 0) {
51959
- const signatures = await this.base.connection.getSignaturesForAddress(this.base.getVaultAta(USDC), {
51960
- ...minSlot ? {
51961
- minContextSlot: minSlot
51962
- } : {}
51963
- }, commitment);
51964
- signatures.forEach((sig)=>txHashes.add(sig.signature));
51974
+ const signatures = await this.base.connection.getSignaturesForAddress(this.base.getVaultAta(USDC), {}, commitment);
51975
+ signatures.filter((s)=>s.slot >= minSlot).forEach((sig)=>{
51976
+ txHashes.add(sig.signature);
51977
+ txSlots.set(sig.signature, sig.slot);
51978
+ });
51965
51979
  }
51966
51980
  if (txHashes.size === 0) {
51967
51981
  return [];
@@ -52009,6 +52023,9 @@ class CctpClient {
52009
52023
  nonce,
52010
52024
  txHash
52011
52025
  });
52026
+ for (const event of events){
52027
+ event.slot = txSlots.get(txHash);
52028
+ }
52012
52029
  allEvents.push(...events);
52013
52030
  }
52014
52031
  }
@@ -52023,34 +52040,42 @@ class CctpClient {
52023
52040
  * 2. Get the created transaction for each message account
52024
52041
  * 3. Call iris api to get the attestation status and parsed message using each tx hash
52025
52042
  */ async getOutgoingBridgeEvents(options) {
52026
- const { batchSize = 1, commitment = "confirmed", minSlot } = options;
52043
+ const { batchSize = 1, commitment = "confirmed", minSlot = 0 } = options;
52027
52044
  const txHashes = new Set(options.txHashes ?? []);
52045
+ const txSlots = new Map();
52028
52046
  // If no txHashes are provided, find all message accounts for the vault
52029
52047
  if (txHashes.size === 0) {
52030
52048
  const messagePubkeys = await this.findV2Messages(this.base.vaultPda, {
52031
- commitment,
52032
- minSlot
52049
+ commitment
52033
52050
  });
52034
52051
  if (messagePubkeys.length === 0) {
52035
52052
  return [];
52036
52053
  }
52054
+ // Get account creation transaction for each message account
52037
52055
  for(let i = 0; i < messagePubkeys.length; i += batchSize){
52038
52056
  const batch = messagePubkeys.slice(i, i + batchSize);
52039
52057
  const signaturesPromises = batch.map((pubkey)=>this.base.connection.getSignaturesForAddress(pubkey));
52040
52058
  const batchSignatures = await Promise.all(signaturesPromises);
52041
52059
  // Process batch results and collect transaction signatures
52042
52060
  for(let j = 0; j < batch.length; j++){
52043
- const sigs = batchSignatures[j];
52061
+ const sigs = batchSignatures[j].filter((s)=>s.slot >= minSlot);
52062
+ if (sigs.length === 0) {
52063
+ continue;
52064
+ }
52044
52065
  const createdTx = sigs.sort((a, b)=>a.slot - b.slot)[0];
52045
52066
  txHashes.add(createdTx.signature);
52067
+ txSlots.set(createdTx.signature, createdTx.slot);
52046
52068
  }
52047
52069
  }
52048
52070
  }
52049
52071
  const allEvents = [];
52050
52072
  for (const txHash of txHashes){
52051
- const events = await this.parseEventsFromAttestion(5, {
52073
+ const events = await this.parseEventsFromAttestion(CCTP_DOMAIN_SOLANA, {
52052
52074
  txHash
52053
52075
  });
52076
+ for (const event of events){
52077
+ event.slot = txSlots.get(txHash);
52078
+ }
52054
52079
  allEvents.push(...events);
52055
52080
  }
52056
52081
  return allEvents;
@@ -52211,7 +52236,6 @@ exports.EmergencyAccessUpdateArgs = EmergencyAccessUpdateArgs;
52211
52236
  exports.EmergencyUpdateMintArgs = EmergencyUpdateMintArgs;
52212
52237
  exports.ExchangeStatus = ExchangeStatus;
52213
52238
  exports.Fraction = Fraction;
52214
- exports.FuelOverflowStatus = FuelOverflowStatus;
52215
52239
  exports.GLAM_CONFIG_PROGRAM = GLAM_CONFIG_PROGRAM;
52216
52240
  exports.GLAM_REFERRER = GLAM_REFERRER;
52217
52241
  exports.GlamClient = GlamClient;
@@ -52234,8 +52258,6 @@ exports.KAMINO_VAULTS_PROGRAM = KAMINO_VAULTS_PROGRAM;
52234
52258
  exports.KAMINO_VAULT_STATE_SIZE = KAMINO_VAULT_STATE_SIZE;
52235
52259
  exports.KaminoLendingPolicy = KaminoLendingPolicy;
52236
52260
  exports.KaminoVaultsPolicy = KaminoVaultsPolicy;
52237
- exports.LPAction = LPAction;
52238
- exports.LiquidationType = LiquidationType;
52239
52261
  exports.MARINADE_NATIVE_STAKE_AUTHORITY = MARINADE_NATIVE_STAKE_AUTHORITY;
52240
52262
  exports.MARINADE_PROGRAM_ID = MARINADE_PROGRAM_ID;
52241
52263
  exports.MEMO_PROGRAM = MEMO_PROGRAM;
@@ -52259,13 +52281,11 @@ exports.OrderType = OrderType;
52259
52281
  exports.PerpOperation = PerpOperation;
52260
52282
  exports.PkMap = PkMap;
52261
52283
  exports.PkSet = PkSet;
52262
- exports.PlaceAndTakeOrderSuccessCondition = PlaceAndTakeOrderSuccessCondition;
52263
52284
  exports.PositionDirection = PositionDirection;
52264
52285
  exports.PostOnlyParams = PostOnlyParams;
52265
52286
  exports.PriceDenom = PriceDenom;
52266
52287
  exports.ProtocolPermissions = ProtocolPermissions;
52267
52288
  exports.ProtocolPolicy = ProtocolPolicy;
52268
- exports.ReferrerStatus = ReferrerStatus;
52269
52289
  exports.RequestType = RequestType;
52270
52290
  exports.SANCTUM_STAKE_POOL_PROGRAM_ID = SANCTUM_STAKE_POOL_PROGRAM_ID;
52271
52291
  exports.SEED_ACCOUNT_POLICY = SEED_ACCOUNT_POLICY;
@@ -52283,7 +52303,6 @@ exports.STAKE_ACCOUNT_SIZE = STAKE_ACCOUNT_SIZE;
52283
52303
  exports.STAKE_POOLS = STAKE_POOLS;
52284
52304
  exports.STAKE_POOLS_MAP = STAKE_POOLS_MAP;
52285
52305
  exports.SettlePnlExplanation = SettlePnlExplanation;
52286
- exports.SettlePnlMode = SettlePnlMode;
52287
52306
  exports.SpotBalanceType = SpotBalanceType;
52288
52307
  exports.SpotFulfillmentConfigStatus = SpotFulfillmentConfigStatus;
52289
52308
  exports.SpotFulfillmentStatus = SpotFulfillmentStatus;
@@ -52294,12 +52313,10 @@ exports.StateAccountType = StateAccountType;
52294
52313
  exports.StateIdlModel = StateIdlModel;
52295
52314
  exports.StateModel = StateModel;
52296
52315
  exports.SwapDirection = SwapDirection;
52297
- exports.SwapReduceOnly = SwapReduceOnly;
52298
52316
  exports.TOKEN_MESSENGER_MINTER_V2 = TOKEN_MESSENGER_MINTER_V2;
52299
52317
  exports.TRANSFER_HOOK_PROGRAM = TRANSFER_HOOK_PROGRAM;
52300
52318
  exports.TimeUnit = TimeUnit;
52301
52319
  exports.TimelockClient = TimelockClient;
52302
- exports.TradeSide = TradeSide;
52303
52320
  exports.TransferPolicy = TransferPolicy;
52304
52321
  exports.USDC = USDC;
52305
52322
  exports.USDC_DEVNET = USDC_DEVNET;
@@ -52375,17 +52392,15 @@ exports.getStatePda = getStatePda;
52375
52392
  exports.getTokenAccountsByOwner = getTokenAccountsByOwner;
52376
52393
  exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
52377
52394
  exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
52378
- exports.getVariant = getVariant;
52379
52395
  exports.getVaultPda = getVaultPda;
52380
52396
  exports.hexToBytes = hexToBytes;
52381
- exports.isOneOfVariant = isOneOfVariant;
52382
- exports.isVariant = isVariant;
52383
52397
  exports.nameToChars = nameToChars;
52384
52398
  exports.parseMintAccountInfo = parseMintAccountInfo;
52385
52399
  exports.parseProgramLogs = parseProgramLogs;
52386
52400
  exports.parseProtocolPermissionsBitmask = parseProtocolPermissionsBitmask;
52387
52401
  exports.parseProtocolsBitmask = parseProtocolsBitmask;
52388
52402
  exports.publicKeyToEvmAddress = publicKeyToEvmAddress;
52403
+ exports.readI128LE = readI128LE;
52389
52404
  exports.readSignedBigInt64LE = readSignedBigInt64LE;
52390
52405
  exports.readUnsignedBigInt64LE = readUnsignedBigInt64LE;
52391
52406
  exports.setsAreEqual = setsAreEqual;