@velocity-exchange/sdk 0.9.0 → 0.11.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 (74) hide show
  1. package/lib/browser/adminClient.d.ts +4 -3
  2. package/lib/browser/adminClient.js +5 -13
  3. package/lib/browser/equityFloorManager.d.ts +9 -5
  4. package/lib/browser/equityFloorManager.js +9 -5
  5. package/lib/browser/idl/velocity.d.ts +119 -3
  6. package/lib/browser/idl/velocity.json +119 -3
  7. package/lib/browser/index.d.ts +2 -0
  8. package/lib/browser/index.js +3 -0
  9. package/lib/browser/jupiter/jupiterClient.d.ts +31 -27
  10. package/lib/browser/jupiter/jupiterClient.js +61 -35
  11. package/lib/browser/math/amm.d.ts +6 -5
  12. package/lib/browser/math/amm.js +39 -19
  13. package/lib/browser/math/margin.d.ts +12 -10
  14. package/lib/browser/math/margin.js +16 -14
  15. package/lib/browser/math/superStake.d.ts +9 -9
  16. package/lib/browser/math/superStake.js +8 -8
  17. package/lib/browser/swap/UnifiedSwapClient.d.ts +38 -76
  18. package/lib/browser/swap/UnifiedSwapClient.js +46 -117
  19. package/lib/browser/swap/routeInstructions.d.ts +19 -0
  20. package/lib/browser/swap/routeInstructions.js +43 -0
  21. package/lib/browser/swap/types.d.ts +196 -0
  22. package/lib/browser/swap/types.js +88 -0
  23. package/lib/browser/titan/titanClient.d.ts +32 -68
  24. package/lib/browser/titan/titanClient.js +128 -102
  25. package/lib/browser/types.d.ts +2 -0
  26. package/lib/browser/user.d.ts +16 -18
  27. package/lib/browser/user.js +24 -26
  28. package/lib/browser/velocityClient.d.ts +122 -101
  29. package/lib/browser/velocityClient.js +221 -289
  30. package/lib/node/adminClient.d.ts +4 -3
  31. package/lib/node/adminClient.d.ts.map +1 -1
  32. package/lib/node/adminClient.js +5 -13
  33. package/lib/node/equityFloorManager.d.ts +9 -5
  34. package/lib/node/equityFloorManager.d.ts.map +1 -1
  35. package/lib/node/equityFloorManager.js +9 -5
  36. package/lib/node/idl/velocity.d.ts +119 -3
  37. package/lib/node/idl/velocity.d.ts.map +1 -1
  38. package/lib/node/idl/velocity.json +119 -3
  39. package/lib/node/index.d.ts +2 -0
  40. package/lib/node/index.d.ts.map +1 -1
  41. package/lib/node/index.js +3 -0
  42. package/lib/node/jupiter/jupiterClient.d.ts +31 -27
  43. package/lib/node/jupiter/jupiterClient.d.ts.map +1 -1
  44. package/lib/node/jupiter/jupiterClient.js +61 -35
  45. package/lib/node/math/amm.d.ts +6 -5
  46. package/lib/node/math/amm.d.ts.map +1 -1
  47. package/lib/node/math/amm.js +39 -19
  48. package/lib/node/math/margin.d.ts +12 -10
  49. package/lib/node/math/margin.d.ts.map +1 -1
  50. package/lib/node/math/margin.js +16 -14
  51. package/lib/node/math/superStake.d.ts +9 -9
  52. package/lib/node/math/superStake.d.ts.map +1 -1
  53. package/lib/node/math/superStake.js +8 -8
  54. package/lib/node/swap/UnifiedSwapClient.d.ts +38 -76
  55. package/lib/node/swap/UnifiedSwapClient.d.ts.map +1 -1
  56. package/lib/node/swap/UnifiedSwapClient.js +46 -117
  57. package/lib/node/swap/routeInstructions.d.ts +20 -0
  58. package/lib/node/swap/routeInstructions.d.ts.map +1 -0
  59. package/lib/node/swap/routeInstructions.js +43 -0
  60. package/lib/node/swap/types.d.ts +197 -0
  61. package/lib/node/swap/types.d.ts.map +1 -0
  62. package/lib/node/swap/types.js +88 -0
  63. package/lib/node/titan/titanClient.d.ts +32 -68
  64. package/lib/node/titan/titanClient.d.ts.map +1 -1
  65. package/lib/node/titan/titanClient.js +128 -102
  66. package/lib/node/types.d.ts +2 -0
  67. package/lib/node/types.d.ts.map +1 -1
  68. package/lib/node/user.d.ts +16 -18
  69. package/lib/node/user.d.ts.map +1 -1
  70. package/lib/node/user.js +24 -26
  71. package/lib/node/velocityClient.d.ts +122 -101
  72. package/lib/node/velocityClient.d.ts.map +1 -1
  73. package/lib/node/velocityClient.js +221 -289
  74. package/package.json +1 -1
@@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.JupiterClient = exports.RECOMMENDED_JUPITER_API = exports.LEGACY_JUPITER_API = exports.RECOMMENDED_JUPITER_API_VERSION = void 0;
7
7
  const web3_js_1 = require("@solana/web3.js");
8
8
  const node_fetch_1 = __importDefault(require("node-fetch"));
9
+ const routeInstructions_1 = require("../swap/routeInstructions");
10
+ const types_1 = require("../swap/types");
9
11
  exports.RECOMMENDED_JUPITER_API_VERSION = '/v1';
10
12
  /** @deprecated Use RECOMMENDED_JUPITER_API instead. lite-api.jup.ag requires migration to api.jup.ag with API key. */
11
13
  exports.LEGACY_JUPITER_API = 'https://lite-api.jup.ag/swap';
@@ -18,7 +20,8 @@ class JupiterClient {
18
20
  * @param apiKey - API key for Jupiter API. Required for api.jup.ag (free tier available at https://portal.jup.ag)
19
21
  */
20
22
  constructor({ connection, url, apiKey, }) {
21
- this.lookupTableCahce = new Map();
23
+ this.providerName = 'jupiter';
24
+ this.lookupTableCache = new Map();
22
25
  this.connection = connection;
23
26
  this.url = url !== null && url !== void 0 ? url : exports.RECOMMENDED_JUPITER_API;
24
27
  this.apiKey = apiKey;
@@ -45,8 +48,7 @@ class JupiterClient {
45
48
  * @param swapMode the swap mode (ExactIn or ExactOut)
46
49
  * @param onlyDirectRoutes whether to only return direct routes
47
50
  */
48
- async getQuote({ inputMint, outputMint, amount, maxAccounts = 50, // 50 is an estimated amount with buffer
49
- slippageBps = 50, swapMode = 'ExactIn', onlyDirectRoutes = false, excludeDexes, autoSlippage = false, maxAutoSlippageBps, usdEstimate, }) {
51
+ async getQuote({ inputMint, outputMint, amount, maxAccounts = types_1.DEFAULT_SWAP_MAX_ACCOUNTS, slippageBps = 50, swapMode = 'ExactIn', onlyDirectRoutes = false, excludeDexes, autoSlippage = false, maxAutoSlippageBps, usdEstimate, }) {
50
52
  var _a;
51
53
  if (autoSlippage && maxAutoSlippageBps === undefined) {
52
54
  throw new Error('JupiterClient.getQuote: maxAutoSlippageBps is required when autoSlippage is enabled');
@@ -94,19 +96,25 @@ class JupiterClient {
94
96
  if (!quote.inputMint || !quote.outputMint || !quote.outAmount) {
95
97
  throw new Error('Jupiter quote failed: response is missing route fields');
96
98
  }
97
- return quote;
99
+ // Jupiter's /swap endpoint takes the quote body back verbatim, so the
100
+ // quote is its own route payload.
101
+ return (0, types_1.buildSwapQuote)(quote, { provider: 'jupiter', quote });
98
102
  }
99
103
  /**
100
104
  * Get a swap transaction for quote
101
- * @param quoteResponse quote to perform swap
105
+ * @param quote quote to perform swap, from {@link getQuote}
102
106
  * @param userPublicKey the signer's wallet public key
103
- * @param slippageBps the slippage tolerance in basis points
107
+ *
108
+ * Always builds at the quote's own slippage — the price the caller was
109
+ * shown. Re-quote to change it rather than overriding it here.
104
110
  */
105
- async getSwap({ quote, userPublicKey, slippageBps = 50, }) {
111
+ async getSwap({ quote, userPublicKey, }) {
106
112
  var _a;
107
113
  if (!quote) {
108
114
  throw new Error('Jupiter swap quote not provided. Please try again.');
109
115
  }
116
+ // `providerRoute` is our own wrapper, not part of Jupiter's quote body.
117
+ const { providerRoute: _providerRoute, ...quoteResponse } = quote;
110
118
  const apiVersionParam = this.url === exports.RECOMMENDED_JUPITER_API || this.url === exports.LEGACY_JUPITER_API
111
119
  ? exports.RECOMMENDED_JUPITER_API_VERSION
112
120
  : '';
@@ -114,9 +122,9 @@ class JupiterClient {
114
122
  method: 'POST',
115
123
  headers: this.getHeaders('application/json'),
116
124
  body: JSON.stringify({
117
- quoteResponse: quote,
125
+ quoteResponse,
118
126
  userPublicKey,
119
- slippageBps,
127
+ slippageBps: quoteResponse.slippageBps,
120
128
  }),
121
129
  })).json();
122
130
  if (!('swapTransaction' in resp)) {
@@ -131,6 +139,41 @@ class JupiterClient {
131
139
  throw new Error('Something went wrong with creating the Jupiter swap transaction. Please try again.');
132
140
  }
133
141
  }
142
+ /**
143
+ * The standalone transaction Jupiter's `/swap` endpoint returns, setup and
144
+ * teardown included.
145
+ * @throws If the quote came from a different provider or a different wallet.
146
+ */
147
+ async getSwapTransaction({ quote, userPublicKey, }) {
148
+ const jupiterQuote = (0, types_1.expectProviderRoute)(quote, 'jupiter', userPublicKey)
149
+ .quote;
150
+ return this.getSwap({ quote: jupiterQuote, userPublicKey });
151
+ }
152
+ /**
153
+ * Builds the route instructions for a quote returned by {@link getQuote}.
154
+ *
155
+ * The quote carries its own route payload, so this reads no client state
156
+ * and two quotes in flight can never be confused for one another. The swap
157
+ * is built at the slippage the quote was priced at — re-quote to change it.
158
+ * @throws If the quote came from a different provider or a different wallet.
159
+ */
160
+ async getRouteInstructions({ quote, userPublicKey, }) {
161
+ const jupiterQuote = (0, types_1.expectProviderRoute)(quote, 'jupiter', userPublicKey)
162
+ .quote;
163
+ const transaction = await this.getSwap({
164
+ quote: jupiterQuote,
165
+ userPublicKey,
166
+ });
167
+ const { transactionMessage, lookupTables } = await this.getTransactionMessageAndLookupTables({ transaction });
168
+ return {
169
+ instructions: (0, routeInstructions_1.filterRouteInstructions)({
170
+ instructions: transactionMessage.instructions,
171
+ inputMint: new web3_js_1.PublicKey(quote.inputMint),
172
+ outputMint: new web3_js_1.PublicKey(quote.outputMint),
173
+ }),
174
+ lookupTables,
175
+ };
176
+ }
134
177
  /**
135
178
  * Get the transaction message and lookup tables for a transaction
136
179
  * @param transaction
@@ -149,7 +192,7 @@ class JupiterClient {
149
192
  };
150
193
  }
151
194
  async getLookupTable(accountKey) {
152
- const cached = this.lookupTableCahce.get(accountKey.toString());
195
+ const cached = this.lookupTableCache.get(accountKey.toString());
153
196
  if (cached !== undefined) {
154
197
  return cached;
155
198
  }
@@ -159,36 +202,19 @@ class JupiterClient {
159
202
  }
160
203
  // Populate the cache — without this every route re-fetches the same tables,
161
204
  // which is a large share of the RPC calls a swap makes.
162
- this.lookupTableCahce.set(accountKey.toString(), lookupTable);
205
+ this.lookupTableCache.set(accountKey.toString(), lookupTable);
163
206
  return lookupTable;
164
207
  }
165
208
  /**
166
- * Get the jupiter instructions from transaction by filtering out instructions to compute budget and associated token programs
167
- * @param transactionMessage the transaction message
168
- * @param inputMint the input mint
169
- * @param outputMint the output mint
209
+ * Strips the setup/teardown Jupiter wraps around its route.
210
+ * @deprecated Use {@link getRouteInstructions}, which quotes and filters in
211
+ * one step. Kept for callers holding a decompiled message of their own.
170
212
  */
171
213
  getJupiterInstructions({ transactionMessage, inputMint, outputMint, }) {
172
- return transactionMessage.instructions.filter((instruction) => {
173
- if (instruction.programId.toString() ===
174
- 'ComputeBudget111111111111111111111111111111') {
175
- return false;
176
- }
177
- if (instruction.programId.toString() ===
178
- 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') {
179
- return false;
180
- }
181
- if (instruction.programId.toString() === '11111111111111111111111111111111') {
182
- return false;
183
- }
184
- if (instruction.programId.toString() ===
185
- 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL') {
186
- const mint = instruction.keys[3].pubkey;
187
- if (mint.equals(inputMint) || mint.equals(outputMint)) {
188
- return false;
189
- }
190
- }
191
- return true;
214
+ return (0, routeInstructions_1.filterRouteInstructions)({
215
+ instructions: transactionMessage.instructions,
216
+ inputMint,
217
+ outputMint,
192
218
  });
193
219
  }
194
220
  }
@@ -327,15 +327,16 @@ export declare function calculateSpreadBN(baseSpread: number, lastOracleReserveP
327
327
  * Convenience wrapper around `calculateSpreadBN` that derives its lower-level inputs
328
328
  * (reserve price, oracle-vs-reserve spread, live oracle std, and confidence interval) from
329
329
  * `amm`/`marketStats`/`oraclePriceData` directly, then applies the market's manual
330
- * `ammSpreadAdjustment` (%, shrink if negative/grow if positive, floored at 1) on top. Returns
331
- * `[baseSpread/2, baseSpread/2]` unchanged (no dynamic widening) if `baseSpread` or
332
- * `curveUpdateIntensity` is zero.
330
+ * `ammSpreadAdjustment` (%, shrink if negative/grow if positive, floored at 1) on top.
331
+ * Mirrors `update_spreads` in `vlp/amm/math/spread.rs`: the dynamic spread is computed
332
+ * whenever `curveUpdateIntensity` is nonzero, and only a zero `curveUpdateIntensity`
333
+ * falls back to `[baseSpread/2, baseSpread/2]` (truncated).
333
334
  * @param amm AMM state to price the spread for.
334
335
  * @param marketStats Market stats needed for volatility/funding-bias inputs.
335
- * @param oraclePriceData Current oracle price data; required unless `baseSpread`/`curveUpdateIntensity` are both zero.
336
+ * @param oraclePriceData Current oracle price data; required unless `curveUpdateIntensity` is zero.
336
337
  * @param now Current unix timestamp (seconds); defaults to wall-clock time if omitted.
337
338
  * @param reservePrice Current AMM reserve price, PRICE_PRECISION (1e6); computed from `amm`'s reserves if omitted.
338
- * @throws if `oraclePriceData` is omitted while `baseSpread` and `curveUpdateIntensity` are both nonzero.
339
+ * @throws if `oraclePriceData` is omitted while `curveUpdateIntensity` is nonzero.
339
340
  * @returns `[longSpread, shortSpread]`, both BID_ASK_SPREAD_PRECISION (1e6) fraction-of-price units.
340
341
  */
341
342
  export declare function calculateSpread(amm: AMM, marketStats: MarketStats, oraclePriceData?: Pick<OraclePriceData, 'price' | 'confidence'>, now?: BN, reservePrice?: BN): [number, number];
@@ -699,27 +699,57 @@ function calculateSpreadBN(baseSpread, lastOracleReservePriceSpreadPct, lastOrac
699
699
  return [longSpread, shortSpread];
700
700
  }
701
701
  exports.calculateSpreadBN = calculateSpreadBN;
702
+ /**
703
+ * Applies the market's manual `ammSpreadAdjustment` (%, grow if positive / shrink if
704
+ * negative, floored at 1) to an already-computed spread pair. Mirrors the tail of
705
+ * `update_spreads` in `vlp/amm/math/spread.rs`, which applies it to the frozen-curve
706
+ * branch as well as the dynamic one, and rounds as integer math (ceil when growing,
707
+ * floor when shrinking).
708
+ * @param amm AMM state holding `ammSpreadAdjustment`.
709
+ * @param longSpread Long-side spread before adjustment.
710
+ * @param shortSpread Short-side spread before adjustment.
711
+ * @returns `[longSpread, shortSpread]` after adjustment.
712
+ */
713
+ function applyAmmSpreadAdjustment(amm, longSpread, shortSpread) {
714
+ if (amm.ammSpreadAdjustment > 0) {
715
+ const grow = (spread) => Math.max(spread + Math.ceil((spread * amm.ammSpreadAdjustment) / 100), 1);
716
+ return [grow(longSpread), grow(shortSpread)];
717
+ }
718
+ if (amm.ammSpreadAdjustment < 0) {
719
+ const shrink = (spread) => Math.max(spread - Math.floor((spread * -amm.ammSpreadAdjustment) / 100), 1);
720
+ return [shrink(longSpread), shrink(shortSpread)];
721
+ }
722
+ return [longSpread, shortSpread];
723
+ }
702
724
  /**
703
725
  * Convenience wrapper around `calculateSpreadBN` that derives its lower-level inputs
704
726
  * (reserve price, oracle-vs-reserve spread, live oracle std, and confidence interval) from
705
727
  * `amm`/`marketStats`/`oraclePriceData` directly, then applies the market's manual
706
- * `ammSpreadAdjustment` (%, shrink if negative/grow if positive, floored at 1) on top. Returns
707
- * `[baseSpread/2, baseSpread/2]` unchanged (no dynamic widening) if `baseSpread` or
708
- * `curveUpdateIntensity` is zero.
728
+ * `ammSpreadAdjustment` (%, shrink if negative/grow if positive, floored at 1) on top.
729
+ * Mirrors `update_spreads` in `vlp/amm/math/spread.rs`: the dynamic spread is computed
730
+ * whenever `curveUpdateIntensity` is nonzero, and only a zero `curveUpdateIntensity`
731
+ * falls back to `[baseSpread/2, baseSpread/2]` (truncated).
709
732
  * @param amm AMM state to price the spread for.
710
733
  * @param marketStats Market stats needed for volatility/funding-bias inputs.
711
- * @param oraclePriceData Current oracle price data; required unless `baseSpread`/`curveUpdateIntensity` are both zero.
734
+ * @param oraclePriceData Current oracle price data; required unless `curveUpdateIntensity` is zero.
712
735
  * @param now Current unix timestamp (seconds); defaults to wall-clock time if omitted.
713
736
  * @param reservePrice Current AMM reserve price, PRICE_PRECISION (1e6); computed from `amm`'s reserves if omitted.
714
- * @throws if `oraclePriceData` is omitted while `baseSpread` and `curveUpdateIntensity` are both nonzero.
737
+ * @throws if `oraclePriceData` is omitted while `curveUpdateIntensity` is nonzero.
715
738
  * @returns `[longSpread, shortSpread]`, both BID_ASK_SPREAD_PRECISION (1e6) fraction-of-price units.
716
739
  */
717
740
  function calculateSpread(amm, marketStats, oraclePriceData, now, reservePrice) {
718
- if (amm.baseSpread == 0 || amm.curveUpdateIntensity == 0) {
719
- return [amm.baseSpread / 2, amm.baseSpread / 2];
741
+ // On chain the dynamic spread is computed whenever curveUpdateIntensity > 0; a
742
+ // baseSpread of 0 does NOT disable it, it only lowers the floor that the vol
743
+ // spread is maxed against. Short-circuiting on baseSpread == 0 made the SDK
744
+ // report a zero-width vAMM spread on markets configured with baseSpread 0,
745
+ // while the program was quoting an inventory-skewed spread of >10%.
746
+ if (amm.curveUpdateIntensity == 0) {
747
+ // integer division on chain: `base_spread.safe_div(2)`
748
+ const halfBaseSpread = Math.floor(amm.baseSpread / 2);
749
+ return applyAmmSpreadAdjustment(amm, halfBaseSpread, halfBaseSpread);
720
750
  }
721
751
  if (!oraclePriceData) {
722
- throw new Error('calculateSpread: oraclePriceData is required when baseSpread and curveUpdateIntensity are nonzero');
752
+ throw new Error('calculateSpread: oraclePriceData is required when curveUpdateIntensity is nonzero');
723
753
  }
724
754
  if (!reservePrice) {
725
755
  reservePrice = calculatePrice(amm.baseAssetReserve, amm.quoteAssetReserve, amm.pegMultiplier);
@@ -733,17 +763,7 @@ function calculateSpread(amm, marketStats, oraclePriceData, now, reservePrice) {
733
763
  const liveOracleStd = (0, oracles_1.calculateLiveOracleStd)(marketStats, oraclePriceData, now);
734
764
  const confIntervalPct = (0, oracles_1.getNewOracleConfPct)(marketStats, oraclePriceData, reservePrice, now);
735
765
  const spreads = calculateSpreadBN(amm.baseSpread, targetMarkSpreadPct, confIntervalPct, amm.maxSpread, amm.quoteAssetReserve, amm.terminalQuoteAssetReserve, amm.pegMultiplier, amm.baseAssetAmountWithAmm, reservePrice, amm.totalFeeMinusDistributions, amm.netRevenueSinceLastFunding, amm.baseAssetReserve, amm.minBaseAssetReserve, amm.maxBaseAssetReserve, marketStats.markStd, liveOracleStd, marketStats.longIntensityVolume, marketStats.shortIntensityVolume, marketStats.volume24H, amm.ammInventorySpreadAdjustment, marketStats.last24HAvgFundingRate, marketStats.lastFundingOracleTwap, amm.fundingBiasSensitivity);
736
- let longSpread = spreads[0];
737
- let shortSpread = spreads[1];
738
- if (amm.ammSpreadAdjustment > 0) {
739
- longSpread = Math.max(longSpread + (longSpread * amm.ammSpreadAdjustment) / 100, 1);
740
- shortSpread = Math.max(shortSpread + (shortSpread * amm.ammSpreadAdjustment) / 100, 1);
741
- }
742
- else if (amm.ammSpreadAdjustment < 0) {
743
- longSpread = Math.max(longSpread - (longSpread * -amm.ammSpreadAdjustment) / 100, 1);
744
- shortSpread = Math.max(shortSpread - (shortSpread * -amm.ammSpreadAdjustment) / 100, 1);
745
- }
746
- return [longSpread, shortSpread];
766
+ return applyAmmSpreadAdjustment(amm, spreads[0], spreads[1]);
747
767
  }
748
768
  exports.calculateSpread = calculateSpread;
749
769
  /**
@@ -104,13 +104,14 @@ export declare function calculateCollateralDepositRequiredForTrade(velocityClien
104
104
  * Minimal equity floor to carry along with a quote transfer of `amount` out
105
105
  * of a subaccount so the debited side ends at/above its buffered floor
106
106
  * (`equityFloor + equityFloorBuffer`): the first
107
- * `totalCollateral - (floor + buffer)` of the transfer carries no floor, the
107
+ * `netEquity - (floor + buffer)` of the transfer carries no floor, the
108
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.
109
+ * actually holds. `netEquity` is `User.getNetUsdValue()`, the metric the
110
+ * onchain floor checks use. Returns zero when no floor is set. The result
111
+ * never exceeds `amount`, so a credited side that met its own buffered floor
112
+ * before the transfer still meets it after. All values QUOTE_PRECISION.
112
113
  */
113
- export declare function calculateEquityFloorAutoDelta(amount: BN, totalCollateral: BN, equityFloor: BN, equityFloorBuffer: BN): BN;
114
+ export declare function calculateEquityFloorAutoDelta(amount: BN, netEquity: BN, equityFloor: BN, equityFloorBuffer: BN): BN;
114
115
  /**
115
116
  * Severity of a subaccount's equity relative to its floor, most to least
116
117
  * severe. `breached`: below the floor, the permissionless breaker can trip.
@@ -120,9 +121,10 @@ export declare function calculateEquityFloorAutoDelta(amount: BN, totalCollatera
120
121
  */
121
122
  export type EquityFloorLevel = 'breached' | 'critical' | 'warning' | 'healthy' | 'disabled';
122
123
  /**
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.
124
+ * Classifies `netEquity` (`User.getNetUsdValue()`) against the floor
125
+ * thresholds. Used by the `EquityFloorManager` and the equity-floor guard bot
126
+ * so both report the same levels. `warningBufferMultiple` scales the warning
127
+ * threshold above the floor (default 2: warn inside `floor + 2 * buffer`).
128
+ * All QUOTE_PRECISION.
127
129
  */
128
- export declare function getEquityFloorLevel(totalCollateral: BN, equityFloor: BN, equityFloorBuffer: BN, warningBufferMultiple?: number): EquityFloorLevel;
130
+ export declare function getEquityFloorLevel(netEquity: BN, equityFloor: BN, equityFloorBuffer: BN, warningBufferMultiple?: number): EquityFloorLevel;
@@ -214,37 +214,39 @@ exports.calculateCollateralDepositRequiredForTrade = calculateCollateralDepositR
214
214
  * Minimal equity floor to carry along with a quote transfer of `amount` out
215
215
  * of a subaccount so the debited side ends at/above its buffered floor
216
216
  * (`equityFloor + equityFloorBuffer`): the first
217
- * `totalCollateral - (floor + buffer)` of the transfer carries no floor, the
217
+ * `netEquity - (floor + buffer)` of the transfer carries no floor, the
218
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.
219
+ * actually holds. `netEquity` is `User.getNetUsdValue()`, the metric the
220
+ * onchain floor checks use. Returns zero when no floor is set. The result
221
+ * never exceeds `amount`, so a credited side that met its own buffered floor
222
+ * before the transfer still meets it after. All values QUOTE_PRECISION.
222
223
  */
223
- function calculateEquityFloorAutoDelta(amount, totalCollateral, equityFloor, equityFloorBuffer) {
224
+ function calculateEquityFloorAutoDelta(amount, netEquity, equityFloor, equityFloorBuffer) {
224
225
  if (equityFloor.lte(numericConstants_1.ZERO)) {
225
226
  return numericConstants_1.ZERO;
226
227
  }
227
- const excess = anchor_1.BN.max(totalCollateral.sub(equityFloor.add(equityFloorBuffer)), numericConstants_1.ZERO);
228
+ const excess = anchor_1.BN.max(netEquity.sub(equityFloor.add(equityFloorBuffer)), numericConstants_1.ZERO);
228
229
  return anchor_1.BN.min(anchor_1.BN.max(amount.sub(excess), numericConstants_1.ZERO), equityFloor);
229
230
  }
230
231
  exports.calculateEquityFloorAutoDelta = calculateEquityFloorAutoDelta;
231
232
  /**
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.
233
+ * Classifies `netEquity` (`User.getNetUsdValue()`) against the floor
234
+ * thresholds. Used by the `EquityFloorManager` and the equity-floor guard bot
235
+ * so both report the same levels. `warningBufferMultiple` scales the warning
236
+ * threshold above the floor (default 2: warn inside `floor + 2 * buffer`).
237
+ * All QUOTE_PRECISION.
236
238
  */
237
- function getEquityFloorLevel(totalCollateral, equityFloor, equityFloorBuffer, warningBufferMultiple = 2) {
239
+ function getEquityFloorLevel(netEquity, equityFloor, equityFloorBuffer, warningBufferMultiple = 2) {
238
240
  if (equityFloor.lte(numericConstants_1.ZERO)) {
239
241
  return 'disabled';
240
242
  }
241
- if (totalCollateral.lt(equityFloor)) {
243
+ if (netEquity.lt(equityFloor)) {
242
244
  return 'breached';
243
245
  }
244
- if (totalCollateral.lt(equityFloor.add(equityFloorBuffer))) {
246
+ if (netEquity.lt(equityFloor.add(equityFloorBuffer))) {
245
247
  return 'critical';
246
248
  }
247
- if (totalCollateral.lt(equityFloor.add(equityFloorBuffer.muln(warningBufferMultiple)))) {
249
+ if (netEquity.lt(equityFloor.add(equityFloorBuffer.muln(warningBufferMultiple)))) {
248
250
  return 'warning';
249
251
  }
250
252
  return 'healthy';
@@ -1,5 +1,5 @@
1
1
  import { AddressLookupTableAccount, PublicKey, TransactionInstruction } from '@solana/web3.js';
2
- import { JupiterClient, QuoteResponse } from '../jupiter/jupiterClient';
2
+ import { JupiterClient, JupiterSwapQuote } from '../jupiter/jupiterClient';
3
3
  import { VelocityClient } from '../velocityClient';
4
4
  import { BN } from '../isomorphic/anchor';
5
5
  import { User } from '../user';
@@ -61,7 +61,7 @@ export declare function fetchBSolVelocityEmissions(): Promise<fetch.Response>;
61
61
  * @param {boolean} [params.forceMarinade] - Force the direct Marinade stake path over a Jupiter
62
62
  * swap even if Jupiter would be cheaper (market index 2 only)
63
63
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
64
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse instead of
64
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse instead of
65
65
  * fetching a fresh one
66
66
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
67
67
  * method: 'jupiter' | 'marinade'; price?: number }>} The instructions to submit, any address
@@ -78,7 +78,7 @@ export declare function findBestSuperStakeIxs({ marketIndex, amount, jupiterClie
78
78
  userAccountPublicKey?: PublicKey;
79
79
  forceMarinade?: boolean;
80
80
  onlyDirectRoutes?: boolean;
81
- jupiterQuote?: QuoteResponse;
81
+ jupiterQuote?: JupiterSwapQuote;
82
82
  }): Promise<{
83
83
  ixs: TransactionInstruction[];
84
84
  lookupTables: AddressLookupTableAccount[];
@@ -100,7 +100,7 @@ export declare function findBestSuperStakeIxs({ marketIndex, amount, jupiterClie
100
100
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
101
101
  * @param {boolean} [params.forceMarinade] - Force the Marinade path regardless of Jupiter pricing
102
102
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
103
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
103
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
104
104
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
105
105
  * method: 'jupiter' | 'marinade'; price: number }>} The chosen route's instructions, required
106
106
  * lookup tables, the method used, and the mSOL/SOL price used for the decision
@@ -113,7 +113,7 @@ export declare function findBestMSolSuperStakeIxs({ amount, jupiterClient, veloc
113
113
  userAccountPublicKey?: PublicKey;
114
114
  forceMarinade?: boolean;
115
115
  onlyDirectRoutes?: boolean;
116
- jupiterQuote?: QuoteResponse;
116
+ jupiterQuote?: JupiterSwapQuote;
117
117
  }): Promise<{
118
118
  ixs: TransactionInstruction[];
119
119
  lookupTables: AddressLookupTableAccount[];
@@ -130,7 +130,7 @@ export declare function findBestMSolSuperStakeIxs({ amount, jupiterClient, veloc
130
130
  * @param {VelocityClient} params.velocityClient - Velocity client
131
131
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
132
132
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
133
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
133
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
134
134
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
135
135
  * method: 'jupiter' | 'marinade'; price?: number }>} Always resolves with `method: 'jupiter'`
136
136
  */
@@ -140,7 +140,7 @@ export declare function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, ve
140
140
  velocityClient: VelocityClient;
141
141
  userAccountPublicKey?: PublicKey;
142
142
  onlyDirectRoutes?: boolean;
143
- jupiterQuote?: QuoteResponse;
143
+ jupiterQuote?: JupiterSwapQuote;
144
144
  }): Promise<{
145
145
  ixs: TransactionInstruction[];
146
146
  lookupTables: AddressLookupTableAccount[];
@@ -161,7 +161,7 @@ export declare function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, ve
161
161
  * @param {VelocityClient} params.velocityClient - Velocity client
162
162
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
163
163
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
164
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
164
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
165
165
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
166
166
  * method: 'jupiter' | 'marinade' }>} Always resolves with `method: 'jupiter'`
167
167
  */
@@ -173,7 +173,7 @@ export declare function findBestLstSuperStakeIxs({ amount, jupiterClient, veloci
173
173
  velocityClient: VelocityClient;
174
174
  userAccountPublicKey?: PublicKey;
175
175
  onlyDirectRoutes?: boolean;
176
- jupiterQuote?: QuoteResponse;
176
+ jupiterQuote?: JupiterSwapQuote;
177
177
  }): Promise<{
178
178
  ixs: TransactionInstruction[];
179
179
  lookupTables: AddressLookupTableAccount[];
@@ -49,7 +49,7 @@ exports.fetchBSolVelocityEmissions = fetchBSolVelocityEmissions;
49
49
  * @param {boolean} [params.forceMarinade] - Force the direct Marinade stake path over a Jupiter
50
50
  * swap even if Jupiter would be cheaper (market index 2 only)
51
51
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
52
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse instead of
52
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse instead of
53
53
  * fetching a fresh one
54
54
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
55
55
  * method: 'jupiter' | 'marinade'; price?: number }>} The instructions to submit, any address
@@ -112,7 +112,7 @@ exports.findBestSuperStakeIxs = findBestSuperStakeIxs;
112
112
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
113
113
  * @param {boolean} [params.forceMarinade] - Force the Marinade path regardless of Jupiter pricing
114
114
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
115
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
115
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
116
116
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
117
117
  * method: 'jupiter' | 'marinade'; price: number }>} The chosen route's instructions, required
118
118
  * lookup tables, the method used, and the mSOL/SOL price used for the decision
@@ -155,10 +155,10 @@ async function findBestMSolSuperStakeIxs({ amount, jupiterClient, velocityClient
155
155
  };
156
156
  }
157
157
  else {
158
- const { ixs, lookupTables } = await velocityClient.getJupiterSwapIxV6({
158
+ const { ixs, lookupTables } = await velocityClient.getProviderSwapIx({
159
159
  inMarketIndex: 1,
160
160
  outMarketIndex: 2,
161
- jupiterClient,
161
+ swapProvider: jupiterClient,
162
162
  amount,
163
163
  userAccountPublicKey,
164
164
  onlyDirectRoutes,
@@ -183,7 +183,7 @@ exports.findBestMSolSuperStakeIxs = findBestMSolSuperStakeIxs;
183
183
  * @param {VelocityClient} params.velocityClient - Velocity client
184
184
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
185
185
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
186
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
186
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
187
187
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
188
188
  * method: 'jupiter' | 'marinade'; price?: number }>} Always resolves with `method: 'jupiter'`
189
189
  */
@@ -214,15 +214,15 @@ exports.findBestJitoSolSuperStakeIxs = findBestJitoSolSuperStakeIxs;
214
214
  * @param {VelocityClient} params.velocityClient - Velocity client
215
215
  * @param {PublicKey} [params.userAccountPublicKey] - The target sub-account
216
216
  * @param {boolean} [params.onlyDirectRoutes] - Restrict Jupiter routing to direct swaps only
217
- * @param {QuoteResponse} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
217
+ * @param {JupiterSwapQuote} [params.jupiterQuote] - A pre-fetched Jupiter quote to reuse
218
218
  * @return {Promise<{ ixs: TransactionInstruction[]; lookupTables: AddressLookupTableAccount[];
219
219
  * method: 'jupiter' | 'marinade' }>} Always resolves with `method: 'jupiter'`
220
220
  */
221
221
  async function findBestLstSuperStakeIxs({ amount, jupiterClient, velocityClient, userAccountPublicKey, onlyDirectRoutes, lstMarketIndex, jupiterQuote, }) {
222
- const { ixs, lookupTables } = await velocityClient.getJupiterSwapIxV6({
222
+ const { ixs, lookupTables } = await velocityClient.getProviderSwapIx({
223
223
  inMarketIndex: 1,
224
224
  outMarketIndex: lstMarketIndex,
225
- jupiterClient,
225
+ swapProvider: jupiterClient,
226
226
  amount,
227
227
  userAccountPublicKey,
228
228
  onlyDirectRoutes,
@@ -1,66 +1,23 @@
1
- import { Connection, PublicKey, TransactionMessage, AddressLookupTableAccount, VersionedTransaction, TransactionInstruction } from '@solana/web3.js';
2
- import { BN } from '../isomorphic/anchor';
1
+ import { Connection, VersionedTransaction } from '@solana/web3.js';
3
2
  import { JupiterClient } from '../jupiter/jupiterClient';
4
3
  import { TitanClient } from '../titan/titanClient';
5
- export type SwapMode = 'ExactIn' | 'ExactOut';
6
- export type SwapClientType = 'jupiter' | 'titan';
4
+ import { GetRouteInstructionsParams, SwapClientType, SwapProvider, SwapQuote, SwapQuoteParams, SwapRouteInstructions } from './types';
5
+ export type { GetRouteInstructionsParams, SwapProviderRoute, SwapClientType, SwapMode, SwapProvider, SwapQuote, SwapQuoteParams, SwapRouteInstructions, UnifiedQuoteResponse, } from './types';
6
+ /** Byte budget handed to a swap provider for the route portion of the tx. */
7
+ export declare const DEFAULT_ROUTE_SIZE_CONSTRAINT: number;
7
8
  /**
8
- * Unified quote response interface that combines properties from both Jupiter and Titan
9
- * This provides a consistent interface while allowing for provider-specific fields
9
+ * Routes swap calls to the configured provider.
10
+ *
11
+ * Intentionally thin: it picks a provider and forwards. Anything that varies
12
+ * between Jupiter and Titan belongs in the provider, behind
13
+ * {@link SwapProvider} — branching on the provider here is how the two paths
14
+ * drifted apart previously, since nothing forced them to keep the same
15
+ * semantics.
10
16
  */
11
- export interface UnifiedQuoteResponse {
12
- inputMint: string;
13
- inAmount: string;
14
- outputMint: string;
15
- outAmount: string;
16
- swapMode: SwapMode;
17
- slippageBps: number;
18
- routePlan: Array<{
19
- swapInfo: any;
20
- percent: number;
21
- }>;
22
- otherAmountThreshold?: string;
23
- priceImpactPct?: string;
24
- platformFee?: {
25
- amount?: string;
26
- feeBps?: number;
27
- };
28
- contextSlot?: number;
29
- timeTaken?: number;
30
- error?: string;
31
- errorCode?: string;
32
- }
33
- export interface SwapQuoteParams {
34
- inputMint: PublicKey;
35
- outputMint: PublicKey;
36
- amount: BN;
37
- userPublicKey?: PublicKey;
38
- maxAccounts?: number;
39
- slippageBps?: number;
40
- swapMode?: SwapMode;
41
- onlyDirectRoutes?: boolean;
42
- excludeDexes?: string[];
43
- sizeConstraint?: number;
44
- accountsLimitWritable?: number;
45
- autoSlippage?: boolean;
46
- maxAutoSlippageBps?: number;
47
- usdEstimate?: number;
48
- }
49
- export interface SwapTransactionParams {
50
- quote: UnifiedQuoteResponse;
51
- userPublicKey: PublicKey;
52
- slippageBps?: number;
53
- }
54
- export interface SwapTransactionResult {
55
- transaction?: VersionedTransaction;
56
- transactionMessage?: TransactionMessage;
57
- lookupTables?: AddressLookupTableAccount[];
58
- }
59
- export declare class UnifiedSwapClient {
17
+ export declare class UnifiedSwapClient implements SwapProvider {
60
18
  private client;
61
19
  private clientType;
62
20
  /**
63
- * Create a unified swap client
64
21
  * @param clientType - 'jupiter' or 'titan'
65
22
  * @param connection - Solana connection
66
23
  * @param authToken - For Titan: auth token (required when not using proxy). For Jupiter: API key (required for api.jup.ag, get free key at https://portal.jup.ag)
@@ -74,32 +31,37 @@ export declare class UnifiedSwapClient {
74
31
  url?: string;
75
32
  proxyUrl?: string;
76
33
  });
34
+ get providerName(): SwapClientType;
35
+ /**
36
+ * The configured client, seen only as {@link SwapProvider}.
37
+ *
38
+ * Forwarding through the interface rather than the concrete union is what
39
+ * makes goal of this class enforceable: a provider added to the union that
40
+ * implements only part of the contract fails to compile here, instead of
41
+ * resolving against whichever call signatures the union happens to share.
42
+ */
43
+ private get provider();
77
44
  /**
78
- * Get a swap quote from the underlying client
45
+ * Get a swap quote from the configured provider.
46
+ *
47
+ * Provider-specific fields on {@link SwapQuoteParams} are mapped by the
48
+ * provider, so the ones it doesn't recognise are simply ignored.
79
49
  */
80
- getQuote(params: SwapQuoteParams): Promise<UnifiedQuoteResponse>;
50
+ getQuote(params: SwapQuoteParams): Promise<SwapQuote>;
81
51
  /**
82
- * Get a swap transaction from the underlying client
52
+ * Builds the route instructions for a quote from {@link getQuote}, at the
53
+ * slippage that quote was priced at.
54
+ * @throws If the quote came from a different provider or a different wallet.
83
55
  */
84
- getSwap(params: SwapTransactionParams): Promise<SwapTransactionResult>;
56
+ getRouteInstructions(params: GetRouteInstructionsParams): Promise<SwapRouteInstructions>;
85
57
  /**
86
- * Get swap instructions from the underlying client (Jupiter or Titan)
87
- * This is the core swap logic without any context preparation
58
+ * Builds a standalone swap transaction for a quote from {@link getQuote},
59
+ * keeping the provider's own compute budget, token account creation and SOL
60
+ * wrapping. Use {@link getRouteInstructions} for a swap that runs inside
61
+ * velocity's `beginSwap`/`endSwap` bracket.
62
+ * @throws If the quote came from a different provider or a different wallet.
88
63
  */
89
- getSwapInstructions({ inputMint, outputMint, amount, userPublicKey, slippageBps, swapMode, onlyDirectRoutes, quote, sizeConstraint, }: {
90
- inputMint: PublicKey;
91
- outputMint: PublicKey;
92
- amount: BN;
93
- userPublicKey: PublicKey;
94
- slippageBps?: number;
95
- swapMode?: SwapMode;
96
- onlyDirectRoutes?: boolean;
97
- quote?: UnifiedQuoteResponse;
98
- sizeConstraint?: number;
99
- }): Promise<{
100
- instructions: TransactionInstruction[];
101
- lookupTables: AddressLookupTableAccount[];
102
- }>;
64
+ getSwapTransaction(params: GetRouteInstructionsParams): Promise<VersionedTransaction>;
103
65
  /**
104
66
  * Get the underlying client instance
105
67
  */