@naviprotocol/multiply 0.2.0-preview.20261124.2 → 0.2.0-preview.20261124.4

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/README.md CHANGED
@@ -71,7 +71,7 @@ valuation belongs to the API and may differ for LST backing. Zero debt has null
71
71
  HF; empty/non-positive equity has null leverage.
72
72
 
73
73
  `maxLeverage` bounds leverage at the **minimum** conversion output, at quote, live
74
- rebuild and on chain, with the solver's 0.01% tolerance: a target equal to it is
74
+ rebuild and on chain, with its existing 0.01% rounding band: a target equal to it is
75
75
  reachable at zero slippage, and a nonzero `maxSlippageBps` needs matching headroom
76
76
  above the target. It bounds only what can raise leverage: `close`, `repay` and
77
77
  `add_collateral` are never refused by it, and `remove_principal` or a lowering
@@ -82,46 +82,36 @@ equity, but the result must still meet `minHealthFactor`. A `remove_principal`
82
82
  target that would need new debt is `ACTION_UNSUPPORTED`. `add_principal` levers
83
83
  the amount it adds to the target, or to the current leverage when none is given.
84
84
 
85
- ## Snapshot-based leverage quotes
86
-
87
- Opening, adding principal and increasing leverage estimate flash funding with prices,
88
- fees and the selected conversion rate. Volo/Haedal native staking now use an optional
89
- `getStakingSnapshot(pair)` with complete integer state to calculate the conversion
90
- locally. A valid candidate needs **zero formal conversion quotes**. Other routes,
91
- including USDSUI/USDC, still validate one real quote. An unavailable snapshot or a
92
- candidate outside the original tolerance/risk limits falls back to the original
93
- bracket solver. Malformed state and the shared deadline remain errors.
94
-
95
- Volo simulates `refresh` followed by effective supply and fee getters in one PTB.
96
- It rounds the stake fee up, then minted LST down. Haedal reads all supply components
97
- from one state object and reproduces checked-u64 arithmetic; the pinned stake
98
- entrypoint does not charge its stored `deposit_fee`. Its redemption fee is unchanged.
99
- This is exact integer math for the pinned native contracts, not a rounded display
100
- exchange rate. Both preserve the existing SDK minimum of 1 SUI conversion input.
101
-
102
- Snapshots live for 5 seconds per converter/client instance. Every use checks the
103
- current epoch; epoch changes invalidate the cache. Concurrent reads are deduplicated;
104
- expired pending reads can be retried, and late old reads cannot replace newer state.
105
- Volo's simulation reports its actual epoch. A read exceeding TTL is not accepted.
106
- Reusing an instance avoids the complete snapshot read, but still performs an epoch
107
- RPC. No snapshot is used for unstaking or DEX execution.
108
-
109
- Protocol oracle prices still determine target leverage, HF, LTV and capacity. All
110
- integer funding/fee rounding, minimum-output guards and final on-chain HF checks
111
- remain in force. Builds must still be fully simulated before execution: fees, pause
112
- state and exchange rates can change after quoting. The cache TTL controls calculation
113
- reuse; it does not shrink the existing executable quote lifetime. Snapshot reads and
114
- fallback quotes share the existing 32-attempt / 45-second budget. Custom converters
115
- can still supply `getRateHint`, which requires an actual quote to verify the seed.
116
-
117
- See [the current benchmark and acceptance evidence](docs/native-snapshot-benchmark.md).
118
- After building, `node e2e/quote-seed-benchmark.mjs` compares baseline `0e8f2a9` against
119
- cold and same-instance follow-up quotes. `MULTIPLY_BENCH_BASE`, `MULTIPLY_BENCH_ROUNDS`,
120
- `MULTIPLY_BENCH_PRINCIPAL`, `MULTIPLY_BENCH_LEVERAGE` and `MULTIPLY_BENCH_OUT` configure
121
- it. Formal quotes and snapshot time are reported separately within total SDK latency.
122
- `node e2e/native-snapshot-build.mjs` exercises fully funded mainnet simulations,
123
- actual minted amounts, min-output failures and final HF failures. Neither signs or
124
- broadcasts transactions.
85
+ For `open` and upward `set_leverage`, target accuracy is a relative **0.1%**:
86
+ `abs(actualLeverage - targetLeverage) / targetLeverage <= 0.001`.
87
+ This applies to both the first swap candidate and the solver result. Other actions
88
+ retain their existing 0.01% target accuracy. Estimates always report the actual
89
+ quoted result. Target accuracy never relaxes HF, LTV, the independent
90
+ `maxLeverage` band, liquidity limits, or funding conservation checks. A candidate
91
+ that fails any of those checks still falls back or fails.
92
+
93
+ ## Astros-only leverage quotes
94
+
95
+ Default conversions use Astros exact-input quotes and build the saved Astros route.
96
+ For vSUI/haSUI, an independent chain-rate reader seeds the amount; protocol oracle
97
+ prices still determine leverage, HF and capacity. The hint never supplies executable
98
+ outputs. One real quote must pass the unchanged target, minimum-output and risk
99
+ checks; otherwise the existing solver continues using Astros. An exit candidate is
100
+ reused once as the starting point of the existing correction loop. No persistent
101
+ amount memoization disables intentional endpoint refreshes.
102
+
103
+ The Volo hint reads refreshed supply totals in one read-only PTB; Haedal reads the
104
+ chain conversion getter with an integer probe. Hints expire after 5 seconds and
105
+ are not cached across requests or epochs. Unavailable/paused getters or zero totals
106
+ skip the hint. Native cash, native fees and minimums do not gate Astros routes.
107
+ `useRateHints: false` disables seeds without changing execution routing.
108
+ `rateHintProvider` may provide a separate custom reader. USDSUI uses a price/fee seed.
109
+ Close uses its known full input directly; repay/top-up/direct collateral 1x need no
110
+ hint or swap. The shared 45-second/32-call budget and solver precision are unchanged.
111
+
112
+ Explicit custom converters remain supported, including native snapshot methods;
113
+ those methods are never selected by the default client or the API's Astros-only client.
114
+ See `e2e/astros-only-benchmark.mjs` for read-only interleaved measurements.
125
115
 
126
116
  ## Execution plan v4
127
117
 
@@ -147,14 +137,16 @@ server-side. The caller must simulate the final composed PTB before signing.
147
137
 
148
138
  ## Converters
149
139
 
150
- Volo and Haedal use live contract getters. Eligible routes are compared by minimum
151
- net output. Astros is the fallback only for explicit route unavailability or
152
- minimum-amount errors; malformed quotes, invalid inputs and read failures propagate.
153
- A build never silently switches routes. Haedal instant redemption requires gross
154
- SUI equivalent >= 1 SUI **before** its service fee in the pinned staking module.
140
+ The default registry contains Astros only. Optional Volo/Haedal converters remain
141
+ available for explicitly configured integrations; their native execution limits
142
+ apply only when callers select them. Astros may itself choose native, DEX or mixed
143
+ routes. A build uses the saved route and never silently switches providers.
155
144
  Unknown conversion fees are omitted, never fabricated as zero. Known fees are
156
145
  marked `includedInExpectedOutput: true`. Optional route metadata describes provider,
157
146
  hops, pools/DEX and observation time; it is separate from opaque executable data.
147
+ Astros fee decoration runs at most once per selected conversion, before the checksum,
148
+ and never changes output/minimum amounts. Direct converter consumers can call
149
+ `enrichFees(quote)` explicitly. Unknown/mixed-route fees remain unavailable.
158
150
 
159
151
  Astros is pinned to 2.0.7. Its route change goes directly to `quote.address`, not
160
152
  the gas sponsor or `built.coins`. Vault integrations must account for that custody
@@ -233,3 +225,35 @@ alongside their effective risk parameters. Paused groups disable new exposure;
233
225
  the default source can read only that group's configuration to support repayment
234
226
  and exit, without reading any account's current mode. Keep the existing final-byte
235
227
  simulation requirement, especially with `buildPTBForSimulation`.
228
+
229
+ ### Market-price and native-exit optimization
230
+
231
+ `marketPriceMode` defaults to `live` for existing SDK callers. `prefer-market`
232
+ uses `Pool.oracle.freshness` only when both strategy assets have coherent,
233
+ validated, unexpired evidence for the configured NAVI deployment; otherwise it
234
+ uses the existing live oracle path. `market-only` fails with
235
+ `PRICE_DATA_UNAVAILABLE` instead of preparing/updating the oracle. Price expiry
236
+ also bounds the quote expiry. An expired calculation is replanned once with live
237
+ prices only in `prefer-market`, within the original request budget.
238
+
239
+ Default exits now use the independent rate hint plus a real Astros quote; the prior
240
+ native redemption cash-gated fast path is not selected. Explicit native integrations
241
+ can still use their snapshot helpers. API `MULTIPLY_DISABLE_RATE_HINTS=true` disables
242
+ hints only and never restores native execution.
243
+
244
+ `prepareOracleForSimulation: false` applies **only** to
245
+ `buildPTBForSimulation`. It omits oracle preparation/update commands. The caller
246
+ must run the complete checks-enabled transaction simulation and reconcile funding
247
+ before exposing signing bytes. Public `buildPTB` keeps its existing oracle and
248
+ preflight behavior. No-update builds can fail on expired on-chain prices even if
249
+ a live quote succeeded by updating prices inside a read-only simulation. Requoting
250
+ does not itself update on-chain prices.
251
+
252
+ Read-only regression tools:
253
+
254
+ - `e2e/exit-snapshot-benchmark.mjs`: interleaved native/DEX solver comparison, plus
255
+ real wallet exit simulations. Synthetic positions used for solver timing are
256
+ explicitly separate from the wallet section.
257
+ - `MULTIPLY_REFERENCE_ORACLE=true` is an **E2E-only** fixture that explicitly adds
258
+ an oracle update inside simulation. It is never enabled by the API and does not
259
+ prove a no-update build succeeded on current chain state.
package/dist/amounts.d.ts CHANGED
@@ -40,9 +40,9 @@ export declare function withinSameReserveCapacity(strategy: {
40
40
  borrowFee: string;
41
41
  }, market: MarketSnapshot): boolean;
42
42
  /**
43
- * `maxLeverage` as enforced: the solver accepts a plan within 0.01% of its target and amounts are
44
- * whole atoms, so a target equal to the ceiling can land a hair above it. The quote, the live
45
- * rebuild and the on-chain check all allow that same band, and nothing beyond it.
43
+ * Independent 0.01% rounding band for the hard `maxLeverage` ceiling. Whole-atom amounts
44
+ * may land a hair above the requested ceiling. Quote, live rebuild and on-chain checks
45
+ * share this band; relaxing target accuracy must never widen it.
46
46
  */
47
47
  export declare const LEVERAGE_TOLERANCE = "0.0001";
48
48
  export declare function leverageCeiling(maxLeverage: string): import('bignumber.js').BigNumber;
@@ -1 +1 @@
1
- {"version":3,"file":"amounts.js","sources":["../src/amounts.ts"],"sourcesContent":["import type { Pool } from '@naviprotocol/lending'\nimport type { Action, ExecutionPlan, MarketSnapshot, PositionAmounts, Strategy } from './types'\nimport { BN, check, decimal } from './utils'\n\n/** NAVI stores lending balances/capacity at 9 decimals, independently of Coin<T>. */\nexport const LENDING_DECIMALS = 9\n\nexport function tokenDecimals(pool: Pick<Pool, 'token'>): number {\n const value = pool.token?.decimals\n check(\n Number.isInteger(value) && value >= 0 && value <= 18,\n 'MARKET_UNSUPPORTED',\n 'Token precision must be an integer from 0 to 18'\n )\n return value\n}\n\nexport function lendingToRaw(value: string, decimals: number, roundUp = false) {\n return decimal(value)\n .shiftedBy(decimals - LENDING_DECIMALS)\n .integerValue(roundUp ? BN.ROUND_CEIL : BN.ROUND_FLOOR)\n .toFixed(0)\n}\n\n/** A custom source with a rounded-down zero cannot establish an empty Cap without the protocol amount. */\nexport function positionSides(position: PositionAmounts, market: MarketSnapshot) {\n const side = (amount: string, protocol: string | undefined, decimals: number, debt: boolean) => {\n if (protocol !== undefined) {\n check(\n /^(0|[1-9][0-9]{0,77})$/.test(protocol) &&\n lendingToRaw(protocol, decimals, debt) === amount,\n 'READ_FAILED',\n 'Invalid protocol balance or inconsistent native amount'\n )\n return protocol !== '0'\n }\n check(\n debt || decimals >= LENDING_DECIMALS || amount !== '0',\n 'READ_FAILED',\n 'Rounded collateral requires a protocol balance'\n )\n return amount !== '0'\n }\n return {\n collateral: side(\n position.collateralAmount,\n position.protocolCollateralAmount,\n tokenDecimals(market.collateral),\n false\n ),\n debt: side(position.debtAmount, position.protocolDebtAmount, tokenDecimals(market.debt), true)\n }\n}\n\nexport function isDustClose(strategy: Strategy, position: PositionAmounts, market: MarketSnapshot) {\n return (\n strategy.allowCollateralDustClose === true &&\n tokenDecimals(market.collateral) === 6 &&\n position.collateralAmount === '0' &&\n position.debtAmount === '0' &&\n position.protocolDebtAmount === '0' &&\n typeof position.protocolCollateralAmount === 'string' &&\n /^[1-9][0-9]{0,2}$/.test(position.protocolCollateralAmount)\n )\n}\n\n/** Price of one native atom, used only inside the solver. Public prices stay USD/token. */\nexport function atomPrices(market: MarketSnapshot) {\n return {\n collateral: decimal(market.collateralPrice).shiftedBy(-tokenDecimals(market.collateral)),\n debt: decimal(market.debtPrice).shiftedBy(-tokenDecimals(market.debt))\n }\n}\n\n/** Existing one-micro-token interest/drift cushion, with at least one native atom. */\nexport function amountCushion(pool: Pick<Pool, 'token'>) {\n return BN.maximum(1, new BN(1).shiftedBy(tokenDecimals(pool) - 6))\n}\n\nexport function supplyCapacity(market: MarketSnapshot) {\n return BN.maximum(\n 0,\n new BN(market.collateral.leftSupply)\n .shiftedBy(tokenDecimals(market.collateral))\n .integerValue(BN.ROUND_FLOOR)\n )\n}\n\nexport function borrowCapacity(market: MarketSnapshot) {\n return new BN(lendingToRaw(market.debt.availableBorrow, tokenDecimals(market.debt)))\n}\n\n/**\n * Pool cash of the debt reserve, raw in the coin's own decimals: the lending API's `balance` (\"pool withdrawable\n * balance\"). Not the `Pool<T>` object's balance: the SUI pool stakes most of its SUI and unstakes on withdrawal (LQ-09).\n */\nexport function reserveCash(market: MarketSnapshot) {\n const cash = (market.debt as { balance?: unknown }).balance\n check(\n typeof cash === 'string' && /^\\d+$/.test(cash),\n 'READ_FAILED',\n 'Missing or invalid debt reserve cash'\n )\n return new BN(cash)\n}\n\n/**\n * LQ-01 / LQ-05..LQ-10: a main-market strategy flash-loans its debt coin from the same main-market reserve it borrows\n * from, and the flash is still outstanding when the borrow runs. The borrow alone uses borrow-cap headroom\n * (`availableBorrow`, checked separately); every coin taken out — flash, borrow and its fee — must be in the pool at once.\n * A flash-only exit at the borrow cap stays possible while the cash is there (LQ-04). Isolated markets borrow from their\n * own reserve (LQ-02): only the separate checks apply there.\n */\nexport function withinSameReserveCapacity(\n strategy: { market: string },\n amounts: { flashAmount: string; borrowAmount: string; borrowFee: string },\n market: MarketSnapshot\n) {\n if (strategy.market !== 'main') return true\n const out = new BN(amounts.flashAmount).plus(amounts.borrowAmount).plus(amounts.borrowFee)\n return out.isZero() || out.lte(reserveCash(market))\n}\n\n/**\n * `maxLeverage` as enforced: the solver accepts a plan within 0.01% of its target and amounts are\n * whole atoms, so a target equal to the ceiling can land a hair above it. The quote, the live\n * rebuild and the on-chain check all allow that same band, and nothing beyond it.\n */\nexport const LEVERAGE_TOLERANCE = '0.0001'\nexport function leverageCeiling(maxLeverage: string) {\n return new BN(maxLeverage).times(new BN(1).plus(LEVERAGE_TOLERANCE))\n}\n\n/**\n * The `maxLeverage` bound of one action, the same at quote, live rebuild and on chain. An action\n * that adds debt (`increase`: open, add_principal, a raising set_leverage) must land within the\n * ceiling. Repay, a collateral top-up and close only lower leverage, so `maxLeverage` never refuses\n * them (`undefined`): a position above the ceiling — prices moved, or an open landed inside the\n * band — must stay exitable. Any other decrease may keep such a position's leverage but not raise\n * it: its bound is the higher of the ceiling and the current leverage with the same band.\n */\nexport function leverageLimit(\n maxLeverage: string | undefined,\n action: Pick<Action, 'type'>,\n direction: ExecutionPlan['direction'],\n currentLeverage: string | null\n) {\n if (!maxLeverage || ['close', 'repay', 'add_collateral'].includes(action.type)) return undefined\n const ceiling = leverageCeiling(maxLeverage)\n return direction === 'increase' || currentLeverage === null\n ? ceiling\n : BN.maximum(ceiling, leverageCeiling(currentLeverage))\n}\n\n/** A lowered borrowing cap must still permit repayment, collateral top-up and exit. */\nexport function withinLtv(\n projected: PositionAmounts,\n before: PositionAmounts,\n market: MarketSnapshot,\n allowReduction: boolean\n) {\n const prices = atomPrices(market)\n const c = new BN(projected.collateralAmount),\n d = new BN(projected.debtAmount)\n if (\n d\n .times(prices.debt)\n .times(market.borrowWeight)\n .lte(c.times(prices.collateral).times(market.ltv))\n )\n return true\n return (\n allowReduction &&\n d.lte(before.debtAmount) &&\n d.times(before.collateralAmount).lte(new BN(before.debtAmount).times(c))\n )\n}\n"],"names":["LENDING_DECIMALS","tokenDecimals","pool","value","check","lendingToRaw","decimals","roundUp","decimal","BN","positionSides","position","market","side","amount","protocol","debt","isDustClose","strategy","atomPrices","amountCushion","supplyCapacity","borrowCapacity","reserveCash","cash","withinSameReserveCapacity","amounts","out","LEVERAGE_TOLERANCE","leverageCeiling","maxLeverage","leverageLimit","action","direction","currentLeverage","ceiling","withinLtv","projected","before","allowReduction","prices","c","d"],"mappings":";AAKO,MAAMA,IAAmB;AAEzB,SAASC,EAAcC,GAAmC;AAC/D,QAAMC,IAAQD,EAAK,OAAO;AAC1B,SAAAE;AAAA,IACE,OAAO,UAAUD,CAAK,KAAKA,KAAS,KAAKA,KAAS;AAAA,IAClD;AAAA,IACA;AAAA,EAAA,GAEKA;AACT;AAEO,SAASE,EAAaF,GAAeG,GAAkBC,IAAU,IAAO;AAC7E,SAAOC,EAAQL,CAAK,EACjB,UAAUG,IAAWN,CAAgB,EACrC,aAAaO,IAAUE,EAAG,aAAaA,EAAG,WAAW,EACrD,QAAQ,CAAC;AACd;AAGO,SAASC,EAAcC,GAA2BC,GAAwB;AAC/E,QAAMC,IAAO,CAACC,GAAgBC,GAA8BT,GAAkBU,MACxED,MAAa,UACfX;AAAA,IACE,yBAAyB,KAAKW,CAAQ,KACpCV,EAAaU,GAAUT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,IAAIJ,EAAO,UAAU,KACvBI,EAAE,MAAMJ,EAAO,gBAAgB,EAAE,IAAI,IAAI7B,EAAG6B,EAAO,UAAU,EAAE,MAAMG,CAAC,CAAC;AAE3E;"}
1
+ {"version":3,"file":"amounts.js","sources":["../src/amounts.ts"],"sourcesContent":["import type { Pool } from '@naviprotocol/lending'\nimport type { Action, ExecutionPlan, MarketSnapshot, PositionAmounts, Strategy } from './types'\nimport { BN, check, decimal } from './utils'\n\n/** NAVI stores lending balances/capacity at 9 decimals, independently of Coin<T>. */\nexport const LENDING_DECIMALS = 9\n\nexport function tokenDecimals(pool: Pick<Pool, 'token'>): number {\n const value = pool.token?.decimals\n check(\n Number.isInteger(value) && value >= 0 && value <= 18,\n 'MARKET_UNSUPPORTED',\n 'Token precision must be an integer from 0 to 18'\n )\n return value\n}\n\nexport function lendingToRaw(value: string, decimals: number, roundUp = false) {\n return decimal(value)\n .shiftedBy(decimals - LENDING_DECIMALS)\n .integerValue(roundUp ? BN.ROUND_CEIL : BN.ROUND_FLOOR)\n .toFixed(0)\n}\n\n/** A custom source with a rounded-down zero cannot establish an empty Cap without the protocol amount. */\nexport function positionSides(position: PositionAmounts, market: MarketSnapshot) {\n const side = (amount: string, protocol: string | undefined, decimals: number, debt: boolean) => {\n if (protocol !== undefined) {\n check(\n /^(0|[1-9][0-9]{0,77})$/.test(protocol) &&\n lendingToRaw(protocol, decimals, debt) === amount,\n 'READ_FAILED',\n 'Invalid protocol balance or inconsistent native amount'\n )\n return protocol !== '0'\n }\n check(\n debt || decimals >= LENDING_DECIMALS || amount !== '0',\n 'READ_FAILED',\n 'Rounded collateral requires a protocol balance'\n )\n return amount !== '0'\n }\n return {\n collateral: side(\n position.collateralAmount,\n position.protocolCollateralAmount,\n tokenDecimals(market.collateral),\n false\n ),\n debt: side(position.debtAmount, position.protocolDebtAmount, tokenDecimals(market.debt), true)\n }\n}\n\nexport function isDustClose(strategy: Strategy, position: PositionAmounts, market: MarketSnapshot) {\n return (\n strategy.allowCollateralDustClose === true &&\n tokenDecimals(market.collateral) === 6 &&\n position.collateralAmount === '0' &&\n position.debtAmount === '0' &&\n position.protocolDebtAmount === '0' &&\n typeof position.protocolCollateralAmount === 'string' &&\n /^[1-9][0-9]{0,2}$/.test(position.protocolCollateralAmount)\n )\n}\n\n/** Price of one native atom, used only inside the solver. Public prices stay USD/token. */\nexport function atomPrices(market: MarketSnapshot) {\n return {\n collateral: decimal(market.collateralPrice).shiftedBy(-tokenDecimals(market.collateral)),\n debt: decimal(market.debtPrice).shiftedBy(-tokenDecimals(market.debt))\n }\n}\n\n/** Existing one-micro-token interest/drift cushion, with at least one native atom. */\nexport function amountCushion(pool: Pick<Pool, 'token'>) {\n return BN.maximum(1, new BN(1).shiftedBy(tokenDecimals(pool) - 6))\n}\n\nexport function supplyCapacity(market: MarketSnapshot) {\n return BN.maximum(\n 0,\n new BN(market.collateral.leftSupply)\n .shiftedBy(tokenDecimals(market.collateral))\n .integerValue(BN.ROUND_FLOOR)\n )\n}\n\nexport function borrowCapacity(market: MarketSnapshot) {\n return new BN(lendingToRaw(market.debt.availableBorrow, tokenDecimals(market.debt)))\n}\n\n/**\n * Pool cash of the debt reserve, raw in the coin's own decimals: the lending API's `balance` (\"pool withdrawable\n * balance\"). Not the `Pool<T>` object's balance: the SUI pool stakes most of its SUI and unstakes on withdrawal (LQ-09).\n */\nexport function reserveCash(market: MarketSnapshot) {\n const cash = (market.debt as { balance?: unknown }).balance\n check(\n typeof cash === 'string' && /^\\d+$/.test(cash),\n 'READ_FAILED',\n 'Missing or invalid debt reserve cash'\n )\n return new BN(cash)\n}\n\n/**\n * LQ-01 / LQ-05..LQ-10: a main-market strategy flash-loans its debt coin from the same main-market reserve it borrows\n * from, and the flash is still outstanding when the borrow runs. The borrow alone uses borrow-cap headroom\n * (`availableBorrow`, checked separately); every coin taken out — flash, borrow and its fee — must be in the pool at once.\n * A flash-only exit at the borrow cap stays possible while the cash is there (LQ-04). Isolated markets borrow from their\n * own reserve (LQ-02): only the separate checks apply there.\n */\nexport function withinSameReserveCapacity(\n strategy: { market: string },\n amounts: { flashAmount: string; borrowAmount: string; borrowFee: string },\n market: MarketSnapshot\n) {\n if (strategy.market !== 'main') return true\n const out = new BN(amounts.flashAmount).plus(amounts.borrowAmount).plus(amounts.borrowFee)\n return out.isZero() || out.lte(reserveCash(market))\n}\n\n/**\n * Independent 0.01% rounding band for the hard `maxLeverage` ceiling. Whole-atom amounts\n * may land a hair above the requested ceiling. Quote, live rebuild and on-chain checks\n * share this band; relaxing target accuracy must never widen it.\n */\nexport const LEVERAGE_TOLERANCE = '0.0001'\nexport function leverageCeiling(maxLeverage: string) {\n return new BN(maxLeverage).times(new BN(1).plus(LEVERAGE_TOLERANCE))\n}\n\n/**\n * The `maxLeverage` bound of one action, the same at quote, live rebuild and on chain. An action\n * that adds debt (`increase`: open, add_principal, a raising set_leverage) must land within the\n * ceiling. Repay, a collateral top-up and close only lower leverage, so `maxLeverage` never refuses\n * them (`undefined`): a position above the ceiling — prices moved, or an open landed inside the\n * band — must stay exitable. Any other decrease may keep such a position's leverage but not raise\n * it: its bound is the higher of the ceiling and the current leverage with the same band.\n */\nexport function leverageLimit(\n maxLeverage: string | undefined,\n action: Pick<Action, 'type'>,\n direction: ExecutionPlan['direction'],\n currentLeverage: string | null\n) {\n if (!maxLeverage || ['close', 'repay', 'add_collateral'].includes(action.type)) return undefined\n const ceiling = leverageCeiling(maxLeverage)\n return direction === 'increase' || currentLeverage === null\n ? ceiling\n : BN.maximum(ceiling, leverageCeiling(currentLeverage))\n}\n\n/** A lowered borrowing cap must still permit repayment, collateral top-up and exit. */\nexport function withinLtv(\n projected: PositionAmounts,\n before: PositionAmounts,\n market: MarketSnapshot,\n allowReduction: boolean\n) {\n const prices = atomPrices(market)\n const c = new BN(projected.collateralAmount),\n d = new BN(projected.debtAmount)\n if (\n d\n .times(prices.debt)\n .times(market.borrowWeight)\n .lte(c.times(prices.collateral).times(market.ltv))\n )\n return true\n return (\n allowReduction &&\n d.lte(before.debtAmount) &&\n d.times(before.collateralAmount).lte(new BN(before.debtAmount).times(c))\n )\n}\n"],"names":["LENDING_DECIMALS","tokenDecimals","pool","value","check","lendingToRaw","decimals","roundUp","decimal","BN","positionSides","position","market","side","amount","protocol","debt","isDustClose","strategy","atomPrices","amountCushion","supplyCapacity","borrowCapacity","reserveCash","cash","withinSameReserveCapacity","amounts","out","LEVERAGE_TOLERANCE","leverageCeiling","maxLeverage","leverageLimit","action","direction","currentLeverage","ceiling","withinLtv","projected","before","allowReduction","prices","c","d"],"mappings":";AAKO,MAAMA,IAAmB;AAEzB,SAASC,EAAcC,GAAmC;AAC/D,QAAMC,IAAQD,EAAK,OAAO;AAC1B,SAAAE;AAAA,IACE,OAAO,UAAUD,CAAK,KAAKA,KAAS,KAAKA,KAAS;AAAA,IAClD;AAAA,IACA;AAAA,EAAA,GAEKA;AACT;AAEO,SAASE,EAAaF,GAAeG,GAAkBC,IAAU,IAAO;AAC7E,SAAOC,EAAQL,CAAK,EACjB,UAAUG,IAAWN,CAAgB,EACrC,aAAaO,IAAUE,EAAG,aAAaA,EAAG,WAAW,EACrD,QAAQ,CAAC;AACd;AAGO,SAASC,EAAcC,GAA2BC,GAAwB;AAC/E,QAAMC,IAAO,CAACC,GAAgBC,GAA8BT,GAAkBU,MACxED,MAAa,UACfX;AAAA,IACE,yBAAyB,KAAKW,CAAQ,KACpCV,EAAaU,GAAUT,GAAUU,CAAI,MAAMF;AAAA,IAC7C;AAAA,IACA;AAAA,EAAA,GAEKC,MAAa,QAEtBX;AAAA,IACEY,KAAQV,KAAYN,KAAoBc,MAAW;AAAA,IACnD;AAAA,IACA;AAAA,EAAA,GAEKA,MAAW;AAEpB,SAAO;AAAA,IACL,YAAYD;AAAA,MACVF,EAAS;AAAA,MACTA,EAAS;AAAA,MACTV,EAAcW,EAAO,UAAU;AAAA,MAC/B;AAAA,IAAA;AAAA,IAEF,MAAMC,EAAKF,EAAS,YAAYA,EAAS,oBAAoBV,EAAcW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IlB,EAAGiB,EAAQ,WAAW,EAAE,KAAKA,EAAQ,YAAY,EAAE,KAAKA,EAAQ,SAAS;AACzF,SAAOC,EAAI,YAAYA,EAAI,IAAIJ,EAAYX,CAAM,CAAC;AACpD;AAOO,MAAMgB,IAAqB;AAC3B,SAASC,EAAgBC,GAAqB;AACnD,SAAO,IAAIrB,EAAGqB,CAAW,EAAE,MAAM,IAAIrB,EAAG,CAAC,EAAE,KAAKmB,CAAkB,CAAC;AACrE;AAUO,SAASG,EACdD,GACAE,GACAC,GACAC,GACA;AACA,MAAI,CAACJ,KAAe,CAAC,SAAS,SAAS,gBAAgB,EAAE,SAASE,EAAO,IAAI,EAAG;AAChF,QAAMG,IAAUN,EAAgBC,CAAW;AAC3C,SAAOG,MAAc,cAAcC,MAAoB,OACnDC,IACA1B,EAAG,QAAQ0B,GAASN,EAAgBK,CAAe,CAAC;AAC1D;AAGO,SAASE,EACdC,GACAC,GACA1B,GACA2B,GACA;AACA,QAAMC,IAASrB,EAAWP,CAAM,GAC1B6B,IAAI,IAAIhC,EAAG4B,EAAU,gBAAgB,GACzCK,IAAI,IAAIjC,EAAG4B,EAAU,UAAU;AACjC,SACEK,EACG,MAAMF,EAAO,IAAI,EACjB,MAAM5B,EAAO,YAAY,EACzB,IAAI6B,EAAE,MAAMD,EAAO,UAAU,EAAE,MAAM5B,EAAO,GAAG,CAAC,IAE5C,KAEP2B,KACAG,EAAE,IAAIJ,EAAO,UAAU,KACvBI,EAAE,MAAMJ,EAAO,gBAAgB,EAAE,IAAI,IAAI7B,EAAG6B,EAAO,UAAU,EAAE,MAAMG,CAAC,CAAC;AAE3E;"}
package/dist/client.d.ts CHANGED
@@ -5,7 +5,7 @@ export declare function createMultiplyClient(options?: MultiplyOptions): {
5
5
  getPosition: (owner: string, query?: {
6
6
  strategy?: Strategy;
7
7
  }) => Promise<Position[]>;
8
- quote: (owner: string, suppliedStrategy: Strategy, action: Action, constraints: Constraints) => Promise<MultiplyQuote>;
8
+ quote: (owner: string, strategy: Strategy, action: Action, constraints: Constraints) => Promise<MultiplyQuote>;
9
9
  buildPTB: (tx: Transaction, q: MultiplyQuote, inputs: BuildInputs) => Promise<BuildResult>;
10
10
  buildPTBForSimulation: (tx: Transaction, q: MultiplyQuote, coins: BuildInputs["coins"]) => Promise<BuildResult>;
11
11
  };
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAkC,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAEV,MAAM,EACN,WAAW,EACX,WAAW,EACX,WAAW,EAGX,eAAe,EACf,aAAa,EACb,QAAQ,EACR,QAAQ,EACT,MAAM,SAAS,CAAA;AAyChB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,eAAoB;yBA2JvD,MAAM,UACN;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAC7B,OAAO,CAAC,QAAQ,EAAE,CAAC;mBAwBb,MAAM,oBACK,QAAQ,UAClB,MAAM,eACD,WAAW,KACvB,OAAO,CAAC,aAAa,CAAC;mBAiuBH,WAAW,KAAK,aAAa,UAAU,WAAW;gCAKrC,WAAW,KAAK,aAAa,SAAS,WAAW,CAAC,OAAO,CAAC;EAK9F"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAkC,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAEV,MAAM,EACN,WAAW,EACX,WAAW,EACX,WAAW,EAGX,eAAe,EACf,aAAa,EACb,QAAQ,EACR,QAAQ,EAET,MAAM,SAAS,CAAA;AA0ChB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,eAAoB;yBAmKvD,MAAM,UACN;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAC7B,OAAO,CAAC,QAAQ,EAAE,CAAC;mBAqNb,MAAM,YACH,QAAQ,UACV,MAAM,eACD,WAAW,KACvB,OAAO,CAAC,aAAa,CAAC;mBA+nBH,WAAW,KAAK,aAAa,UAAU,WAAW;gCAKrC,WAAW,KAAK,aAAa,SAAS,WAAW,CAAC,OAAO,CAAC;EAK9F"}