@velocity-exchange/sdk 0.8.0 → 0.9.0

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 (55) hide show
  1. package/lib/browser/adminClient.d.ts +11 -8
  2. package/lib/browser/adminClient.js +13 -10
  3. package/lib/browser/decode/user.js +3 -1
  4. package/lib/browser/equityFloorManager.d.ts +150 -0
  5. package/lib/browser/equityFloorManager.js +279 -0
  6. package/lib/browser/idl/velocity.d.ts +84 -10
  7. package/lib/browser/idl/velocity.json +84 -10
  8. package/lib/browser/index.d.ts +2 -0
  9. package/lib/browser/index.js +2 -0
  10. package/lib/browser/jupiter/jupiterClient.js +24 -3
  11. package/lib/browser/math/margin.d.ts +26 -0
  12. package/lib/browser/math/margin.js +41 -1
  13. package/lib/browser/swap/UnifiedSwapClient.js +17 -3
  14. package/lib/browser/titan/titanClient.d.ts +6 -0
  15. package/lib/browser/titan/titanClient.js +44 -13
  16. package/lib/browser/types.d.ts +6 -2
  17. package/lib/browser/types.js +2 -0
  18. package/lib/browser/user.d.ts +38 -11
  19. package/lib/browser/user.js +84 -33
  20. package/lib/browser/velocityClient.d.ts +8 -7
  21. package/lib/browser/velocityClient.js +11 -15
  22. package/lib/node/adminClient.d.ts +11 -8
  23. package/lib/node/adminClient.d.ts.map +1 -1
  24. package/lib/node/adminClient.js +13 -10
  25. package/lib/node/decode/user.d.ts.map +1 -1
  26. package/lib/node/decode/user.js +3 -1
  27. package/lib/node/equityFloorManager.d.ts +151 -0
  28. package/lib/node/equityFloorManager.d.ts.map +1 -0
  29. package/lib/node/equityFloorManager.js +279 -0
  30. package/lib/node/idl/velocity.d.ts +84 -10
  31. package/lib/node/idl/velocity.d.ts.map +1 -1
  32. package/lib/node/idl/velocity.json +84 -10
  33. package/lib/node/index.d.ts +2 -0
  34. package/lib/node/index.d.ts.map +1 -1
  35. package/lib/node/index.js +2 -0
  36. package/lib/node/jupiter/jupiterClient.d.ts.map +1 -1
  37. package/lib/node/jupiter/jupiterClient.js +24 -3
  38. package/lib/node/math/margin.d.ts +26 -0
  39. package/lib/node/math/margin.d.ts.map +1 -1
  40. package/lib/node/math/margin.js +41 -1
  41. package/lib/node/swap/UnifiedSwapClient.d.ts.map +1 -1
  42. package/lib/node/swap/UnifiedSwapClient.js +17 -3
  43. package/lib/node/titan/titanClient.d.ts +6 -0
  44. package/lib/node/titan/titanClient.d.ts.map +1 -1
  45. package/lib/node/titan/titanClient.js +44 -13
  46. package/lib/node/types.d.ts +6 -2
  47. package/lib/node/types.d.ts.map +1 -1
  48. package/lib/node/types.js +2 -0
  49. package/lib/node/user.d.ts +38 -11
  50. package/lib/node/user.d.ts.map +1 -1
  51. package/lib/node/user.js +84 -33
  52. package/lib/node/velocityClient.d.ts +8 -7
  53. package/lib/node/velocityClient.d.ts.map +1 -1
  54. package/lib/node/velocityClient.js +11 -15
  55. package/package.json +1 -1
@@ -12460,6 +12460,10 @@
12460
12460
  {
12461
12461
  "name": "equity_floor",
12462
12462
  "type": "u64"
12463
+ },
12464
+ {
12465
+ "name": "equity_floor_buffer",
12466
+ "type": "u64"
12463
12467
  }
12464
12468
  ]
12465
12469
  },
@@ -12881,6 +12885,63 @@
12881
12885
  ],
12882
12886
  "args": []
12883
12887
  },
12888
+ {
12889
+ "name": "update_user_vault_owned",
12890
+ "docs": [
12891
+ "Mark a User as vault-owned (its authority is a vault PDA and its equity",
12892
+ "prices vault depositor shares). Set-only and authority-gated: only the",
12893
+ "User's authority may call it, and it is CPI'd by the vaults program at",
12894
+ "vault init. A vault-owned User is skipped by the revenue-share sweep so a",
12895
+ "builder/referral reward can never enter vault NAV (OtterSec #91/#92/#93)."
12896
+ ],
12897
+ "discriminator": [
12898
+ 50,
12899
+ 156,
12900
+ 218,
12901
+ 143,
12902
+ 216,
12903
+ 94,
12904
+ 68,
12905
+ 93
12906
+ ],
12907
+ "accounts": [
12908
+ {
12909
+ "name": "user",
12910
+ "writable": true,
12911
+ "pda": {
12912
+ "seeds": [
12913
+ {
12914
+ "kind": "const",
12915
+ "value": [
12916
+ 117,
12917
+ 115,
12918
+ 101,
12919
+ 114
12920
+ ]
12921
+ },
12922
+ {
12923
+ "kind": "account",
12924
+ "path": "authority"
12925
+ },
12926
+ {
12927
+ "kind": "arg",
12928
+ "path": "sub_account_id"
12929
+ }
12930
+ ]
12931
+ }
12932
+ },
12933
+ {
12934
+ "name": "authority",
12935
+ "signer": true
12936
+ }
12937
+ ],
12938
+ "args": [
12939
+ {
12940
+ "name": "_sub_account_id",
12941
+ "type": "u16"
12942
+ }
12943
+ ]
12944
+ },
12884
12945
  {
12885
12946
  "name": "update_warm_admin",
12886
12947
  "discriminator": [
@@ -16293,6 +16354,16 @@
16293
16354
  "code": 6364,
16294
16355
  "name": "DailyDepositLimit",
16295
16356
  "msg": "Spot market daily deposit limit hit"
16357
+ },
16358
+ {
16359
+ "code": 6365,
16360
+ "name": "ReservedSpotMarketName",
16361
+ "msg": "The name 'USDT' is reserved for the quote spot market (index 0)"
16362
+ },
16363
+ {
16364
+ "code": 6366,
16365
+ "name": "CannotModifyBuilderOrder",
16366
+ "msg": "Cannot modify a builder-coded order; cancel and re-place instead"
16296
16367
  }
16297
16368
  ],
16298
16369
  "types": [
@@ -24059,21 +24130,24 @@
24059
24130
  {
24060
24131
  "name": "equity_floor",
24061
24132
  "docs": [
24062
- "Minimum account equity (cross-margin total collateral) required for",
24063
- "risk-increasing orders, fills, withdrawals and deposit transfers.",
24064
- "Settable only by the warm/cold admin; 0 disables the check.",
24133
+ "Minimum account equity (cross-margin total collateral). Below this the",
24134
+ "permissionless breaker can trip. Risk-increasing orders, fills,",
24135
+ "withdrawals and deposit transfers must clear `equity_floor +",
24136
+ "equity_floor_buffer`. Settable only by the warm/cold admin; 0 disables",
24137
+ "both checks.",
24065
24138
  "precision: QUOTE_PRECISION"
24066
24139
  ],
24067
24140
  "type": "u64"
24068
24141
  },
24069
24142
  {
24070
- "name": "padding2",
24071
- "type": {
24072
- "array": [
24073
- "u8",
24074
- 8
24075
- ]
24076
- }
24143
+ "name": "equity_floor_buffer",
24144
+ "docs": [
24145
+ "Extra headroom above `equity_floor` required by risk-increasing",
24146
+ "actions, so an account cannot legally end an action at the trip",
24147
+ "threshold. No effect while `equity_floor` is 0.",
24148
+ "precision: QUOTE_PRECISION"
24149
+ ],
24150
+ "type": "u64"
24077
24151
  }
24078
24152
  ]
24079
24153
  }
@@ -45,6 +45,7 @@ export * from './adminClient';
45
45
  export * from './assert/assert';
46
46
  export { PythLazerSubscriber, type PythLazerPriceFeedArray, type PriceUpdateAccount, } from './pyth';
47
47
  export * from './testClient';
48
+ export * from './equityFloorManager';
48
49
  export * from './user';
49
50
  export * from './userConfig';
50
51
  export * from './userStats';
@@ -109,6 +110,7 @@ export * from './tx/priorityFeeCalculator';
109
110
  export * from './tx/types';
110
111
  export * from './tx/txHandler';
111
112
  export * from './tx/txParamProcessor';
113
+ export * from './tx/utils';
112
114
  export * from './util/computeUnits';
113
115
  export * from './util/digest';
114
116
  export * from './util/promiseTimeout';
@@ -75,6 +75,7 @@ __exportStar(require("./assert/assert"), exports);
75
75
  var pyth_1 = require("./pyth");
76
76
  Object.defineProperty(exports, "PythLazerSubscriber", { enumerable: true, get: function () { return pyth_1.PythLazerSubscriber; } });
77
77
  __exportStar(require("./testClient"), exports);
78
+ __exportStar(require("./equityFloorManager"), exports);
78
79
  __exportStar(require("./user"), exports);
79
80
  __exportStar(require("./userConfig"), exports);
80
81
  __exportStar(require("./userStats"), exports);
@@ -140,6 +141,7 @@ __exportStar(require("./tx/priorityFeeCalculator"), exports);
140
141
  __exportStar(require("./tx/types"), exports);
141
142
  __exportStar(require("./tx/txHandler"), exports);
142
143
  __exportStar(require("./tx/txParamProcessor"), exports);
144
+ __exportStar(require("./tx/utils"), exports);
143
145
  __exportStar(require("./util/computeUnits"), exports);
144
146
  __exportStar(require("./util/digest"), exports);
145
147
  __exportStar(require("./util/promiseTimeout"), exports);
@@ -47,6 +47,7 @@ class JupiterClient {
47
47
  */
48
48
  async getQuote({ inputMint, outputMint, amount, maxAccounts = 50, // 50 is an estimated amount with buffer
49
49
  slippageBps = 50, swapMode = 'ExactIn', onlyDirectRoutes = false, excludeDexes, autoSlippage = false, maxAutoSlippageBps, usdEstimate, }) {
50
+ var _a;
50
51
  if (autoSlippage && maxAutoSlippageBps === undefined) {
51
52
  throw new Error('JupiterClient.getQuote: maxAutoSlippageBps is required when autoSlippage is enabled');
52
53
  }
@@ -78,7 +79,21 @@ class JupiterClient {
78
79
  : '';
79
80
  const headers = this.getHeaders();
80
81
  const fetchOptions = Object.keys(headers).length > 0 ? { headers } : {};
81
- const quote = await (await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/quote?${params.toString()}`, fetchOptions)).json();
82
+ const response = await (0, node_fetch_1.default)(`${this.url}${apiVersionParam}/quote?${params.toString()}`, fetchOptions);
83
+ const quote = (await response.json().catch(() => undefined));
84
+ // A failed quote still returns parseable JSON — an `{ error, errorCode }`
85
+ // body with no mints or amounts. Returning it unchecked pushes the failure
86
+ // downstream to /swap, which rejects it with an opaque deserialization
87
+ // error ("missing field `inputMint`") that hides the real cause.
88
+ if (!response.ok || !quote) {
89
+ throw new Error(`Jupiter quote failed: ${response.status} ${(quote === null || quote === void 0 ? void 0 : quote.error) || (quote === null || quote === void 0 ? void 0 : quote.errorCode) || response.statusText}`);
90
+ }
91
+ if (quote.error || quote.errorCode) {
92
+ throw new Error(`Jupiter quote failed: ${(_a = quote.error) !== null && _a !== void 0 ? _a : quote.errorCode}`);
93
+ }
94
+ if (!quote.inputMint || !quote.outputMint || !quote.outAmount) {
95
+ throw new Error('Jupiter quote failed: response is missing route fields');
96
+ }
82
97
  return quote;
83
98
  }
84
99
  /**
@@ -134,12 +149,18 @@ class JupiterClient {
134
149
  };
135
150
  }
136
151
  async getLookupTable(accountKey) {
137
- var _a;
138
152
  const cached = this.lookupTableCahce.get(accountKey.toString());
139
153
  if (cached !== undefined) {
140
154
  return cached;
141
155
  }
142
- return ((_a = (await this.connection.getAddressLookupTable(accountKey)).value) !== null && _a !== void 0 ? _a : undefined);
156
+ const lookupTable = (await this.connection.getAddressLookupTable(accountKey)).value;
157
+ if (!lookupTable) {
158
+ return undefined;
159
+ }
160
+ // Populate the cache — without this every route re-fetches the same tables,
161
+ // which is a large share of the RPC calls a swap makes.
162
+ this.lookupTableCahce.set(accountKey.toString(), lookupTable);
163
+ return lookupTable;
143
164
  }
144
165
  /**
145
166
  * Get the jupiter instructions from transaction by filtering out instructions to compute budget and associated token programs
@@ -100,3 +100,29 @@ export declare function calculateMarginUSDCRequiredForTrade(velocityClient: Velo
100
100
  * @returns Collateral amount required, in `collateralIndex`'s own spot-market precision (via `velocityClient.convertToSpotPrecision`).
101
101
  */
102
102
  export declare function calculateCollateralDepositRequiredForTrade(velocityClient: VelocityClient, targetMarketIndex: number, baseSize: BN, collateralIndex: number, userMaxMarginRatio?: number, estEntryPrice?: BN): BN;
103
+ /**
104
+ * Minimal equity floor to carry along with a quote transfer of `amount` out
105
+ * of a subaccount so the debited side ends at/above its buffered floor
106
+ * (`equityFloor + equityFloorBuffer`): the first
107
+ * `totalCollateral - (floor + buffer)` of the transfer carries no floor, the
108
+ * remainder carries floor one-for-one, capped at the floor the subaccount
109
+ * actually holds. Returns zero when no floor is set. The result never exceeds
110
+ * `amount`, so a credited side that met its own buffered floor before the
111
+ * transfer still meets it after. All values QUOTE_PRECISION.
112
+ */
113
+ export declare function calculateEquityFloorAutoDelta(amount: BN, totalCollateral: BN, equityFloor: BN, equityFloorBuffer: BN): BN;
114
+ /**
115
+ * Severity of a subaccount's equity relative to its floor, most to least
116
+ * severe. `breached`: below the floor, the permissionless breaker can trip.
117
+ * `critical`: below `floor + buffer`, risk-increasing actions are rejecting.
118
+ * `warning`: within `warningBufferMultiple * buffer` of the floor.
119
+ * `healthy`: above all thresholds. `disabled`: no floor set.
120
+ */
121
+ export type EquityFloorLevel = 'breached' | 'critical' | 'warning' | 'healthy' | 'disabled';
122
+ /**
123
+ * Classifies `totalCollateral` against the floor thresholds. Used by the
124
+ * `EquityFloorManager` and the equity-floor guard bot so both report the same
125
+ * levels. `warningBufferMultiple` scales the warning threshold above the
126
+ * floor (default 2: warn inside `floor + 2 * buffer`). All QUOTE_PRECISION.
127
+ */
128
+ export declare function getEquityFloorLevel(totalCollateral: BN, equityFloor: BN, equityFloorBuffer: BN, warningBufferMultiple?: number): EquityFloorLevel;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateCollateralDepositRequiredForTrade = exports.calculateMarginUSDCRequiredForTrade = exports.calculatePerpLiabilityValue = exports.calculateWorstCasePerpLiabilityValue = exports.calculateWorstCaseBaseAssetAmount = exports.calculateBaseAssetValueWithOracle = exports.calculateSizeDiscountAssetWeight = exports.calculateSizePremiumLiabilityWeight = void 0;
3
+ exports.getEquityFloorLevel = exports.calculateEquityFloorAutoDelta = exports.calculateCollateralDepositRequiredForTrade = exports.calculateMarginUSDCRequiredForTrade = exports.calculatePerpLiabilityValue = exports.calculateWorstCasePerpLiabilityValue = exports.calculateWorstCaseBaseAssetAmount = exports.calculateBaseAssetValueWithOracle = exports.calculateSizeDiscountAssetWeight = exports.calculateSizePremiumLiabilityWeight = void 0;
4
4
  /**
5
5
  * Margin calculation helpers — TypeScript mirror of `programs/velocity/src/math/margin.rs`.
6
6
  * Computes initial/maintenance margin requirements, free collateral, and account health.
@@ -210,3 +210,43 @@ function calculateCollateralDepositRequiredForTrade(velocityClient, targetMarket
210
210
  return baseAmountRequired;
211
211
  }
212
212
  exports.calculateCollateralDepositRequiredForTrade = calculateCollateralDepositRequiredForTrade;
213
+ /**
214
+ * Minimal equity floor to carry along with a quote transfer of `amount` out
215
+ * of a subaccount so the debited side ends at/above its buffered floor
216
+ * (`equityFloor + equityFloorBuffer`): the first
217
+ * `totalCollateral - (floor + buffer)` of the transfer carries no floor, the
218
+ * remainder carries floor one-for-one, capped at the floor the subaccount
219
+ * actually holds. Returns zero when no floor is set. The result never exceeds
220
+ * `amount`, so a credited side that met its own buffered floor before the
221
+ * transfer still meets it after. All values QUOTE_PRECISION.
222
+ */
223
+ function calculateEquityFloorAutoDelta(amount, totalCollateral, equityFloor, equityFloorBuffer) {
224
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
225
+ return numericConstants_1.ZERO;
226
+ }
227
+ const excess = anchor_1.BN.max(totalCollateral.sub(equityFloor.add(equityFloorBuffer)), numericConstants_1.ZERO);
228
+ return anchor_1.BN.min(anchor_1.BN.max(amount.sub(excess), numericConstants_1.ZERO), equityFloor);
229
+ }
230
+ exports.calculateEquityFloorAutoDelta = calculateEquityFloorAutoDelta;
231
+ /**
232
+ * Classifies `totalCollateral` against the floor thresholds. Used by the
233
+ * `EquityFloorManager` and the equity-floor guard bot so both report the same
234
+ * levels. `warningBufferMultiple` scales the warning threshold above the
235
+ * floor (default 2: warn inside `floor + 2 * buffer`). All QUOTE_PRECISION.
236
+ */
237
+ function getEquityFloorLevel(totalCollateral, equityFloor, equityFloorBuffer, warningBufferMultiple = 2) {
238
+ if (equityFloor.lte(numericConstants_1.ZERO)) {
239
+ return 'disabled';
240
+ }
241
+ if (totalCollateral.lt(equityFloor)) {
242
+ return 'breached';
243
+ }
244
+ if (totalCollateral.lt(equityFloor.add(equityFloorBuffer))) {
245
+ return 'critical';
246
+ }
247
+ if (totalCollateral.lt(equityFloor.add(equityFloorBuffer.muln(warningBufferMultiple)))) {
248
+ return 'warning';
249
+ }
250
+ return 'healthy';
251
+ }
252
+ exports.getEquityFloorLevel = getEquityFloorLevel;
@@ -3,6 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UnifiedSwapClient = void 0;
4
4
  const jupiterClient_1 = require("../jupiter/jupiterClient");
5
5
  const titanClient_1 = require("../titan/titanClient");
6
+ const utils_1 = require("../tx/utils");
7
+ /**
8
+ * Bytes reserved for the velocity begin/end swap instructions that wrap the
9
+ * route, so the provider only gets the budget actually left for the route.
10
+ */
11
+ const VELOCITY_SWAP_IX_SIZE_BUFFER = 375;
12
+ /** Byte budget handed to a swap provider for the route portion of the tx. */
13
+ const DEFAULT_ROUTE_SIZE_CONSTRAINT = utils_1.MAX_TX_BYTE_SIZE - VELOCITY_SWAP_IX_SIZE_BUFFER;
6
14
  class UnifiedSwapClient {
7
15
  /**
8
16
  * Create a unified swap client
@@ -56,7 +64,7 @@ class UnifiedSwapClient {
56
64
  ...titanParams,
57
65
  userPublicKey: titanParams.userPublicKey,
58
66
  swapMode: titanParams.swapMode, // Titan expects string
59
- sizeConstraint: titanParams.sizeConstraint || 1280 - 375, // Use same default as getSwapInstructions
67
+ sizeConstraint: titanParams.sizeConstraint || DEFAULT_ROUTE_SIZE_CONSTRAINT,
60
68
  };
61
69
  return await titanClient.getQuote(titanParamsWithUser);
62
70
  }
@@ -131,7 +139,13 @@ class UnifiedSwapClient {
131
139
  }
132
140
  else {
133
141
  const titanClient = this.client;
134
- // For Titan, get swap directly (it handles quote internally)
142
+ // For Titan, get swap directly (it handles quote internally).
143
+ //
144
+ // NOTE: `getSwap` reads only `userPublicKey` — it replays the route
145
+ // cached by the preceding `getQuote`, so every other argument here is
146
+ // inert. The size constraint is therefore enforced at quote time (see
147
+ // `getQuote` above), which means an explicit `sizeConstraint` passed
148
+ // only to this method does not affect route selection.
135
149
  const { transactionMessage, lookupTables: titanLookupTables } = await titanClient.getSwap({
136
150
  inputMint,
137
151
  outputMint,
@@ -140,7 +154,7 @@ class UnifiedSwapClient {
140
154
  slippageBps,
141
155
  swapMode: isExactOut ? titanClient_1.SwapMode.ExactOut : titanClient_1.SwapMode.ExactIn,
142
156
  onlyDirectRoutes,
143
- sizeConstraint: sizeConstraint || 1280 - 375, // MAX_TX_BYTE_SIZE - buffer for velocity instructions
157
+ sizeConstraint: sizeConstraint || DEFAULT_ROUTE_SIZE_CONSTRAINT,
144
158
  });
145
159
  swapInstructions = titanClient.getTitanInstructions({
146
160
  transactionMessage,
@@ -85,5 +85,11 @@ export declare class TitanClient {
85
85
  inputMint: PublicKey;
86
86
  outputMint: PublicKey;
87
87
  }): TransactionInstruction[];
88
+ /**
89
+ * Fetches a lookup table required by a route, retrying transient RPC
90
+ * failures (rate limiting in particular) before giving up.
91
+ * @throws If the table still can't be loaded, or doesn't exist on-chain.
92
+ */
93
+ private fetchLookupTable;
88
94
  private getTransactionMessageAndLookupTables;
89
95
  }
@@ -9,6 +9,10 @@ var SwapMode;
9
9
  SwapMode["ExactOut"] = "ExactOut";
10
10
  })(SwapMode || (exports.SwapMode = SwapMode = {}));
11
11
  const TITAN_API_URL = 'https://api.titan.exchange';
12
+ /** Retries for a route's lookup tables, which must all resolve for the tx to fit. */
13
+ const LOOKUP_TABLE_FETCH_RETRIES = 2;
14
+ const LOOKUP_TABLE_RETRY_BASE_DELAY_MS = 150;
15
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
16
  class TitanClient {
13
17
  constructor({ connection, authToken, url, proxyUrl, }) {
14
18
  this.connection = connection;
@@ -141,13 +145,13 @@ class TitanClient {
141
145
  throw new Error('No routes available');
142
146
  }
143
147
  if (route.instructions && route.instructions.length > 0) {
148
+ // Errors propagate as-is. Replacing them with generic copy here loses
149
+ // the reason the swap can't be built — an unresolvable lookup table,
150
+ // say — which the caller needs to decide whether re-quoting will help.
144
151
  try {
145
152
  const { transactionMessage, lookupTables } = await this.getTransactionMessageAndLookupTables(route, userPublicKey);
146
153
  return { transactionMessage, lookupTables };
147
154
  }
148
- catch (err) {
149
- throw new Error('Something went wrong with creating the Titan swap transaction. Please try again.');
150
- }
151
155
  finally {
152
156
  // Clear cached quote data after use
153
157
  this.lastQuoteData = undefined;
@@ -189,6 +193,35 @@ class TitanClient {
189
193
  });
190
194
  return filteredInstructions;
191
195
  }
196
+ /**
197
+ * Fetches a lookup table required by a route, retrying transient RPC
198
+ * failures (rate limiting in particular) before giving up.
199
+ * @throws If the table still can't be loaded, or doesn't exist on-chain.
200
+ */
201
+ async fetchLookupTable(altPubkey) {
202
+ let lastError;
203
+ for (let attempt = 0; attempt <= LOOKUP_TABLE_FETCH_RETRIES; attempt++) {
204
+ if (attempt > 0) {
205
+ await sleep(LOOKUP_TABLE_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1));
206
+ }
207
+ let altAccount;
208
+ try {
209
+ altAccount = await this.connection.getAddressLookupTable(altPubkey);
210
+ }
211
+ catch (err) {
212
+ // Transient — rate limiting, connection reset. Worth another go.
213
+ lastError = err;
214
+ continue;
215
+ }
216
+ if (altAccount.value) {
217
+ return altAccount.value;
218
+ }
219
+ // A successful response with no value means the route references a
220
+ // table that isn't on-chain. Retrying won't conjure it up.
221
+ throw new Error(`Address lookup table ${altPubkey.toString()} does not exist`);
222
+ }
223
+ throw new Error(`Failed to fetch address lookup table ${altPubkey.toString()}: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
224
+ }
192
225
  async getTransactionMessageAndLookupTables(route, userPublicKey) {
193
226
  const solanaInstructions = route.instructions.map((instruction) => ({
194
227
  programId: new web3_js_1.PublicKey(instruction.p),
@@ -201,19 +234,17 @@ class TitanClient {
201
234
  }));
202
235
  // Get recent blockhash
203
236
  const { blockhash } = await this.connection.getLatestBlockhash();
204
- // Build address lookup tables if provided
237
+ // Build address lookup tables if provided.
238
+ //
239
+ // These all have to resolve. A table that fails to load isn't a slightly
240
+ // worse route — every account it would have compressed to a 1-byte index
241
+ // gets inlined as a 32-byte pubkey instead, which pushes the transaction
242
+ // past the size limit and only surfaces later as an opaque
243
+ // "encoding overruns Uint8Array". Failing here lets the caller re-quote.
205
244
  const addressLookupTables = [];
206
245
  if (route.addressLookupTables && route.addressLookupTables.length > 0) {
207
246
  for (const altPubkey of route.addressLookupTables) {
208
- try {
209
- const altAccount = await this.connection.getAddressLookupTable(new web3_js_1.PublicKey(altPubkey));
210
- if (altAccount.value) {
211
- addressLookupTables.push(altAccount.value);
212
- }
213
- }
214
- catch (err) {
215
- console.warn(`Failed to fetch address lookup table:`, err);
216
- }
247
+ addressLookupTables.push(await this.fetchLookupTable(new web3_js_1.PublicKey(altPubkey)));
217
248
  }
218
249
  }
219
250
  const transactionMessage = new web3_js_1.TransactionMessage({
@@ -116,7 +116,9 @@ export declare enum UserStatus {
116
116
  BEING_LIQUIDATED = 1,
117
117
  BANKRUPT = 2,
118
118
  REDUCE_ONLY = 4,
119
- ADVANCED_LP = 8
119
+ ADVANCED_LP = 8,
120
+ /** Owned by a Strategy Vault (authority is a vault PDA; equity prices vault shares). Revenue-share sweeps skip such Users so a builder/referral reward can't enter vault NAV. */
121
+ VAULT_OWNED = 32
120
122
  }
121
123
  /** Bitmask mirror of `UserAccount.specialUserStatus`. `VAMM_HEDGER` marks the account used by the protocol's own vAMM-hedging bot. */
122
124
  export declare enum SpecialUserStatus {
@@ -1697,8 +1699,10 @@ export type UserAccount = {
1697
1699
  poolId: number;
1698
1700
  /** bitmask, see `SpecialUserStatus` */
1699
1701
  specialUserStatus: number;
1700
- /** QUOTE_PRECISION (1e6); admin-set minimum cross-margin total collateral for risk-increasing orders, fills, withdrawals and transfers; 0 = disabled */
1702
+ /** QUOTE_PRECISION (1e6); admin-set minimum cross-margin total collateral; below it the permissionless breaker can trip; 0 = disabled */
1701
1703
  equityFloor: BN;
1704
+ /** QUOTE_PRECISION (1e6); extra headroom above `equityFloor` required by risk-increasing orders, fills, withdrawals and transfers; no effect while `equityFloor` is 0 */
1705
+ equityFloorBuffer: BN;
1702
1706
  };
1703
1707
  /** A user's balance in one spot market. Decoded mirror of the on-chain `SpotPosition`. */
1704
1708
  export type SpotPosition = {
@@ -103,6 +103,8 @@ var UserStatus;
103
103
  UserStatus[UserStatus["REDUCE_ONLY"] = 4] = "REDUCE_ONLY";
104
104
  UserStatus[UserStatus["ADVANCED_LP"] = 8] = "ADVANCED_LP";
105
105
  // 16 reserved (was PROTECTED_MAKER)
106
+ /** Owned by a Strategy Vault (authority is a vault PDA; equity prices vault shares). Revenue-share sweeps skip such Users so a builder/referral reward can't enter vault NAV. */
107
+ UserStatus[UserStatus["VAULT_OWNED"] = 32] = "VAULT_OWNED";
106
108
  })(UserStatus || (exports.UserStatus = UserStatus = {}));
107
109
  /** Bitmask mirror of `UserAccount.specialUserStatus`. `VAMM_HEDGER` marks the account used by the protocol's own vAMM-hedging bot. */
108
110
  var SpecialUserStatus;
@@ -362,24 +362,23 @@ export declare class User {
362
362
  * @param marginCategory `'Initial'` or `'Maintenance'` asset/liability weights; omit for unweighted (100%) values.
363
363
  * @param liquidationBuffer Optional buffer (MARGIN_PRECISION, 1e4) added to the liability weight side.
364
364
  * @param includeOpenOrders If false, ignores open bids/asks and only counts the current balance (faster, less conservative).
365
- * @param strict Use the worse of live oracle price vs 5-minute TWAP. Defaults to false.
366
- * @param now Unix timestamp (seconds) used for TWAP staleness when `strict` is set; defaults to current time.
365
+ * @param strict Use the worse of live oracle price vs the market's stored 5-minute TWAP. Defaults to false.
367
366
  * @returns `{ totalAssetValue, totalLiabilityValue }`, both QUOTE_PRECISION (1e6) and non-negative.
368
367
  */
369
- getSpotMarketAssetAndLiabilityValue(marketIndex?: number, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, now?: BN): {
368
+ getSpotMarketAssetAndLiabilityValue(marketIndex?: number, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean): {
370
369
  totalAssetValue: BN;
371
370
  totalLiabilityValue: BN;
372
371
  };
373
372
  /** Convenience wrapper around `getSpotMarketAssetAndLiabilityValue` returning only `totalLiabilityValue`. See that method for parameter semantics. Returns QUOTE_PRECISION (1e6). */
374
- getSpotMarketLiabilityValue(marketIndex?: number, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean, now?: BN): BN;
373
+ getSpotMarketLiabilityValue(marketIndex?: number, marginCategory?: MarginCategory, liquidationBuffer?: BN, includeOpenOrders?: boolean, strict?: boolean): BN;
375
374
  /** Thin wrapper around the `math/spotBalance` `getSpotLiabilityValue` helper that supplies the user's `maxMarginRatio`. Returns QUOTE_PRECISION (1e6), negative. */
376
375
  getSpotLiabilityValue(tokenAmount: BN, strictOraclePrice: StrictOraclePrice, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory, liquidationBuffer?: BN): BN;
377
376
  /** Convenience wrapper around `getSpotMarketAssetAndLiabilityValue` returning only `totalAssetValue`. See that method for parameter semantics. Returns QUOTE_PRECISION (1e6), non-negative. */
378
- getSpotMarketAssetValue(marketIndex?: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean, now?: BN): BN;
377
+ getSpotMarketAssetValue(marketIndex?: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean): BN;
379
378
  /** Thin wrapper around the `math/spotBalance` `getSpotAssetValue` helper that supplies the user's `maxMarginRatio`. Returns QUOTE_PRECISION (1e6), non-negative. */
380
379
  getSpotAssetValue(tokenAmount: BN, strictOraclePrice: StrictOraclePrice, spotMarketAccount: SpotMarketAccount, marginCategory?: MarginCategory): BN;
381
380
  /** Net spot value (`totalAssetValue - totalLiabilityValue`) for a single spot market. See `getSpotMarketAssetAndLiabilityValue` for parameter semantics. Returns QUOTE_PRECISION (1e6), can be negative. */
382
- getSpotPositionValue(marketIndex: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean, now?: BN): BN;
381
+ getSpotPositionValue(marketIndex: number, marginCategory?: MarginCategory, includeOpenOrders?: boolean, strict?: boolean): BN;
383
382
  /**
384
383
  * Net spot value (`totalAssetValue - totalLiabilityValue`) across all spot
385
384
  * markets combined.
@@ -412,19 +411,46 @@ export declare class User {
412
411
  getTotalCollateral(marginCategory?: MarginCategory, strict?: boolean, includeOpenOrders?: boolean, liquidationBuffer?: BN, perpMarketIndex?: number): BN;
413
412
  /**
414
413
  * True when the account has an admin-set `equityFloor` and its cross-margin
415
- * total collateral is below it. While below the floor, the program rejects
416
- * risk-increasing order placement and fills, withdrawals, and transfers out
417
- * of the account (`EquityBelowFloor`); reduce-only activity stays allowed.
414
+ * total collateral is below it. This is the trip threshold of the
415
+ * permissionless `tripEquityFloorBreaker`; action gating happens at
416
+ * `equityFloor + equityFloorBuffer` (see `isBelowBufferedEquityFloor`).
418
417
  * Mirrors `User::is_below_equity_floor` on-chain.
419
418
  * @param strict Use TWAP-bounded oracle pricing, matching the withdraw path. Defaults to false.
420
419
  */
421
420
  isBelowEquityFloor(strict?: boolean): boolean;
421
+ /**
422
+ * The equity required by risk-increasing actions:
423
+ * `equityFloor + equityFloorBuffer` (QUOTE_PRECISION). Mirrors
424
+ * `User::buffered_equity_floor` on-chain. Meaningless while
425
+ * `equityFloor` is 0 (the checks are disabled).
426
+ */
427
+ getBufferedEquityFloor(): BN;
428
+ /**
429
+ * True when the account has an admin-set `equityFloor` and its cross-margin
430
+ * total collateral is below `equityFloor + equityFloorBuffer`. While below,
431
+ * the program rejects risk-increasing order placement and fills,
432
+ * withdrawals, and transfers out of the account (`EquityBelowFloor`);
433
+ * reduce-only activity stays allowed. Mirrors
434
+ * `User::is_below_buffered_equity_floor` on-chain.
435
+ * @param strict Use TWAP-bounded oracle pricing, matching the withdraw path. Defaults to false.
436
+ */
437
+ isBelowBufferedEquityFloor(strict?: boolean): boolean;
422
438
  /**
423
439
  * Cross-margin total collateral in excess of the admin-set `equityFloor`,
424
440
  * floored at zero (QUOTE_PRECISION). Unbounded (`null`) when no floor is set.
441
+ * This is headroom above the trip threshold; headroom above the level
442
+ * risk-increasing actions must clear is `getEquityAboveBufferedFloor`.
425
443
  * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
426
444
  */
427
445
  getEquityAboveFloor(strict?: boolean): BN | null;
446
+ /**
447
+ * Cross-margin total collateral in excess of `equityFloor +
448
+ * equityFloorBuffer`, floored at zero (QUOTE_PRECISION). Unbounded
449
+ * (`null`) when no floor is set. When this reaches zero, risk-increasing
450
+ * actions start rejecting.
451
+ * @param strict Use TWAP-bounded oracle pricing. Defaults to false.
452
+ */
453
+ getEquityAboveBufferedFloor(strict?: boolean): BN | null;
428
454
  /**
429
455
  * Builds the liquidation-buffer map to pass into margin calculations while
430
456
  * a liquidation is in progress: `'cross'` is set to the state account's
@@ -768,7 +794,7 @@ export declare class User {
768
794
  * @param outMarketIndex
769
795
  * @param calculateSwap Optional function to simulate the in-to-out conversion (e.g. to model swap fees/slippage); defaults to a 1:1 oracle-price conversion.
770
796
  * @param iterationLimit How many binary-search iterations to run before erroring out. Defaults to 1000.
771
- * @returns `inAmount`/`outAmount` in each market's own token decimals, and the resulting `leverage` (TEN_THOUSAND, 1e4 precision) after the swap.
797
+ * @returns `inAmount`/`outAmount` in each market's own token decimals, and the resulting `leverage` (TEN_THOUSAND, 1e4 precision) after the swap. Sizing is TWAP-bounded to match the program's margin check; `leverage` is marked at the live oracle price so it stays comparable to `getLeverage()`.
772
798
  */
773
799
  getMaxSwapAmount({ inMarketIndex, outMarketIndex, calculateSwap, iterationLimit, }: {
774
800
  inMarketIndex: number;
@@ -796,7 +822,8 @@ export declare class User {
796
822
  totalLiabilityValue: BN;
797
823
  };
798
824
  /**
799
- * Estimates what the user leverage will be after swap
825
+ * Estimates what the user leverage will be after swap, marked at the live
826
+ * oracle price so it stays comparable to `getLeverage()`.
800
827
  * @param inMarketIndex Market being sold/paid from.
801
828
  * @param outMarketIndex Market being bought/received.
802
829
  * @param inAmount Amount removed from `inMarketIndex`, that market's own token decimals.