@naviprotocol/multiply 0.2.0-preview.20261124.1 → 0.2.0-preview.20261124.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -1
- package/dist/amounts.d.ts +10 -1
- package/dist/amounts.d.ts.map +1 -1
- package/dist/amounts.js +47 -41
- package/dist/amounts.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +298 -276
- package/dist/client.js.map +1 -1
- package/dist/converters.d.ts.map +1 -1
- package/dist/converters.js +221 -204
- package/dist/converters.js.map +1 -1
- package/dist/native-staking.d.ts +13 -0
- package/dist/native-staking.d.ts.map +1 -0
- package/dist/native-staking.js +157 -0
- package/dist/native-staking.js.map +1 -0
- package/dist/planner.d.ts +2 -2
- package/dist/planner.d.ts.map +1 -1
- package/dist/planner.js +384 -270
- package/dist/planner.js.map +1 -1
- package/dist/types.d.ts +26 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -73,11 +73,56 @@ HF; empty/non-positive equity has null leverage.
|
|
|
73
73
|
`maxLeverage` bounds leverage at the **minimum** conversion output, at quote, live
|
|
74
74
|
rebuild and on chain, with the solver's 0.01% tolerance: a target equal to it is
|
|
75
75
|
reachable at zero slippage, and a nonzero `maxSlippageBps` needs matching headroom
|
|
76
|
-
above the target.
|
|
76
|
+
above the target. It bounds only what can raise leverage: `close`, `repay` and
|
|
77
|
+
`add_collateral` are never refused by it, and `remove_principal` or a lowering
|
|
78
|
+
`set_leverage` on a position already above it may keep, but not raise, the current
|
|
79
|
+
leverage; `add_principal` there is refused, since it adds debt. `repay` and
|
|
80
|
+
`add_collateral` stay available without positive
|
|
77
81
|
equity, but the result must still meet `minHealthFactor`. A `remove_principal`
|
|
78
82
|
target that would need new debt is `ACTION_UNSUPPORTED`. `add_principal` levers
|
|
79
83
|
the amount it adds to the target, or to the current leverage when none is given.
|
|
80
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.
|
|
125
|
+
|
|
81
126
|
## Execution plan v4
|
|
82
127
|
|
|
83
128
|
Older plans must be re-quoted. `funding` identifies wallet collateral/debt or no
|
package/dist/amounts.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Pool } from '@naviprotocol/lending';
|
|
2
|
-
import { MarketSnapshot, PositionAmounts, Strategy } from './types.js';
|
|
2
|
+
import { Action, ExecutionPlan, MarketSnapshot, PositionAmounts, Strategy } from './types.js';
|
|
3
3
|
|
|
4
4
|
/** NAVI stores lending balances/capacity at 9 decimals, independently of Coin<T>. */
|
|
5
5
|
export declare const LENDING_DECIMALS = 9;
|
|
@@ -46,6 +46,15 @@ export declare function withinSameReserveCapacity(strategy: {
|
|
|
46
46
|
*/
|
|
47
47
|
export declare const LEVERAGE_TOLERANCE = "0.0001";
|
|
48
48
|
export declare function leverageCeiling(maxLeverage: string): import('bignumber.js').BigNumber;
|
|
49
|
+
/**
|
|
50
|
+
* The `maxLeverage` bound of one action, the same at quote, live rebuild and on chain. An action
|
|
51
|
+
* that adds debt (`increase`: open, add_principal, a raising set_leverage) must land within the
|
|
52
|
+
* ceiling. Repay, a collateral top-up and close only lower leverage, so `maxLeverage` never refuses
|
|
53
|
+
* them (`undefined`): a position above the ceiling — prices moved, or an open landed inside the
|
|
54
|
+
* band — must stay exitable. Any other decrease may keep such a position's leverage but not raise
|
|
55
|
+
* it: its bound is the higher of the ceiling and the current leverage with the same band.
|
|
56
|
+
*/
|
|
57
|
+
export declare function leverageLimit(maxLeverage: string | undefined, action: Pick<Action, 'type'>, direction: ExecutionPlan['direction'], currentLeverage: string | null): import('bignumber.js').BigNumber | undefined;
|
|
49
58
|
/** A lowered borrowing cap must still permit repayment, collateral top-up and exit. */
|
|
50
59
|
export declare function withinLtv(projected: PositionAmounts, before: PositionAmounts, market: MarketSnapshot, allowReduction: boolean): boolean;
|
|
51
60
|
//# sourceMappingURL=amounts.d.ts.map
|
package/dist/amounts.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"amounts.d.ts","sourceRoot":"","sources":["../src/amounts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"amounts.d.ts","sourceRoot":"","sources":["../src/amounts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAG/F,qFAAqF;AACrF,eAAO,MAAM,gBAAgB,IAAI,CAAA;AAEjC,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,MAAM,CAQ/D;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,UAAQ,UAK5E;AAED,0GAA0G;AAC1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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { decimal as s, BN as n, check as c } from "./utils.js";
|
|
2
|
-
const
|
|
3
|
-
function
|
|
2
|
+
const m = 9;
|
|
3
|
+
function i(e) {
|
|
4
4
|
const t = e.token?.decimals;
|
|
5
5
|
return c(
|
|
6
6
|
Number.isInteger(t) && t >= 0 && t <= 18,
|
|
@@ -8,51 +8,51 @@ function o(e) {
|
|
|
8
8
|
"Token precision must be an integer from 0 to 18"
|
|
9
9
|
), t;
|
|
10
10
|
}
|
|
11
|
-
function
|
|
12
|
-
return s(e).shiftedBy(t -
|
|
11
|
+
function f(e, t, l = !1) {
|
|
12
|
+
return s(e).shiftedBy(t - m).integerValue(l ? n.ROUND_CEIL : n.ROUND_FLOOR).toFixed(0);
|
|
13
13
|
}
|
|
14
|
-
function
|
|
15
|
-
const l = (
|
|
16
|
-
/^(0|[1-9][0-9]{0,77})$/.test(
|
|
14
|
+
function E(e, t) {
|
|
15
|
+
const l = (o, r, u, a) => r !== void 0 ? (c(
|
|
16
|
+
/^(0|[1-9][0-9]{0,77})$/.test(r) && f(r, u, a) === o,
|
|
17
17
|
"READ_FAILED",
|
|
18
18
|
"Invalid protocol balance or inconsistent native amount"
|
|
19
|
-
),
|
|
20
|
-
|
|
19
|
+
), r !== "0") : (c(
|
|
20
|
+
a || u >= m || o !== "0",
|
|
21
21
|
"READ_FAILED",
|
|
22
22
|
"Rounded collateral requires a protocol balance"
|
|
23
|
-
),
|
|
23
|
+
), o !== "0");
|
|
24
24
|
return {
|
|
25
25
|
collateral: l(
|
|
26
26
|
e.collateralAmount,
|
|
27
27
|
e.protocolCollateralAmount,
|
|
28
|
-
|
|
28
|
+
i(t.collateral),
|
|
29
29
|
!1
|
|
30
30
|
),
|
|
31
|
-
debt: l(e.debtAmount, e.protocolDebtAmount,
|
|
31
|
+
debt: l(e.debtAmount, e.protocolDebtAmount, i(t.debt), !0)
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
|
-
function
|
|
35
|
-
return e.allowCollateralDustClose === !0 &&
|
|
34
|
+
function p(e, t, l) {
|
|
35
|
+
return e.allowCollateralDustClose === !0 && i(l.collateral) === 6 && t.collateralAmount === "0" && t.debtAmount === "0" && t.protocolDebtAmount === "0" && typeof t.protocolCollateralAmount == "string" && /^[1-9][0-9]{0,2}$/.test(t.protocolCollateralAmount);
|
|
36
36
|
}
|
|
37
|
-
function
|
|
37
|
+
function A(e) {
|
|
38
38
|
return {
|
|
39
|
-
collateral: s(e.collateralPrice).shiftedBy(-
|
|
40
|
-
debt: s(e.debtPrice).shiftedBy(-
|
|
39
|
+
collateral: s(e.collateralPrice).shiftedBy(-i(e.collateral)),
|
|
40
|
+
debt: s(e.debtPrice).shiftedBy(-i(e.debt))
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
43
|
function C(e) {
|
|
44
|
-
return n.maximum(1, new n(1).shiftedBy(
|
|
44
|
+
return n.maximum(1, new n(1).shiftedBy(i(e) - 6));
|
|
45
45
|
}
|
|
46
46
|
function R(e) {
|
|
47
47
|
return n.maximum(
|
|
48
48
|
0,
|
|
49
|
-
new n(e.collateral.leftSupply).shiftedBy(
|
|
49
|
+
new n(e.collateral.leftSupply).shiftedBy(i(e.collateral)).integerValue(n.ROUND_FLOOR)
|
|
50
50
|
);
|
|
51
51
|
}
|
|
52
52
|
function h(e) {
|
|
53
|
-
return new n(
|
|
53
|
+
return new n(f(e.debt.availableBorrow, i(e.debt)));
|
|
54
54
|
}
|
|
55
|
-
function
|
|
55
|
+
function b(e) {
|
|
56
56
|
const t = e.debt.balance;
|
|
57
57
|
return c(
|
|
58
58
|
typeof t == "string" && /^\d+$/.test(t),
|
|
@@ -60,33 +60,39 @@ function A(e) {
|
|
|
60
60
|
"Missing or invalid debt reserve cash"
|
|
61
61
|
), new n(t);
|
|
62
62
|
}
|
|
63
|
-
function
|
|
63
|
+
function y(e, t, l) {
|
|
64
64
|
if (e.market !== "main") return !0;
|
|
65
|
-
const
|
|
66
|
-
return
|
|
65
|
+
const o = new n(t.flashAmount).plus(t.borrowAmount).plus(t.borrowFee);
|
|
66
|
+
return o.isZero() || o.lte(b(l));
|
|
67
|
+
}
|
|
68
|
+
const w = "0.0001";
|
|
69
|
+
function d(e) {
|
|
70
|
+
return new n(e).times(new n(1).plus(w));
|
|
67
71
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
function v(e, t, l, o) {
|
|
73
|
+
if (!e || ["close", "repay", "add_collateral"].includes(t.type)) return;
|
|
74
|
+
const r = d(e);
|
|
75
|
+
return l === "increase" || o === null ? r : n.maximum(r, d(o));
|
|
71
76
|
}
|
|
72
|
-
function
|
|
73
|
-
const
|
|
74
|
-
return
|
|
77
|
+
function g(e, t, l, o) {
|
|
78
|
+
const r = A(l), u = new n(e.collateralAmount), a = new n(e.debtAmount);
|
|
79
|
+
return a.times(r.debt).times(l.borrowWeight).lte(u.times(r.collateral).times(l.ltv)) ? !0 : o && a.lte(t.debtAmount) && a.times(t.collateralAmount).lte(new n(t.debtAmount).times(u));
|
|
75
80
|
}
|
|
76
81
|
export {
|
|
77
|
-
|
|
78
|
-
|
|
82
|
+
m as LENDING_DECIMALS,
|
|
83
|
+
w as LEVERAGE_TOLERANCE,
|
|
79
84
|
C as amountCushion,
|
|
80
|
-
|
|
85
|
+
A as atomPrices,
|
|
81
86
|
h as borrowCapacity,
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
+
p as isDustClose,
|
|
88
|
+
f as lendingToRaw,
|
|
89
|
+
d as leverageCeiling,
|
|
90
|
+
v as leverageLimit,
|
|
91
|
+
E as positionSides,
|
|
92
|
+
b as reserveCash,
|
|
87
93
|
R as supplyCapacity,
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
94
|
+
i as tokenDecimals,
|
|
95
|
+
g as withinLtv,
|
|
96
|
+
y as withinSameReserveCapacity
|
|
91
97
|
};
|
|
92
98
|
//# sourceMappingURL=amounts.js.map
|
package/dist/amounts.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"amounts.js","sources":["../src/amounts.ts"],"sourcesContent":["import type { Pool } from '@naviprotocol/lending'\nimport type { 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/** 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","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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sB,KACAG,EAAE,IAAIJ,EAAO,UAAU,KACvBI,EAAE,MAAMJ,EAAO,gBAAgB,EAAE,IAAI,IAAIxB,EAAGwB,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 * `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,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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EV,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;
|
|
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"}
|