@velocity-exchange/sdk 0.7.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.
- package/lib/browser/adminClient.d.ts +35 -12
- package/lib/browser/adminClient.js +75 -22
- package/lib/browser/core/VelocityCore.d.ts +2 -0
- package/lib/browser/core/VelocityCore.js +1 -0
- package/lib/browser/core/instructions/trigger.d.ts +4 -0
- package/lib/browser/core/instructions/trigger.js +4 -0
- package/lib/browser/decode/user.js +3 -1
- package/lib/browser/equityFloorManager.d.ts +150 -0
- package/lib/browser/equityFloorManager.js +279 -0
- package/lib/browser/idl/velocity.d.ts +307 -43
- package/lib/browser/idl/velocity.json +308 -44
- package/lib/browser/index.d.ts +2 -0
- package/lib/browser/index.js +2 -0
- package/lib/browser/jupiter/jupiterClient.js +24 -3
- package/lib/browser/math/liquidation.d.ts +37 -2
- package/lib/browser/math/liquidation.js +44 -3
- package/lib/browser/math/margin.d.ts +26 -0
- package/lib/browser/math/margin.js +41 -1
- package/lib/browser/math/spotBalance.d.ts +13 -0
- package/lib/browser/math/spotBalance.js +43 -2
- package/lib/browser/swap/UnifiedSwapClient.js +17 -3
- package/lib/browser/titan/titanClient.d.ts +6 -0
- package/lib/browser/titan/titanClient.js +44 -13
- package/lib/browser/types.d.ts +15 -2
- package/lib/browser/types.js +2 -0
- package/lib/browser/user.d.ts +38 -11
- package/lib/browser/user.js +84 -33
- package/lib/browser/velocityClient.d.ts +37 -24
- package/lib/browser/velocityClient.js +56 -35
- package/lib/node/adminClient.d.ts +35 -12
- package/lib/node/adminClient.d.ts.map +1 -1
- package/lib/node/adminClient.js +75 -22
- package/lib/node/core/VelocityCore.d.ts +2 -0
- package/lib/node/core/VelocityCore.d.ts.map +1 -1
- package/lib/node/core/VelocityCore.js +1 -0
- package/lib/node/core/instructions/trigger.d.ts +4 -0
- package/lib/node/core/instructions/trigger.d.ts.map +1 -1
- package/lib/node/core/instructions/trigger.js +4 -0
- package/lib/node/decode/user.d.ts.map +1 -1
- package/lib/node/decode/user.js +3 -1
- package/lib/node/equityFloorManager.d.ts +151 -0
- package/lib/node/equityFloorManager.d.ts.map +1 -0
- package/lib/node/equityFloorManager.js +279 -0
- package/lib/node/idl/velocity.d.ts +307 -43
- package/lib/node/idl/velocity.d.ts.map +1 -1
- package/lib/node/idl/velocity.json +308 -44
- package/lib/node/index.d.ts +2 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +2 -0
- package/lib/node/jupiter/jupiterClient.d.ts.map +1 -1
- package/lib/node/jupiter/jupiterClient.js +24 -3
- package/lib/node/math/liquidation.d.ts +37 -2
- package/lib/node/math/liquidation.d.ts.map +1 -1
- package/lib/node/math/liquidation.js +44 -3
- package/lib/node/math/margin.d.ts +26 -0
- package/lib/node/math/margin.d.ts.map +1 -1
- package/lib/node/math/margin.js +41 -1
- package/lib/node/math/spotBalance.d.ts +13 -0
- package/lib/node/math/spotBalance.d.ts.map +1 -1
- package/lib/node/math/spotBalance.js +43 -2
- package/lib/node/swap/UnifiedSwapClient.d.ts.map +1 -1
- package/lib/node/swap/UnifiedSwapClient.js +17 -3
- package/lib/node/titan/titanClient.d.ts +6 -0
- package/lib/node/titan/titanClient.d.ts.map +1 -1
- package/lib/node/titan/titanClient.js +44 -13
- package/lib/node/types.d.ts +15 -2
- package/lib/node/types.d.ts.map +1 -1
- package/lib/node/types.js +2 -0
- package/lib/node/user.d.ts +38 -11
- package/lib/node/user.d.ts.map +1 -1
- package/lib/node/user.js +84 -33
- package/lib/node/velocityClient.d.ts +37 -24
- package/lib/node/velocityClient.d.ts.map +1 -1
- package/lib/node/velocityClient.js +56 -35
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"liquidation.d.ts","sourceRoot":"","sources":["../../../src/math/liquidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,sBAAsB,CAAC;AAe1C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,6CAA6C,CAC5D,cAAc,EAAE,EAAE,EAClB,WAAW,EAAE,MAAM,EACnB,cAAc,EAAE,MAAM,EACtB,gBAAgB,EAAE,MAAM,EACxB,WAAW,EAAE,EAAE,EACf,gBAAgB,EAAE,EAAE,GAClB,EAAE,GAAG,SAAS,CAqBhB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,+CAA+C,CAC9D,cAAc,EAAE,EAAE,EAClB,WAAW,EAAE,MAAM,EACnB,0BAA0B,EAAE,MAAM,EAClC,eAAe,EAAE,MAAM,EACvB,8BAA8B,EAAE,MAAM,EACtC,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,EAAE,EAClB,gBAAgB,EAAE,MAAM,GACtB,EAAE,GAAG,SAAS,CA8ChB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,kBAAkB,CACjC,cAAc,EAAE,EAAE,EAClB,mBAAmB,EAAE,EAAE,EACvB,WAAW,EAAE,MAAM,EACnB,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,EAAE,EACf,gBAAgB,EAAE,EAAE,EACpB,mBAAmB,EAAE,MAAM,GACzB,MAAM,CAgCR;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,kBAAkB,CACjC,cAAc,EAAE,EAAE,EAClB,WAAW,EAAE,EAAE,EACf,WAAW,EAAE,MAAM,EACnB,0BAA0B,EAAE,MAAM,EAClC,eAAe,EAAE,MAAM,EACvB,8BAA8B,EAAE,MAAM,EACtC,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,EAAE,EAClB,QAAQ,EAAE,MAAM,GACd,MAAM,CAuCR;AAED
|
|
1
|
+
{"version":3,"file":"liquidation.d.ts","sourceRoot":"","sources":["../../../src/math/liquidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,sBAAsB,CAAC;AAe1C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAA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AW,EAAE,EAAE,EACf,gBAAgB,EAAE,EAAE,EACpB,uBAAuB,EAAE,EAAE,GACzB,EAAE,CAQJ;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,0CAA0C,CACzD,WAAW,EAAE,EAAE,EACf,0BAA0B,EAAE,MAAM,EAClC,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,EAAE,EACd,eAAe,EAAE,EAAE,EACnB,8BAA8B,EAAE,MAAM,EACtC,iBAAiB,EAAE,MAAM,EACzB,cAAc,EAAE,EAAE,GAChB,EAAE,GAAG,SAAS,CAkDhB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CACzC,kBAAkB,EAAE,EAAE,EACtB,0BAA0B,EAAE,EAAE,EAC9B,cAAc,EAAE,EAAE,EAClB,IAAI,EAAE,EAAE,EACR,qBAAqB,EAAE,EAAE,EACzB,mBAAmB,EAAE,EAAE,EACvB,kBAAkB,UAAQ,GACxB,EAAE,CA+BJ;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAChC,sCAAsC,EAAE,EAAE,EAC1C,0BAA0B,EAAE,EAAE,GAC5B,EAAE,CAIJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getMarginShortage = exports.calculateMaxPctToLiquidate = exports.calculateAssetTransferForLiabilityTransfer = exports.calculateSpotIfFee = exports.calculatePerpIfFee = exports.calculateLiabilityTransferToCoverMarginShortage = exports.calculateBaseAssetAmountToCoverMarginShortage = void 0;
|
|
3
|
+
exports.getMarginShortage = exports.calculateMaxPctToLiquidate = exports.calculateAssetTransferForLiabilityTransfer = exports.calculateUserProtectiveLiabilityPrice = exports.calculateUserProtectiveAssetPrice = exports.calculateSpotIfFee = exports.calculatePerpIfFee = exports.calculateLiabilityTransferToCoverMarginShortage = exports.calculateBaseAssetAmountToCoverMarginShortage = void 0;
|
|
4
4
|
const anchor_1 = require("../isomorphic/anchor");
|
|
5
5
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
6
6
|
/**
|
|
@@ -188,6 +188,43 @@ function calculateSpotIfFee(marginShortage, tokenAmount, assetWeight, assetLiqui
|
|
|
188
188
|
return anchor_1.BN.min(new anchor_1.BN(maxIfFee), impliedIfFee).toNumber();
|
|
189
189
|
}
|
|
190
190
|
exports.calculateSpotIfFee = calculateSpotIfFee;
|
|
191
|
+
/**
|
|
192
|
+
* User-protective price at which a collateral (deposit) asset is seized when its oracle is
|
|
193
|
+
* margin-invalid (`StaleForMargin`/`TooUncertain`) but still acceptable for
|
|
194
|
+
* `VelocityAction::Liquidate`, mirroring `calculate_user_protective_asset_price` in
|
|
195
|
+
* `programs/velocity/src/math/liquidation.rs`. The program sizes the asset-conversion leg
|
|
196
|
+
* of spot and pnl-vs-spot liquidations (and the swap-liquidation worst-case price) with this
|
|
197
|
+
* instead of the raw oracle price whenever the deposit oracle fails the margin-calc validity
|
|
198
|
+
* gate — a stale or uncertain oracle can make an account liquidatable but cannot cheapen its
|
|
199
|
+
* collateral. Pass the result as `assetPrice` to `calculateAssetTransferForLiabilityTransfer`
|
|
200
|
+
* to predict on-chain transfer amounts in that case.
|
|
201
|
+
* @param oraclePrice Raw oracle price of the asset, PRICE_PRECISION (1e6).
|
|
202
|
+
* @param oracleConfidence Oracle confidence interval, PRICE_PRECISION (1e6).
|
|
203
|
+
* @param lastOraclePriceTwap5Min The asset spot market's `historicalOracleData.lastOraclePriceTwap5Min`, PRICE_PRECISION (1e6).
|
|
204
|
+
* @returns `max(oraclePrice, lastOraclePriceTwap5Min, oraclePrice + oracleConfidence)`, PRICE_PRECISION (1e6).
|
|
205
|
+
*/
|
|
206
|
+
function calculateUserProtectiveAssetPrice(oraclePrice, oracleConfidence, lastOraclePriceTwap5Min) {
|
|
207
|
+
return anchor_1.BN.max(anchor_1.BN.max(oraclePrice, lastOraclePriceTwap5Min), oraclePrice.add(oracleConfidence));
|
|
208
|
+
}
|
|
209
|
+
exports.calculateUserProtectiveAssetPrice = calculateUserProtectiveAssetPrice;
|
|
210
|
+
/**
|
|
211
|
+
* Liability-side counterpart of `calculateUserProtectiveAssetPrice`, mirroring
|
|
212
|
+
* `calculate_user_protective_liability_price` in
|
|
213
|
+
* `programs/velocity/src/math/liquidation.rs`. When the borrow (liability) oracle is
|
|
214
|
+
* margin-invalid, the program prices the repayment leg of spot and pnl-vs-spot liquidations
|
|
215
|
+
* (and the swap-liquidation worst-case price) at this instead of the raw oracle price, so an
|
|
216
|
+
* inflated stale/uncertain debt price cannot cheapen the collateral (or pnl) exchanged for
|
|
217
|
+
* it. Pass the result as `liabilityPrice` to `calculateAssetTransferForLiabilityTransfer` to
|
|
218
|
+
* predict on-chain transfer amounts in that case.
|
|
219
|
+
* @param oraclePrice Raw oracle price of the liability, PRICE_PRECISION (1e6).
|
|
220
|
+
* @param oracleConfidence Oracle confidence interval, PRICE_PRECISION (1e6).
|
|
221
|
+
* @param lastOraclePriceTwap5Min The liability spot market's `historicalOracleData.lastOraclePriceTwap5Min`, PRICE_PRECISION (1e6).
|
|
222
|
+
* @returns `min(oraclePrice, lastOraclePriceTwap5Min, oraclePrice - oracleConfidence)`, floored at 1, PRICE_PRECISION (1e6).
|
|
223
|
+
*/
|
|
224
|
+
function calculateUserProtectiveLiabilityPrice(oraclePrice, oracleConfidence, lastOraclePriceTwap5Min) {
|
|
225
|
+
return anchor_1.BN.max(anchor_1.BN.min(anchor_1.BN.min(oraclePrice, lastOraclePriceTwap5Min), oraclePrice.sub(oracleConfidence)), numericConstants_1.ONE);
|
|
226
|
+
}
|
|
227
|
+
exports.calculateUserProtectiveLiabilityPrice = calculateUserProtectiveLiabilityPrice;
|
|
191
228
|
/**
|
|
192
229
|
* Calculates how much of a liquidated user's collateral asset a liquidator receives in
|
|
193
230
|
* exchange for repaying `liabilityAmount` of a liability, mirroring
|
|
@@ -200,11 +237,15 @@ exports.calculateSpotIfFee = calculateSpotIfFee;
|
|
|
200
237
|
* @param assetAmount User's available balance of the asset being transferred, asset spot market's own token precision.
|
|
201
238
|
* @param assetLiquidationMultiplier Liquidation-time discount multiplier on the asset side, LIQUIDATION_FEE_PRECISION (1e6).
|
|
202
239
|
* @param assetDecimals Asset spot market's token decimals.
|
|
203
|
-
* @param assetPrice Oracle price of the asset, PRICE_PRECISION (1e6).
|
|
240
|
+
* @param assetPrice Oracle price of the asset, PRICE_PRECISION (1e6). When the asset oracle
|
|
241
|
+
* is margin-invalid, the program prices the seizure protectively — pass
|
|
242
|
+
* `calculateUserProtectiveAssetPrice(...)` instead of the raw oracle price to match.
|
|
204
243
|
* @param liabilityAmount Liability amount being repaid, liability spot market's own token precision.
|
|
205
244
|
* @param liabilityLiquidationMultiplier Liquidation-time premium multiplier on the liability side, LIQUIDATION_FEE_PRECISION (1e6).
|
|
206
245
|
* @param liabilityDecimals Liability spot market's token decimals.
|
|
207
|
-
* @param liabilityPrice Oracle price of the liability asset, PRICE_PRECISION (1e6).
|
|
246
|
+
* @param liabilityPrice Oracle price of the liability asset, PRICE_PRECISION (1e6). When the
|
|
247
|
+
* liability oracle is margin-invalid, the program prices the repayment protectively — pass
|
|
248
|
+
* `calculateUserProtectiveLiabilityPrice(...)` instead of the raw oracle price to match.
|
|
208
249
|
* @returns Asset amount to transfer to the liquidator, asset spot market's own token precision (floored at 1).
|
|
209
250
|
*/
|
|
210
251
|
function calculateAssetTransferForLiabilityTransfer(assetAmount, assetLiquidationMultiplier, assetDecimals, assetPrice, liabilityAmount, liabilityLiquidationMultiplier, liabilityDecimals, liabilityPrice) {
|
|
@@ -100,4 +100,30 @@ 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;
|
|
103
129
|
//# sourceMappingURL=margin.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"margin.d.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SAAS,GACT,UAAU,CAAC;AAEd;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,eAAe,EAAE,EAAE,EACnB,WAAW,EAAE,EAAE,EACf,iBAAiB,EAAE,EAAE,EACrB,qBAAqB,SAAI,GACvB,gBAAgB,CAkBlB"}
|
package/lib/node/math/margin.js
CHANGED
|
@@ -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;
|
|
@@ -241,6 +241,19 @@ export declare function calculateWithdrawLimit(spotMarket: SpotMarketAccount, no
|
|
|
241
241
|
currentDepositAmount: BN;
|
|
242
242
|
currentBorrowAmount: BN;
|
|
243
243
|
};
|
|
244
|
+
/**
|
|
245
|
+
* Mirror of the program's `calculate_max_deposit_token_amount`. Returns the max
|
|
246
|
+
* resulting deposit token amount permitted by the daily deposit cap: growth up
|
|
247
|
+
* to `maxDepositBpsPerDay` above the 24h deposit TWAP, but never below the
|
|
248
|
+
* deposit guard threshold. Returns null when the cap is disabled (pct == 0).
|
|
249
|
+
*/
|
|
250
|
+
export declare function calculateMaxDepositTokenAmount(depositTokenTwap: BN, depositGuardThreshold: BN, maxDepositBpsPerDay: number): BN | null;
|
|
251
|
+
/**
|
|
252
|
+
* Mirror of the program's `check_deposit_limits`. Returns true if the market's
|
|
253
|
+
* current deposit level is within the daily deposit cap (always true when the
|
|
254
|
+
* cap is disabled).
|
|
255
|
+
*/
|
|
256
|
+
export declare function checkDepositLimits(spotMarket: SpotMarketAccount): boolean;
|
|
244
257
|
/**
|
|
245
258
|
* Calculates the margin-weighted value of a spot deposit, mirroring the asset-side of the
|
|
246
259
|
* program's collateral valuation (`get_strict_token_value` + `get_asset_weight`). Uses the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spotBalance.d.ts","sourceRoot":"","sources":["../../../src/math/spotBalance.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,iBAAiB,EACjB,eAAe,EAEf,cAAc,EACd,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,EAAE,EAAE,MAAM,sBAAsB,CAAC;AAgB1C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"spotBalance.d.ts","sourceRoot":"","sources":["../../../src/math/spotBalance.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,iBAAiB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CAClC,CAsCA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,sBAAsB,CACrC,UAAU,EAAE,iBAAiB,EAC7B,GAAG,EAAE,EAAE,GACL;IACF,WAAW,EAAE,EAAE,CAAC;IAChB,aAAa,EAAE,EAAE,CAAC;IAClB,gBAAgB,EAAE,EAAE,CAAC;IACrB,eAAe,EAAE,EAAE,CAAC;IACpB,oBAAoB,EAAE,EAAE,CAAC;IACzB,mBAAmB,EAAE,EAAE,CAAC;CACxB,CA6HA;AAED;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAC7C,gBAAgB,EAAE,EAAE,EACpB,qBAAqB,EAAE,EAAE,EACzB,mBAAmB,EAAE,MAAM,GACzB,EAAE,GAAG,IAAI,CASX;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,iBAAiB,GAAG,OAAO,CAkBzE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,CAChC,WAAW,EAAE,EAAE,EACf,iBAAiB,EAAE,iBAAiB,EACpC,iBAAiB,EAAE,iBAAiB,EACpC,cAAc,EAAE,MAAM,EACtB,cAAc,CAAC,EAAE,cAAc,GAC7B,EAAE,CA8BJ;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACpC,WAAW,EAAE,EAAE,EACf,iBAAiB,EAAE,iBAAiB,EACpC,iBAAiB,EAAE,iBAAiB,EACpC,cAAc,EAAE,MAAM,EACtB,cAAc,CAAC,EAAE,cAAc,EAC/B,iBAAiB,CAAC,EAAE,EAAE,GACpB,EAAE,CAkCJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getSpotLiabilityValue = exports.getSpotAssetValue = exports.calculateWithdrawLimit = exports.calculateTokenUtilizationLimits = exports.calculateInterestAccumulated = exports.calculateBorrowRate = exports.calculateDepositRate = exports.calculateInterestRate = exports.calculateSpotMarketBorrowCapacity = exports.calculateUtilization = exports.calculateLiabilityWeight = exports.calculateScaledInitialAssetWeight = exports.calculateAssetWeight = exports.getTokenValue = exports.getStrictTokenValue = exports.getSignedTokenAmount = exports.getTokenAmount = exports.getBalance = void 0;
|
|
3
|
+
exports.getSpotLiabilityValue = exports.getSpotAssetValue = exports.checkDepositLimits = exports.calculateMaxDepositTokenAmount = exports.calculateWithdrawLimit = exports.calculateTokenUtilizationLimits = exports.calculateInterestAccumulated = exports.calculateBorrowRate = exports.calculateDepositRate = exports.calculateInterestRate = exports.calculateSpotMarketBorrowCapacity = exports.calculateUtilization = exports.calculateLiabilityWeight = exports.calculateScaledInitialAssetWeight = exports.calculateAssetWeight = exports.getTokenValue = exports.getStrictTokenValue = exports.getSignedTokenAmount = exports.getTokenAmount = exports.getBalance = void 0;
|
|
4
4
|
const types_1 = require("../types");
|
|
5
5
|
const anchor_1 = require("../isomorphic/anchor");
|
|
6
6
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
@@ -571,7 +571,14 @@ function calculateWithdrawLimit(spotMarket, now) {
|
|
|
571
571
|
else {
|
|
572
572
|
maxBorrowTokensTwap = anchor_1.BN.max(spotMarket.withdrawGuardThreshold, anchor_1.BN.min(anchor_1.BN.max(lesserDepositAmount.div(new anchor_1.BN(2)), borrowTokenTwapLive.add(lesserDepositAmount.div(new anchor_1.BN(3)))), lesserDepositAmount.sub(lesserDepositAmount.div(new anchor_1.BN(20))))); // isolated pools between 50-95% utilization with friction on twap in 33% increments
|
|
573
573
|
}
|
|
574
|
-
|
|
574
|
+
// 0 is treated as the default 25% (2500 bps) so markets created before the
|
|
575
|
+
// field existed keep prior behavior (mirrors calculate_min_deposit_token_amount).
|
|
576
|
+
// withdrawCircuitBreakerBps is in basis points (BPS_PRECISION = 10_000 = 100%).
|
|
577
|
+
const breakerPct = spotMarket.withdrawCircuitBreakerBps === 0
|
|
578
|
+
? numericConstants_2.BPS_PRECISION.divn(4)
|
|
579
|
+
: new anchor_1.BN(spotMarket.withdrawCircuitBreakerBps);
|
|
580
|
+
const maxDrop = depositTokenTwapLive.mul(breakerPct).div(numericConstants_2.BPS_PRECISION);
|
|
581
|
+
const minDepositTokensTwap = depositTokenTwapLive.sub(anchor_1.BN.max(maxDrop, anchor_1.BN.min(spotMarket.withdrawGuardThreshold, depositTokenTwapLive)));
|
|
575
582
|
const { minDepositTokensForUtilization, maxBorrowTokensForUtilization } = calculateTokenUtilizationLimits(marketDepositTokenAmount, marketBorrowTokenAmount, spotMarket);
|
|
576
583
|
const minDepositTokens = anchor_1.BN.max(minDepositTokensForUtilization, minDepositTokensTwap);
|
|
577
584
|
let maxBorrowTokens = anchor_1.BN.min(maxBorrowTokensForUtilization, maxBorrowTokensTwap);
|
|
@@ -599,6 +606,40 @@ function calculateWithdrawLimit(spotMarket, now) {
|
|
|
599
606
|
};
|
|
600
607
|
}
|
|
601
608
|
exports.calculateWithdrawLimit = calculateWithdrawLimit;
|
|
609
|
+
/**
|
|
610
|
+
* Mirror of the program's `calculate_max_deposit_token_amount`. Returns the max
|
|
611
|
+
* resulting deposit token amount permitted by the daily deposit cap: growth up
|
|
612
|
+
* to `maxDepositBpsPerDay` above the 24h deposit TWAP, but never below the
|
|
613
|
+
* deposit guard threshold. Returns null when the cap is disabled (pct == 0).
|
|
614
|
+
*/
|
|
615
|
+
function calculateMaxDepositTokenAmount(depositTokenTwap, depositGuardThreshold, maxDepositBpsPerDay) {
|
|
616
|
+
if (maxDepositBpsPerDay === 0) {
|
|
617
|
+
return null; // disabled
|
|
618
|
+
}
|
|
619
|
+
// maxDepositBpsPerDay is in basis points (BPS_PRECISION = 10_000 = 100%).
|
|
620
|
+
const maxIncrease = depositTokenTwap
|
|
621
|
+
.mul(new anchor_1.BN(maxDepositBpsPerDay))
|
|
622
|
+
.div(numericConstants_2.BPS_PRECISION);
|
|
623
|
+
return anchor_1.BN.max(depositTokenTwap.add(maxIncrease), depositGuardThreshold);
|
|
624
|
+
}
|
|
625
|
+
exports.calculateMaxDepositTokenAmount = calculateMaxDepositTokenAmount;
|
|
626
|
+
/**
|
|
627
|
+
* Mirror of the program's `check_deposit_limits`. Returns true if the market's
|
|
628
|
+
* current deposit level is within the daily deposit cap (always true when the
|
|
629
|
+
* cap is disabled).
|
|
630
|
+
*/
|
|
631
|
+
function checkDepositLimits(spotMarket) {
|
|
632
|
+
if (spotMarket.maxDepositBpsPerDay === 0) {
|
|
633
|
+
return true;
|
|
634
|
+
}
|
|
635
|
+
const depositTokenAmount = getTokenAmount(spotMarket.depositBalance, spotMarket, types_1.SpotBalanceType.DEPOSIT);
|
|
636
|
+
const maxDepositToken = calculateMaxDepositTokenAmount(spotMarket.depositTokenTwap, spotMarket.depositGuardThreshold, spotMarket.maxDepositBpsPerDay);
|
|
637
|
+
if (maxDepositToken === null) {
|
|
638
|
+
return true;
|
|
639
|
+
}
|
|
640
|
+
return depositTokenAmount.lte(maxDepositToken);
|
|
641
|
+
}
|
|
642
|
+
exports.checkDepositLimits = checkDepositLimits;
|
|
602
643
|
/**
|
|
603
644
|
* Calculates the margin-weighted value of a spot deposit, mirroring the asset-side of the
|
|
604
645
|
* program's collateral valuation (`get_strict_token_value` + `get_asset_weight`). Uses the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UnifiedSwapClient.d.ts","sourceRoot":"","sources":["../../../src/swap/UnifiedSwapClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,UAAU,EACV,SAAS,EACT,kBAAkB,EAClB,yBAAyB,EACzB,oBAAoB,EACpB,sBAAsB,EACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,EAAE,EAAE,MAAM,sBAAsB,CAAC;AAC1C,OAAO,EACN,aAAa,EAEb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,WAAW,EAA6B,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"UnifiedSwapClient.d.ts","sourceRoot":"","sources":["../../../src/swap/Un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ChC,SAAS,EACT,UAAU,EACV,MAAM,EACN,aAAa,EACb,WAAW,EACX,QAAoB,EACpB,gBAAwB,EACxB,KAAK,EACL,cAAc,GACd,EAAE;QACF,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,SAAS,CAAC;QACtB,MAAM,EAAE,EAAE,CAAC;QACX,aAAa,EAAE,SAAS,CAAC;QACzB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;QACpB,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,KAAK,CAAC,EAAE,oBAAoB,CAAC;QAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC;QACX,YAAY,EAAE,sBAAsB,EAAE,CAAC;QACvC,YAAY,EAAE,yBAAyB,EAAE,CAAC;KAC1C,CAAC;IA8EF;;OAEG;IACI,SAAS,IAAI,aAAa,GAAG,WAAW;IAI/C;;OAEG;IACI,aAAa,IAAI,cAAc;IAItC;;OAEG;IACI,SAAS,IAAI,OAAO;IAI3B;;OAEG;IACI,OAAO,IAAI,OAAO;CAGzB"}
|
|
@@ -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 ||
|
|
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 ||
|
|
157
|
+
sizeConstraint: sizeConstraint || DEFAULT_ROUTE_SIZE_CONSTRAINT,
|
|
144
158
|
});
|
|
145
159
|
swapInstructions = titanClient.getTitanInstructions({
|
|
146
160
|
transactionMessage,
|
|
@@ -85,6 +85,12 @@ 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
|
}
|
|
90
96
|
//# sourceMappingURL=titanClient.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"titanClient.d.ts","sourceRoot":"","sources":["../../../src/titan/titanClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,UAAU,EACV,SAAS,EACT,kBAAkB,EAClB,yBAAyB,EACzB,sBAAsB,EACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,EAAE,EAAE,MAAM,sBAAsB,CAAC;AAG1C,oBAAY,QAAQ;IACnB,OAAO,YAAY;IACnB,QAAQ,aAAa;CACrB;AA6DD,MAAM,WAAW,aAAa;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACnD,SAAS,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,GAAG,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MA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B,CAAC;QACvC,YAAY,EAAE,yBAAyB,EAAE,CAAC;KAC1C,CAAC;IAmCF;;;;;OAKG;IACI,oBAAoB,CAAC,EAC3B,kBAAkB,EAClB,SAAS,EACT,UAAU,GACV,EAAE;QACF,kBAAkB,EAAE,kBAAkB,CAAC;QACvC,SAAS,EAAE,SAAS,CAAC;QACrB,UAAU,EAAE,SAAS,CAAC;KACtB,GAAG,sBAAsB,EAAE;IAmC5B;;;;OAIG;YACW,gBAAgB;YAsChB,oCAAoC;CA8ClD"}
|
|
@@ -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
|
-
|
|
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({
|
package/lib/node/types.d.ts
CHANGED
|
@@ -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 {
|
|
@@ -1207,6 +1209,8 @@ export type PerpMarketAccount = {
|
|
|
1207
1209
|
feePoolBufferTarget: BN;
|
|
1208
1210
|
/** PERCENTAGE_PRECISION (1e6 = 100%); fraction of OI notional (at the oracle TWAP) the sweep leaves behind in `feeLedger.pendingIfFee` as a standing bankruptcy first-loss tranche; 0 disables */
|
|
1209
1211
|
bankruptcyIfFloorPct: number;
|
|
1212
|
+
/** QUOTE_PRECISION (1e6); aggregate builder/referrer revenue share accrued but not yet paid out of this market's pnl pool. The fee sweep reserves it (like `max(net_user_pnl, 0)` and the floored IF tranche) so a protocol-fee drain can't leave accrued revenue-share claims temporarily unpayable */
|
|
1213
|
+
pendingRevenueShare: BN;
|
|
1210
1214
|
/** MARGIN_PRECISION (1e4); scales margin ratio up for large positions */
|
|
1211
1215
|
imfFactor: number;
|
|
1212
1216
|
/** MARGIN_PRECISION (1e4); discounts positive-unrealized-pnl asset weight for large positions */
|
|
@@ -1357,6 +1361,10 @@ export type SpotMarketAccount = {
|
|
|
1357
1361
|
protocolLiquidationFee: number;
|
|
1358
1362
|
/** IF_FACTOR_PRECISION (1e6); protocol's carveout of lending deposit-interest gains */
|
|
1359
1363
|
protocolFeeFactor: number;
|
|
1364
|
+
/** token mint precision; IF vault balance recorded at the last revenue settle, used as a
|
|
1365
|
+
* donation-proof base for the per-period revenue-settle APR cap (see `settle_revenue_to_insurance_fund`);
|
|
1366
|
+
* `0` = uninitialized (pre-upgrade accounts, seeded on first settle) */
|
|
1367
|
+
ifLastSettleVaultAmount: BN;
|
|
1360
1368
|
/** token mint decimals; token-mint precision throughout this account is 10^decimals */
|
|
1361
1369
|
decimals: number;
|
|
1362
1370
|
/** SPOT_UTILIZATION_PRECISION (1e6) */
|
|
@@ -1439,6 +1447,9 @@ export type SpotMarketAccount = {
|
|
|
1439
1447
|
poolId: number;
|
|
1440
1448
|
/** -100 to 100; percentage adjustment applied to the base fee rate */
|
|
1441
1449
|
feeAdjustment: number;
|
|
1450
|
+
depositGuardThreshold: BN;
|
|
1451
|
+
withdrawCircuitBreakerBps: number;
|
|
1452
|
+
maxDepositBpsPerDay: number;
|
|
1442
1453
|
};
|
|
1443
1454
|
/** A scaled token balance inside a market's internal pools (pnl pool, protocol fee pool, revenue pool, spot fee pool, AMM fee pool). Multiply `scaledBalance` (SPOT_BALANCE_PRECISION, 1e9) by the referenced spot market's `cumulativeDepositInterest`/`cumulativeBorrowInterest` to get the token amount. */
|
|
1444
1455
|
export type PoolBalance = {
|
|
@@ -1688,8 +1699,10 @@ export type UserAccount = {
|
|
|
1688
1699
|
poolId: number;
|
|
1689
1700
|
/** bitmask, see `SpecialUserStatus` */
|
|
1690
1701
|
specialUserStatus: number;
|
|
1691
|
-
/** QUOTE_PRECISION (1e6); admin-set minimum cross-margin total collateral
|
|
1702
|
+
/** QUOTE_PRECISION (1e6); admin-set minimum cross-margin total collateral; below it the permissionless breaker can trip; 0 = disabled */
|
|
1692
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;
|
|
1693
1706
|
};
|
|
1694
1707
|
/** A user's balance in one spot market. Decoded mirror of the on-chain `SpotPosition`. */
|
|
1695
1708
|
export type SpotPosition = {
|