@drift-labs/sdk 2.140.0-beta.0 → 2.140.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/VERSION +1 -1
  2. package/lib/browser/addresses/pda.d.ts +2 -0
  3. package/lib/browser/addresses/pda.js +15 -1
  4. package/lib/browser/adminClient.d.ts +4 -0
  5. package/lib/browser/adminClient.js +32 -0
  6. package/lib/browser/constants/perpMarkets.js +12 -0
  7. package/lib/browser/driftClient.d.ts +19 -7
  8. package/lib/browser/driftClient.js +327 -24
  9. package/lib/browser/idl/drift.json +571 -0
  10. package/lib/browser/index.d.ts +1 -0
  11. package/lib/browser/index.js +1 -0
  12. package/lib/browser/math/builder.d.ts +5 -0
  13. package/lib/browser/math/builder.js +22 -0
  14. package/lib/browser/math/orders.d.ts +1 -0
  15. package/lib/browser/math/orders.js +6 -1
  16. package/lib/browser/math/state.d.ts +2 -0
  17. package/lib/browser/math/state.js +9 -1
  18. package/lib/browser/memcmp.d.ts +1 -0
  19. package/lib/browser/memcmp.js +10 -1
  20. package/lib/browser/types.d.ts +50 -1
  21. package/lib/browser/types.js +2 -0
  22. package/lib/browser/userMap/revenueShareEscrowMap.d.ts +66 -0
  23. package/lib/browser/userMap/revenueShareEscrowMap.js +210 -0
  24. package/lib/node/addresses/pda.d.ts +2 -0
  25. package/lib/node/addresses/pda.d.ts.map +1 -1
  26. package/lib/node/addresses/pda.js +15 -1
  27. package/lib/node/adminClient.d.ts +4 -0
  28. package/lib/node/adminClient.d.ts.map +1 -1
  29. package/lib/node/adminClient.js +32 -0
  30. package/lib/node/constants/perpMarkets.d.ts.map +1 -1
  31. package/lib/node/constants/perpMarkets.js +12 -0
  32. package/lib/node/driftClient.d.ts +19 -7
  33. package/lib/node/driftClient.d.ts.map +1 -1
  34. package/lib/node/driftClient.js +327 -24
  35. package/lib/node/idl/drift.json +571 -0
  36. package/lib/node/index.d.ts +1 -0
  37. package/lib/node/index.d.ts.map +1 -1
  38. package/lib/node/index.js +1 -0
  39. package/lib/node/math/builder.d.ts +6 -0
  40. package/lib/node/math/builder.d.ts.map +1 -0
  41. package/lib/node/math/builder.js +22 -0
  42. package/lib/node/math/orders.d.ts +1 -0
  43. package/lib/node/math/orders.d.ts.map +1 -1
  44. package/lib/node/math/orders.js +6 -1
  45. package/lib/node/math/state.d.ts +2 -0
  46. package/lib/node/math/state.d.ts.map +1 -1
  47. package/lib/node/math/state.js +9 -1
  48. package/lib/node/memcmp.d.ts +1 -0
  49. package/lib/node/memcmp.d.ts.map +1 -1
  50. package/lib/node/memcmp.js +10 -1
  51. package/lib/node/swift/swiftOrderSubscriber.d.ts.map +1 -1
  52. package/lib/node/types.d.ts +50 -1
  53. package/lib/node/types.d.ts.map +1 -1
  54. package/lib/node/types.js +2 -0
  55. package/lib/node/userMap/revenueShareEscrowMap.d.ts +67 -0
  56. package/lib/node/userMap/revenueShareEscrowMap.d.ts.map +1 -0
  57. package/lib/node/userMap/revenueShareEscrowMap.js +210 -0
  58. package/package.json +1 -1
  59. package/src/addresses/pda.ts +26 -0
  60. package/src/adminClient.ts +55 -0
  61. package/src/constants/perpMarkets.ts +13 -0
  62. package/src/driftClient.ts +530 -26
  63. package/src/idl/drift.json +571 -0
  64. package/src/index.ts +1 -0
  65. package/src/math/builder.ts +20 -0
  66. package/src/math/orders.ts +5 -0
  67. package/src/math/state.ts +8 -0
  68. package/src/memcmp.ts +11 -0
  69. package/src/swift/swiftOrderSubscriber.ts +5 -10
  70. package/src/types.ts +54 -0
  71. package/src/userMap/revenueShareEscrowMap.ts +306 -0
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.140.0-beta.0
1
+ 2.140.0-beta.2
@@ -33,3 +33,5 @@ export declare function getTokenProgramForSpotMarket(spotMarketAccount: SpotMark
33
33
  export declare function getHighLeverageModeConfigPublicKey(programId: PublicKey): PublicKey;
34
34
  export declare function getProtectedMakerModeConfigPublicKey(programId: PublicKey): PublicKey;
35
35
  export declare function getIfRebalanceConfigPublicKey(programId: PublicKey, inMarketIndex: number, outMarketIndex: number): PublicKey;
36
+ export declare function getRevenueShareAccountPublicKey(programId: PublicKey, authority: PublicKey): PublicKey;
37
+ export declare function getRevenueShareEscrowAccountPublicKey(programId: PublicKey, authority: PublicKey): PublicKey;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getIfRebalanceConfigPublicKey = exports.getProtectedMakerModeConfigPublicKey = exports.getHighLeverageModeConfigPublicKey = exports.getTokenProgramForSpotMarket = exports.getPythLazerOraclePublicKey = exports.getPythPullOraclePublicKey = exports.getPrelaunchOraclePublicKey = exports.getProtocolIfSharesTransferConfigPublicKey = exports.getReferrerNamePublicKeySync = exports.getOpenbookV2FulfillmentConfigPublicKey = exports.getPhoenixFulfillmentConfigPublicKey = exports.getSerumFulfillmentConfigPublicKey = exports.getSerumSignerPublicKey = exports.getSerumOpenOrdersPublicKey = exports.getDriftSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getSpotMarketVaultPublicKey = exports.getSpotMarketPublicKeySync = exports.getSpotMarketPublicKey = exports.getPerpMarketPublicKeySync = exports.getPerpMarketPublicKey = exports.getSignedMsgWsDelegatesAccountPublicKey = exports.getSignedMsgUserAccountPublicKey = exports.getFuelOverflowAccountPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getDriftStateAccountPublicKey = exports.getDriftStateAccountPublicKeyAndNonce = void 0;
26
+ exports.getRevenueShareEscrowAccountPublicKey = exports.getRevenueShareAccountPublicKey = exports.getIfRebalanceConfigPublicKey = exports.getProtectedMakerModeConfigPublicKey = exports.getHighLeverageModeConfigPublicKey = exports.getTokenProgramForSpotMarket = exports.getPythLazerOraclePublicKey = exports.getPythPullOraclePublicKey = exports.getPrelaunchOraclePublicKey = exports.getProtocolIfSharesTransferConfigPublicKey = exports.getReferrerNamePublicKeySync = exports.getOpenbookV2FulfillmentConfigPublicKey = exports.getPhoenixFulfillmentConfigPublicKey = exports.getSerumFulfillmentConfigPublicKey = exports.getSerumSignerPublicKey = exports.getSerumOpenOrdersPublicKey = exports.getDriftSignerPublicKey = exports.getInsuranceFundStakeAccountPublicKey = exports.getInsuranceFundVaultPublicKey = exports.getSpotMarketVaultPublicKey = exports.getSpotMarketPublicKeySync = exports.getSpotMarketPublicKey = exports.getPerpMarketPublicKeySync = exports.getPerpMarketPublicKey = exports.getSignedMsgWsDelegatesAccountPublicKey = exports.getSignedMsgUserAccountPublicKey = exports.getFuelOverflowAccountPublicKey = exports.getUserStatsAccountPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getDriftStateAccountPublicKey = exports.getDriftStateAccountPublicKeyAndNonce = void 0;
27
27
  const web3_js_1 = require("@solana/web3.js");
28
28
  const anchor = __importStar(require("@coral-xyz/anchor"));
29
29
  const anchor_1 = require("@coral-xyz/anchor");
@@ -232,3 +232,17 @@ function getIfRebalanceConfigPublicKey(programId, inMarketIndex, outMarketIndex)
232
232
  ], programId)[0];
233
233
  }
234
234
  exports.getIfRebalanceConfigPublicKey = getIfRebalanceConfigPublicKey;
235
+ function getRevenueShareAccountPublicKey(programId, authority) {
236
+ return web3_js_1.PublicKey.findProgramAddressSync([
237
+ Buffer.from(anchor.utils.bytes.utf8.encode('REV_SHARE')),
238
+ authority.toBuffer(),
239
+ ], programId)[0];
240
+ }
241
+ exports.getRevenueShareAccountPublicKey = getRevenueShareAccountPublicKey;
242
+ function getRevenueShareEscrowAccountPublicKey(programId, authority) {
243
+ return web3_js_1.PublicKey.findProgramAddressSync([
244
+ Buffer.from(anchor.utils.bytes.utf8.encode('REV_ESCROW')),
245
+ authority.toBuffer(),
246
+ ], programId)[0];
247
+ }
248
+ exports.getRevenueShareEscrowAccountPublicKey = getRevenueShareEscrowAccountPublicKey;
@@ -242,4 +242,8 @@ export declare class AdminClient extends DriftClient {
242
242
  getUpdateDelegateUserGovTokenInsuranceStakeIx(authority: PublicKey, delegate: PublicKey): Promise<TransactionInstruction>;
243
243
  depositIntoInsuranceFundStake(marketIndex: number, amount: BN, userStatsPublicKey: PublicKey, insuranceFundStakePublicKey: PublicKey, userTokenAccountPublicKey: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
244
244
  getDepositIntoInsuranceFundStakeIx(marketIndex: number, amount: BN, userStatsPublicKey: PublicKey, insuranceFundStakePublicKey: PublicKey, userTokenAccountPublicKey: PublicKey): Promise<TransactionInstruction>;
245
+ updateFeatureBitFlagsBuilderCodes(enable: boolean): Promise<TransactionSignature>;
246
+ getUpdateFeatureBitFlagsBuilderCodesIx(enable: boolean): Promise<TransactionInstruction>;
247
+ updateFeatureBitFlagsBuilderReferral(enable: boolean): Promise<TransactionSignature>;
248
+ getUpdateFeatureBitFlagsBuilderReferralIx(enable: boolean): Promise<TransactionInstruction>;
245
249
  }
@@ -2216,5 +2216,37 @@ class AdminClient extends driftClient_1.DriftClient {
2216
2216
  },
2217
2217
  });
2218
2218
  }
2219
+ async updateFeatureBitFlagsBuilderCodes(enable) {
2220
+ const updateFeatureBitFlagsBuilderCodesIx = await this.getUpdateFeatureBitFlagsBuilderCodesIx(enable);
2221
+ const tx = await this.buildTransaction(updateFeatureBitFlagsBuilderCodesIx);
2222
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
2223
+ return txSig;
2224
+ }
2225
+ async getUpdateFeatureBitFlagsBuilderCodesIx(enable) {
2226
+ return this.program.instruction.updateFeatureBitFlagsBuilderCodes(enable, {
2227
+ accounts: {
2228
+ admin: this.useHotWalletAdmin
2229
+ ? this.wallet.publicKey
2230
+ : this.getStateAccount().admin,
2231
+ state: await this.getStatePublicKey(),
2232
+ },
2233
+ });
2234
+ }
2235
+ async updateFeatureBitFlagsBuilderReferral(enable) {
2236
+ const updateFeatureBitFlagsBuilderReferralIx = await this.getUpdateFeatureBitFlagsBuilderReferralIx(enable);
2237
+ const tx = await this.buildTransaction(updateFeatureBitFlagsBuilderReferralIx);
2238
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
2239
+ return txSig;
2240
+ }
2241
+ async getUpdateFeatureBitFlagsBuilderReferralIx(enable) {
2242
+ return this.program.instruction.updateFeatureBitFlagsBuilderReferral(enable, {
2243
+ accounts: {
2244
+ admin: this.useHotWalletAdmin
2245
+ ? this.wallet.publicKey
2246
+ : this.getStateAccount().admin,
2247
+ state: await this.getStatePublicKey(),
2248
+ },
2249
+ });
2250
+ }
2219
2251
  }
2220
2252
  exports.AdminClient = AdminClient;
@@ -1228,6 +1228,18 @@ exports.MainnetPerpMarkets = [
1228
1228
  pythFeedId: '0xa903b5a82cb572397e3d47595d2889cf80513f5b4cf7a36b513ae10cc8b1e338',
1229
1229
  pythLazerId: 2310,
1230
1230
  },
1231
+ {
1232
+ fullName: 'PLASMA',
1233
+ category: ['DEX'],
1234
+ symbol: 'XPL-PERP',
1235
+ baseAssetSymbol: 'XPL',
1236
+ marketIndex: 77,
1237
+ oracle: new web3_js_1.PublicKey('6kgE1KJcxTux4tkPLE8LL8GRyW2cAsvyZsDFWqCrhHVe'),
1238
+ launchTs: 1758898862000,
1239
+ oracleSource: types_1.OracleSource.PYTH_LAZER,
1240
+ pythFeedId: '0x9873512f5cb33c77ad7a5af098d74812c62111166be395fd0941c8cedb9b00d4',
1241
+ pythLazerId: 2312,
1242
+ },
1231
1243
  ];
1232
1244
  exports.PerpMarkets = {
1233
1245
  devnet: exports.DevnetPerpMarkets,
@@ -25,6 +25,7 @@ import { WormholeCoreBridgeSolana } from '@pythnetwork/pyth-solana-receiver/lib/
25
25
  import { PythSolanaReceiver } from '@pythnetwork/pyth-solana-receiver/lib/idl/pyth_solana_receiver';
26
26
  import { Slothash } from './slot/SlothashSubscriber';
27
27
  import { SignedMsgOrderParams } from './types';
28
+ import { RevenueShareEscrowMap } from './userMap/revenueShareEscrowMap';
28
29
  type RemainingAccountParams = {
29
30
  userAccounts: UserAccount[];
30
31
  writablePerpMarketIndexes?: number[];
@@ -171,6 +172,16 @@ export declare class DriftClient {
171
172
  getResizeSignedMsgUserOrdersInstruction(authority: PublicKey, numOrders: number, userSubaccountId?: number): Promise<TransactionInstruction>;
172
173
  initializeSignedMsgWsDelegatesAccount(authority: PublicKey, delegates?: PublicKey[], txParams?: TxParams): Promise<TransactionSignature>;
173
174
  getInitializeSignedMsgWsDelegatesAccountIx(authority: PublicKey, delegates?: PublicKey[]): Promise<TransactionInstruction>;
175
+ initializeRevenueShare(authority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
176
+ getInitializeRevenueShareIx(authority: PublicKey): Promise<TransactionInstruction>;
177
+ initializeRevenueShareEscrow(authority: PublicKey, numOrders: number, txParams?: TxParams): Promise<TransactionSignature>;
178
+ getInitializeRevenueShareEscrowIx(authority: PublicKey, numOrders: number): Promise<TransactionInstruction>;
179
+ migrateReferrer(authority: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
180
+ getMigrateReferrerIx(authority: PublicKey): Promise<TransactionInstruction>;
181
+ resizeRevenueShareEscrowOrders(authority: PublicKey, numOrders: number, txParams?: TxParams): Promise<TransactionSignature>;
182
+ getResizeRevenueShareEscrowOrdersIx(authority: PublicKey, numOrders: number): Promise<TransactionInstruction>;
183
+ changeApprovedBuilder(builder: PublicKey, maxFeeTenthBps: number, add: boolean, txParams?: TxParams): Promise<TransactionSignature>;
184
+ getChangeApprovedBuilderIx(builder: PublicKey, maxFeeTenthBps: number, add: boolean): Promise<TransactionInstruction>;
174
185
  addSignedMsgWsDelegate(authority: PublicKey, delegate: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
175
186
  getAddSignedMsgWsDelegateIx(authority: PublicKey, delegate: PublicKey): Promise<TransactionInstruction>;
176
187
  removeSignedMsgWsDelegate(authority: PublicKey, delegate: PublicKey, txParams?: TxParams): Promise<TransactionSignature>;
@@ -292,6 +303,7 @@ export declare class DriftClient {
292
303
  getRemainingAccounts(params: RemainingAccountParams): AccountMeta[];
293
304
  addPerpMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>, perpMarketAccountMap: Map<number, AccountMeta>): void;
294
305
  addSpotMarketToRemainingAccountMaps(marketIndex: number, writable: boolean, oracleAccountMap: Map<string, AccountMeta>, spotMarketAccountMap: Map<number, AccountMeta>): void;
306
+ addBuilderToRemainingAccounts(builders: PublicKey[], remainingAccounts: AccountMeta[]): void;
295
307
  getRemainingAccountMapsForUsers(userAccounts: UserAccount[]): {
296
308
  oracleAccountMap: Map<string, AccountMeta>;
297
309
  spotMarketAccountMap: Map<number, AccountMeta>;
@@ -471,8 +483,8 @@ export declare class DriftClient {
471
483
  placeOrdersTx: anchor.web3.Transaction | anchor.web3.VersionedTransaction;
472
484
  }>;
473
485
  getPlaceOrdersIx(params: OptionalOrderParams[], subAccountId?: number): Promise<TransactionInstruction>;
474
- fillPerpOrder(userAccountPublicKey: PublicKey, user: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, txParams?: TxParams, fillerSubAccountId?: number, fillerAuthority?: PublicKey): Promise<TransactionSignature>;
475
- getFillPerpOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, fillerSubAccountId?: number, isSignedMsg?: boolean, fillerAuthority?: PublicKey): Promise<TransactionInstruction>;
486
+ fillPerpOrder(userAccountPublicKey: PublicKey, user: UserAccount, order?: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, txParams?: TxParams, fillerSubAccountId?: number, fillerAuthority?: PublicKey, hasBuilderFee?: boolean): Promise<TransactionSignature>;
487
+ getFillPerpOrderIx(userAccountPublicKey: PublicKey, userAccount: UserAccount, order: Pick<Order, 'marketIndex' | 'orderId'>, makerInfo?: MakerInfo | MakerInfo[], referrerInfo?: ReferrerInfo, fillerSubAccountId?: number, isSignedMsg?: boolean, fillerAuthority?: PublicKey, hasBuilderFee?: boolean): Promise<TransactionInstruction>;
476
488
  getRevertFillIx(fillerPublicKey?: PublicKey): Promise<TransactionInstruction>;
477
489
  placeSpotOrder(orderParams: OptionalOrderParams, txParams?: TxParams, subAccountId?: number): Promise<TransactionSignature>;
478
490
  preparePlaceSpotOrderTx(orderParams: OptionalOrderParams, txParams?: TxParams, subAccountId?: number): Promise<{
@@ -788,13 +800,13 @@ export declare class DriftClient {
788
800
  settleeUserAccountPublicKey: PublicKey;
789
801
  settleeUserAccount: UserAccount;
790
802
  }[], marketIndexes: number[]): Promise<Array<TransactionInstruction>>;
791
- settlePNL(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number, txParams?: TxParams, optionalIxs?: TransactionInstruction[]): Promise<TransactionSignature>;
792
- settlePNLIx(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number): Promise<TransactionInstruction>;
793
- settleMultiplePNLs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, txParams?: TxParams): Promise<TransactionSignature>;
794
- settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, txParams?: TxParams, optionalIxs?: TransactionInstruction[]): Promise<TransactionSignature[]>;
803
+ settlePNL(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number, txParams?: TxParams, optionalIxs?: TransactionInstruction[], escrowMap?: RevenueShareEscrowMap): Promise<TransactionSignature>;
804
+ settlePNLIx(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndex: number, revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionInstruction>;
805
+ settleMultiplePNLs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, revenueShareEscrowMap?: RevenueShareEscrowMap, txParams?: TxParams): Promise<TransactionSignature>;
806
+ settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, txParams?: TxParams, optionalIxs?: TransactionInstruction[], revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionSignature[]>;
795
807
  settleMultiplePNLsIx(settleeUserAccountPublicKey: PublicKey, settleeUserAccount: UserAccount, marketIndexes: number[], mode: SettlePnlMode, overrides?: {
796
808
  authority?: PublicKey;
797
- }): Promise<TransactionInstruction>;
809
+ }, revenueShareEscrowMap?: RevenueShareEscrowMap): Promise<TransactionInstruction>;
798
810
  getSetUserStatusToBeingLiquidatedIx(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionInstruction>;
799
811
  setUserStatusToBeingLiquidated(userAccountPublicKey: PublicKey, userAccount: UserAccount): Promise<TransactionSignature>;
800
812
  liquidatePerp(userAccountPublicKey: PublicKey, userAccount: UserAccount, marketIndex: number, maxBaseAssetAmount: BN, limitPrice?: BN, txParams?: TxParams, liquidatorSubAccountId?: number): Promise<TransactionSignature>;
@@ -72,6 +72,8 @@ const oracleId_1 = require("./oracles/oracleId");
72
72
  const sha256_1 = require("@noble/hashes/sha256");
73
73
  const utils_3 = require("./oracles/utils");
74
74
  const webSocketDriftClientAccountSubscriber_1 = require("./accounts/webSocketDriftClientAccountSubscriber");
75
+ const orders_1 = require("./math/orders");
76
+ const builder_1 = require("./math/builder");
75
77
  /**
76
78
  * # DriftClient
77
79
  * This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
@@ -692,6 +694,97 @@ class DriftClient {
692
694
  });
693
695
  return ix;
694
696
  }
697
+ async initializeRevenueShare(authority, txParams) {
698
+ const ix = await this.getInitializeRevenueShareIx(authority);
699
+ const tx = await this.buildTransaction([ix], txParams);
700
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
701
+ return txSig;
702
+ }
703
+ async getInitializeRevenueShareIx(authority) {
704
+ const revenueShare = (0, pda_1.getRevenueShareAccountPublicKey)(this.program.programId, authority);
705
+ return this.program.instruction.initializeRevenueShare({
706
+ accounts: {
707
+ revenueShare,
708
+ authority,
709
+ payer: this.wallet.publicKey,
710
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
711
+ systemProgram: anchor.web3.SystemProgram.programId,
712
+ },
713
+ });
714
+ }
715
+ async initializeRevenueShareEscrow(authority, numOrders, txParams) {
716
+ const ix = await this.getInitializeRevenueShareEscrowIx(authority, numOrders);
717
+ const tx = await this.buildTransaction([ix], txParams);
718
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
719
+ return txSig;
720
+ }
721
+ async getInitializeRevenueShareEscrowIx(authority, numOrders) {
722
+ const escrow = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, authority);
723
+ return this.program.instruction.initializeRevenueShareEscrow(numOrders, {
724
+ accounts: {
725
+ escrow,
726
+ authority,
727
+ payer: this.wallet.publicKey,
728
+ userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority),
729
+ state: await this.getStatePublicKey(),
730
+ rent: anchor.web3.SYSVAR_RENT_PUBKEY,
731
+ systemProgram: anchor.web3.SystemProgram.programId,
732
+ },
733
+ });
734
+ }
735
+ async migrateReferrer(authority, txParams) {
736
+ const ix = await this.getMigrateReferrerIx(authority);
737
+ const tx = await this.buildTransaction([ix], txParams);
738
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
739
+ return txSig;
740
+ }
741
+ async getMigrateReferrerIx(authority) {
742
+ const escrow = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, authority);
743
+ return this.program.instruction.migrateReferrer({
744
+ accounts: {
745
+ escrow,
746
+ authority,
747
+ userStats: (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, authority),
748
+ state: await this.getStatePublicKey(),
749
+ payer: this.wallet.publicKey,
750
+ },
751
+ });
752
+ }
753
+ async resizeRevenueShareEscrowOrders(authority, numOrders, txParams) {
754
+ const ix = await this.getResizeRevenueShareEscrowOrdersIx(authority, numOrders);
755
+ const tx = await this.buildTransaction([ix], txParams);
756
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
757
+ return txSig;
758
+ }
759
+ async getResizeRevenueShareEscrowOrdersIx(authority, numOrders) {
760
+ const escrow = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, authority);
761
+ return this.program.instruction.resizeRevenueShareEscrowOrders(numOrders, {
762
+ accounts: {
763
+ escrow,
764
+ authority,
765
+ payer: this.wallet.publicKey,
766
+ systemProgram: anchor.web3.SystemProgram.programId,
767
+ },
768
+ });
769
+ }
770
+ async changeApprovedBuilder(builder, maxFeeTenthBps, add, txParams) {
771
+ const ix = await this.getChangeApprovedBuilderIx(builder, maxFeeTenthBps, add);
772
+ const tx = await this.buildTransaction([ix], txParams);
773
+ const { txSig } = await this.sendTransaction(tx, [], this.opts);
774
+ return txSig;
775
+ }
776
+ async getChangeApprovedBuilderIx(builder, maxFeeTenthBps, add) {
777
+ const authority = this.wallet.publicKey;
778
+ const escrow = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, authority);
779
+ return this.program.instruction.changeApprovedBuilder(builder, maxFeeTenthBps, add, {
780
+ accounts: {
781
+ escrow,
782
+ authority,
783
+ payer: this.wallet.publicKey,
784
+ systemProgram: anchor.web3.SystemProgram.programId,
785
+ },
786
+ });
787
+ }
695
788
  async addSignedMsgWsDelegate(authority, delegate, txParams) {
696
789
  const ix = await this.getAddSignedMsgWsDelegateIx(authority, delegate);
697
790
  const tx = await this.buildTransaction([ix], txParams);
@@ -1096,6 +1189,16 @@ class DriftClient {
1096
1189
  userAccounts: [userAccount],
1097
1190
  writableSpotMarketIndexes,
1098
1191
  });
1192
+ for (const order of userAccount.orders) {
1193
+ if ((0, orders_1.hasBuilder)(order)) {
1194
+ remainingAccounts.push({
1195
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, userAccount.authority),
1196
+ isWritable: true,
1197
+ isSigner: false,
1198
+ });
1199
+ break;
1200
+ }
1201
+ }
1099
1202
  const tokenPrograms = new Set();
1100
1203
  for (const spotPosition of userAccount.spotPositions) {
1101
1204
  if ((0, spotPosition_1.isSpotPositionAvailable)(spotPosition)) {
@@ -1399,6 +1502,24 @@ class DriftClient {
1399
1502
  });
1400
1503
  }
1401
1504
  }
1505
+ addBuilderToRemainingAccounts(builders, remainingAccounts) {
1506
+ for (const builder of builders) {
1507
+ // Add User account for the builder
1508
+ const builderUserAccount = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, builder, 0 // subAccountId 0 for builder user account
1509
+ );
1510
+ remainingAccounts.push({
1511
+ pubkey: builderUserAccount,
1512
+ isSigner: false,
1513
+ isWritable: true,
1514
+ });
1515
+ const builderAccount = (0, pda_1.getRevenueShareAccountPublicKey)(this.program.programId, builder);
1516
+ remainingAccounts.push({
1517
+ pubkey: builderAccount,
1518
+ isSigner: false,
1519
+ isWritable: true,
1520
+ });
1521
+ }
1522
+ }
1402
1523
  getRemainingAccountMapsForUsers(userAccounts) {
1403
1524
  const oracleAccountMap = new Map();
1404
1525
  const spotMarketAccountMap = new Map();
@@ -2446,11 +2567,11 @@ class DriftClient {
2446
2567
  remainingAccounts,
2447
2568
  });
2448
2569
  }
2449
- async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, referrerInfo, txParams, fillerSubAccountId, fillerAuthority) {
2450
- const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, referrerInfo, fillerSubAccountId, undefined, fillerAuthority), txParams), [], this.opts);
2570
+ async fillPerpOrder(userAccountPublicKey, user, order, makerInfo, referrerInfo, txParams, fillerSubAccountId, fillerAuthority, hasBuilderFee) {
2571
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.getFillPerpOrderIx(userAccountPublicKey, user, order, makerInfo, referrerInfo, fillerSubAccountId, undefined, fillerAuthority, hasBuilderFee), txParams), [], this.opts);
2451
2572
  return txSig;
2452
2573
  }
2453
- async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, referrerInfo, fillerSubAccountId, isSignedMsg, fillerAuthority) {
2574
+ async getFillPerpOrderIx(userAccountPublicKey, userAccount, order, makerInfo, referrerInfo, fillerSubAccountId, isSignedMsg, fillerAuthority, hasBuilderFee) {
2454
2575
  const userStatsPublicKey = (0, pda_1.getUserStatsAccountPublicKey)(this.program.programId, userAccount.authority);
2455
2576
  let filler;
2456
2577
  if (fillerAuthority) {
@@ -2510,6 +2631,31 @@ class DriftClient {
2510
2631
  });
2511
2632
  }
2512
2633
  }
2634
+ let withBuilder = false;
2635
+ if (hasBuilderFee) {
2636
+ withBuilder = true;
2637
+ }
2638
+ else {
2639
+ // figure out if we need builder account or not
2640
+ if (order && !isSignedMsg) {
2641
+ const userOrder = userAccount.orders.find((o) => o.orderId === order.orderId);
2642
+ if (userOrder) {
2643
+ withBuilder = (0, orders_1.hasBuilder)(userOrder);
2644
+ }
2645
+ }
2646
+ else if (isSignedMsg) {
2647
+ // Order hasn't been placed yet, we cant tell if it has a builder or not.
2648
+ // Include it optimistically
2649
+ withBuilder = true;
2650
+ }
2651
+ }
2652
+ if (withBuilder) {
2653
+ remainingAccounts.push({
2654
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, userAccount.authority),
2655
+ isWritable: true,
2656
+ isSigner: false,
2657
+ });
2658
+ }
2513
2659
  const orderId = isSignedMsg ? null : order.orderId;
2514
2660
  return await this.program.instruction.fillPerpOrder(orderId, null, {
2515
2661
  accounts: {
@@ -3428,7 +3574,19 @@ class DriftClient {
3428
3574
  isSigner: false,
3429
3575
  });
3430
3576
  }
3577
+ remainingAccounts.push({
3578
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3579
+ isWritable: true,
3580
+ isSigner: false,
3581
+ });
3431
3582
  const takerOrderId = takerInfo.order.orderId;
3583
+ if ((0, orders_1.hasBuilder)(takerInfo.order)) {
3584
+ remainingAccounts.push({
3585
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3586
+ isWritable: true,
3587
+ isSigner: false,
3588
+ });
3589
+ }
3432
3590
  return await this.program.instruction.placeAndMakePerpOrder(orderParams, takerOrderId, {
3433
3591
  accounts: {
3434
3592
  state: await this.getStatePublicKey(),
@@ -3479,11 +3637,21 @@ class DriftClient {
3479
3637
  ? 'global' + ':' + 'SignedMsgOrderParamsDelegateMessage'
3480
3638
  : 'global' + ':' + 'SignedMsgOrderParamsMessage';
3481
3639
  const prefix = Buffer.from((0, sha256_1.sha256)(anchorIxName).slice(0, 8));
3640
+ // Backwards-compat: normalize optional builder fields to null for encoding
3641
+ const withBuilderDefaults = {
3642
+ ...orderParamsMessage,
3643
+ builderIdx: orderParamsMessage.builderIdx !== undefined
3644
+ ? orderParamsMessage.builderIdx
3645
+ : null,
3646
+ builderFeeTenthBps: orderParamsMessage.builderFeeTenthBps !== undefined
3647
+ ? orderParamsMessage.builderFeeTenthBps
3648
+ : null,
3649
+ };
3482
3650
  const buf = Buffer.concat([
3483
3651
  prefix,
3484
3652
  delegateSigner
3485
- ? this.program.coder.types.encode('SignedMsgOrderParamsDelegateMessage', orderParamsMessage)
3486
- : this.program.coder.types.encode('SignedMsgOrderParamsMessage', orderParamsMessage),
3653
+ ? this.program.coder.types.encode('SignedMsgOrderParamsDelegateMessage', withBuilderDefaults)
3654
+ : this.program.coder.types.encode('SignedMsgOrderParamsMessage', withBuilderDefaults),
3487
3655
  ]);
3488
3656
  return buf;
3489
3657
  }
@@ -3518,18 +3686,21 @@ class DriftClient {
3518
3686
  });
3519
3687
  const isDelegateSigner = takerInfo.signingAuthority.equals(takerInfo.takerUserAccount.delegate);
3520
3688
  const borshBuf = Buffer.from(signedSignedMsgOrderParams.orderParams.toString(), 'hex');
3521
- try {
3522
- const { signedMsgOrderParams } = this.decodeSignedMsgOrderParamsMessage(borshBuf, isDelegateSigner);
3523
- if ((0, orderParams_1.isUpdateHighLeverageMode)(signedMsgOrderParams.bitFlags)) {
3524
- remainingAccounts.push({
3525
- pubkey: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
3526
- isWritable: true,
3527
- isSigner: false,
3528
- });
3529
- }
3689
+ const signedMessage = this.decodeSignedMsgOrderParamsMessage(borshBuf, isDelegateSigner);
3690
+ if ((0, orderParams_1.isUpdateHighLeverageMode)(signedMessage.signedMsgOrderParams.bitFlags)) {
3691
+ remainingAccounts.push({
3692
+ pubkey: (0, pda_1.getHighLeverageModeConfigPublicKey)(this.program.programId),
3693
+ isWritable: true,
3694
+ isSigner: false,
3695
+ });
3530
3696
  }
3531
- catch (err) {
3532
- console.error('invalid signed order encoding');
3697
+ if (signedMessage.builderFeeTenthBps !== null &&
3698
+ signedMessage.builderIdx !== null) {
3699
+ remainingAccounts.push({
3700
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3701
+ isWritable: true,
3702
+ isSigner: false,
3703
+ });
3533
3704
  }
3534
3705
  const messageLengthBuffer = Buffer.alloc(2);
3535
3706
  messageLengthBuffer.writeUInt16LE(signedSignedMsgOrderParams.orderParams.length);
@@ -3584,6 +3755,17 @@ class DriftClient {
3584
3755
  isSigner: false,
3585
3756
  });
3586
3757
  }
3758
+ const isDelegateSigner = takerInfo.signingAuthority.equals(takerInfo.takerUserAccount.delegate);
3759
+ const borshBuf = Buffer.from(signedSignedMsgOrderParams.orderParams.toString(), 'hex');
3760
+ const signedMessage = this.decodeSignedMsgOrderParamsMessage(borshBuf, isDelegateSigner);
3761
+ if (signedMessage.builderFeeTenthBps !== null &&
3762
+ signedMessage.builderIdx !== null) {
3763
+ remainingAccounts.push({
3764
+ pubkey: (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, takerInfo.takerUserAccount.authority),
3765
+ isWritable: true,
3766
+ isSigner: false,
3767
+ });
3768
+ }
3587
3769
  const placeAndMakeIx = await this.program.instruction.placeAndMakeSignedMsgPerpOrder(orderParams, signedMsgOrderUuid, {
3588
3770
  accounts: {
3589
3771
  state: await this.getStatePublicKey(),
@@ -3914,17 +4096,76 @@ class DriftClient {
3914
4096
  }
3915
4097
  return ixs;
3916
4098
  }
3917
- async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, txParams, optionalIxs) {
4099
+ async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, txParams, optionalIxs, escrowMap) {
3918
4100
  const lookupTableAccounts = await this.fetchAllLookupTableAccounts();
3919
- const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex), txParams, undefined, lookupTableAccounts, undefined, undefined, optionalIxs), [], this.opts);
4101
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, escrowMap), txParams, undefined, lookupTableAccounts, undefined, undefined, optionalIxs), [], this.opts);
3920
4102
  return txSig;
3921
4103
  }
3922
- async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
4104
+ async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex, revenueShareEscrowMap) {
3923
4105
  const remainingAccounts = this.getRemainingAccounts({
3924
4106
  userAccounts: [settleeUserAccount],
3925
4107
  writablePerpMarketIndexes: [marketIndex],
3926
4108
  writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3927
4109
  });
4110
+ if (revenueShareEscrowMap) {
4111
+ const escrow = revenueShareEscrowMap.get(settleeUserAccount.authority.toBase58());
4112
+ if (escrow) {
4113
+ const escrowPk = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, settleeUserAccount.authority);
4114
+ const builders = new Map();
4115
+ for (const order of escrow.orders) {
4116
+ const eligibleBuilder = (0, builder_1.isBuilderOrderCompleted)(order) &&
4117
+ !(0, builder_1.isBuilderOrderReferral)(order) &&
4118
+ order.feesAccrued.gt(numericConstants_1.ZERO) &&
4119
+ order.marketIndex === marketIndex;
4120
+ if (eligibleBuilder && !builders.has(order.builderIdx)) {
4121
+ builders.set(order.builderIdx, escrow.approvedBuilders[order.builderIdx].authority);
4122
+ }
4123
+ }
4124
+ if (builders.size > 0) {
4125
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4126
+ remainingAccounts.push({
4127
+ pubkey: escrowPk,
4128
+ isSigner: false,
4129
+ isWritable: true,
4130
+ });
4131
+ }
4132
+ this.addBuilderToRemainingAccounts(Array.from(builders.values()), remainingAccounts);
4133
+ }
4134
+ // Include escrow and referrer accounts if referral rewards exist for this market
4135
+ const hasReferralForMarket = escrow.orders.some((o) => (0, builder_1.isBuilderOrderReferral)(o) &&
4136
+ o.feesAccrued.gt(numericConstants_1.ZERO) &&
4137
+ o.marketIndex === marketIndex);
4138
+ if (hasReferralForMarket) {
4139
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4140
+ remainingAccounts.push({
4141
+ pubkey: escrowPk,
4142
+ isSigner: false,
4143
+ isWritable: true,
4144
+ });
4145
+ }
4146
+ if (!escrow.referrer.equals(web3_js_1.PublicKey.default)) {
4147
+ this.addBuilderToRemainingAccounts([escrow.referrer], remainingAccounts);
4148
+ }
4149
+ }
4150
+ }
4151
+ else {
4152
+ // Stale-cache fallback: if the user has any builder orders, include escrow PDA. This allows
4153
+ // the program to lazily clean up any completed builder orders.
4154
+ for (const order of settleeUserAccount.orders) {
4155
+ if ((0, orders_1.hasBuilder)(order)) {
4156
+ const escrowPk = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, settleeUserAccount.authority);
4157
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4158
+ remainingAccounts.push({
4159
+ pubkey: escrowPk,
4160
+ isSigner: false,
4161
+ isWritable: true,
4162
+ });
4163
+ }
4164
+ break;
4165
+ }
4166
+ }
4167
+ }
4168
+ }
3928
4169
  return await this.program.instruction.settlePnl(marketIndex, {
3929
4170
  accounts: {
3930
4171
  state: await this.getStatePublicKey(),
@@ -3935,11 +4176,11 @@ class DriftClient {
3935
4176
  remainingAccounts: remainingAccounts,
3936
4177
  });
3937
4178
  }
3938
- async settleMultiplePNLs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams) {
3939
- const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode), txParams), [], this.opts);
4179
+ async settleMultiplePNLs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, revenueShareEscrowMap, txParams) {
4180
+ const { txSig } = await this.sendTransaction(await this.buildTransaction(await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, undefined, revenueShareEscrowMap), txParams), [], this.opts);
3940
4181
  return txSig;
3941
4182
  }
3942
- async settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams, optionalIxs) {
4183
+ async settleMultiplePNLsMultipleTxs(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, txParams, optionalIxs, revenueShareEscrowMap) {
3943
4184
  // need multiple TXs because settling more than 4 markets won't fit in a single TX
3944
4185
  const txsToSign = [];
3945
4186
  const marketIndexesInFourGroups = [];
@@ -3947,7 +4188,7 @@ class DriftClient {
3947
4188
  marketIndexesInFourGroups.push(marketIndexes.slice(i, i + 4));
3948
4189
  }
3949
4190
  for (const marketIndexes of marketIndexesInFourGroups) {
3950
- const ix = await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode);
4191
+ const ix = await this.settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, undefined, revenueShareEscrowMap);
3951
4192
  const computeUnits = Math.min(300000 * marketIndexes.length, 1400000);
3952
4193
  const tx = await this.buildTransaction(ix, {
3953
4194
  ...txParams,
@@ -3970,13 +4211,75 @@ class DriftClient {
3970
4211
  }
3971
4212
  return txSigs;
3972
4213
  }
3973
- async settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, overrides) {
4214
+ async settleMultiplePNLsIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndexes, mode, overrides, revenueShareEscrowMap) {
3974
4215
  var _a;
3975
4216
  const remainingAccounts = this.getRemainingAccounts({
3976
4217
  userAccounts: [settleeUserAccount],
3977
4218
  writablePerpMarketIndexes: marketIndexes,
3978
4219
  writableSpotMarketIndexes: [numericConstants_1.QUOTE_SPOT_MARKET_INDEX],
3979
4220
  });
4221
+ if (revenueShareEscrowMap) {
4222
+ const escrow = revenueShareEscrowMap.get(settleeUserAccount.authority.toBase58());
4223
+ const builders = new Map();
4224
+ if (escrow) {
4225
+ for (const order of escrow.orders) {
4226
+ const eligibleBuilder = (0, builder_1.isBuilderOrderCompleted)(order) &&
4227
+ !(0, builder_1.isBuilderOrderReferral)(order) &&
4228
+ order.feesAccrued.gt(numericConstants_1.ZERO) &&
4229
+ marketIndexes.includes(order.marketIndex);
4230
+ if (eligibleBuilder && !builders.has(order.builderIdx)) {
4231
+ builders.set(order.builderIdx, escrow.approvedBuilders[order.builderIdx].authority);
4232
+ }
4233
+ }
4234
+ if (builders.size > 0) {
4235
+ const escrowPk = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, settleeUserAccount.authority);
4236
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4237
+ remainingAccounts.push({
4238
+ pubkey: escrowPk,
4239
+ isSigner: false,
4240
+ isWritable: true,
4241
+ });
4242
+ }
4243
+ this.addBuilderToRemainingAccounts(Array.from(builders.values()), remainingAccounts);
4244
+ }
4245
+ // Include escrow and referrer accounts when there are referral rewards
4246
+ // for any of the markets we are settling, so on-chain sweep can find them.
4247
+ const hasReferralForRequestedMarkets = escrow.orders.some((o) => (0, builder_1.isBuilderOrderReferral)(o) &&
4248
+ o.feesAccrued.gt(numericConstants_1.ZERO) &&
4249
+ marketIndexes.includes(o.marketIndex));
4250
+ if (hasReferralForRequestedMarkets) {
4251
+ const escrowPk = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, settleeUserAccount.authority);
4252
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4253
+ remainingAccounts.push({
4254
+ pubkey: escrowPk,
4255
+ isSigner: false,
4256
+ isWritable: true,
4257
+ });
4258
+ }
4259
+ // Add referrer's User and RevenueShare accounts
4260
+ if (!escrow.referrer.equals(web3_js_1.PublicKey.default)) {
4261
+ this.addBuilderToRemainingAccounts([escrow.referrer], remainingAccounts);
4262
+ }
4263
+ }
4264
+ }
4265
+ else {
4266
+ // Stale-cache fallback: if the user has any builder orders, include escrow PDA. This allows
4267
+ // the program to lazily clean up any completed builder orders.
4268
+ for (const order of settleeUserAccount.orders) {
4269
+ if ((0, orders_1.hasBuilder)(order)) {
4270
+ const escrowPk = (0, pda_1.getRevenueShareEscrowAccountPublicKey)(this.program.programId, settleeUserAccount.authority);
4271
+ if (!remainingAccounts.find((a) => a.pubkey.equals(escrowPk))) {
4272
+ remainingAccounts.push({
4273
+ pubkey: escrowPk,
4274
+ isSigner: false,
4275
+ isWritable: true,
4276
+ });
4277
+ }
4278
+ break;
4279
+ }
4280
+ }
4281
+ }
4282
+ }
3980
4283
  return await this.program.instruction.settleMultiplePnls(marketIndexes, mode, {
3981
4284
  accounts: {
3982
4285
  state: await this.getStatePublicKey(),