@naviprotocol/multiply 0.2.0-preview.20261119.1 → 0.2.0-preview.20261124.1
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 +39 -12
- package/dist/amounts.d.ts +33 -1
- package/dist/amounts.d.ts.map +1 -1
- package/dist/amounts.js +75 -29
- package/dist/amounts.js.map +1 -1
- package/dist/cap-registry.d.ts +11 -2
- package/dist/cap-registry.d.ts.map +1 -1
- package/dist/cap-registry.js +78 -51
- package/dist/cap-registry.js.map +1 -1
- package/dist/client.d.ts +2 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +427 -326
- package/dist/client.js.map +1 -1
- package/dist/data-source.d.ts +17 -1
- package/dist/data-source.d.ts.map +1 -1
- package/dist/data-source.js +201 -190
- package/dist/data-source.js.map +1 -1
- package/dist/emode.d.ts +7 -0
- package/dist/emode.d.ts.map +1 -0
- package/dist/emode.js +95 -0
- package/dist/emode.js.map +1 -0
- package/dist/funding.d.ts.map +1 -1
- package/dist/funding.js +34 -29
- package/dist/funding.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -17
- package/dist/planner.d.ts +1 -1
- package/dist/planner.d.ts.map +1 -1
- package/dist/planner.js +246 -224
- package/dist/planner.js.map +1 -1
- package/dist/types.d.ts +34 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +4 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +82 -53
- package/dist/utils.js.map +1 -1
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@ quotes and builds transactions; it never signs or broadcasts them.
|
|
|
6
6
|
## Phase 1 model
|
|
7
7
|
|
|
8
8
|
The application owns product registration. Supply its validated `Strategy[]` to
|
|
9
|
-
`createMultiplyClient
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
`createMultiplyClient`. The API's phase 1 directory includes vSUI/SUI, haSUI/SUI,
|
|
10
|
+
and USDSUI/USDC. The application passes retired Registry keys alongside the active
|
|
11
|
+
strategies so wallet reads skip retired AccountCaps.
|
|
12
12
|
|
|
13
13
|
A strategy has distinct collateral and debt tokens. `principalCoinType` can equal
|
|
14
14
|
either. It is the accounting/default withdrawal unit, independent of the selected
|
|
@@ -24,17 +24,17 @@ const multiply = createMultiplyClient({
|
|
|
24
24
|
strategies: productStrategies,
|
|
25
25
|
retiredRegistryKeys: retiredProductKeys,
|
|
26
26
|
})
|
|
27
|
-
const strategy = productStrategies.find(s => s.id === '
|
|
27
|
+
const strategy = productStrategies.find(s => s.id === 'main-vsui-sui')!
|
|
28
28
|
const quote = await multiply.quote(
|
|
29
29
|
address,
|
|
30
30
|
strategy,
|
|
31
31
|
{ type: 'open', inputCoinType: strategy.collateralCoinType,
|
|
32
|
-
amount: '1000000000', targetLeverage: '
|
|
33
|
-
{ minHealthFactor: '
|
|
32
|
+
amount: '1000000000', targetLeverage: '1.5' },
|
|
33
|
+
{ minHealthFactor: '2.0', maxSlippageBps: 50 },
|
|
34
34
|
)
|
|
35
35
|
const tx = new Transaction()
|
|
36
36
|
const built = await multiply.buildPTB(tx, quote, {
|
|
37
|
-
coins: [{ coinType: strategy.collateralCoinType, coin:
|
|
37
|
+
coins: [{ coinType: strategy.collateralCoinType, coin: suppliedVsuiCoin }],
|
|
38
38
|
})
|
|
39
39
|
if (built.createdAccountCap) tx.transferObjects([built.createdAccountCap], address)
|
|
40
40
|
if (built.coins.length) tx.transferObjects(built.coins.map(c => c.coin), address)
|
|
@@ -70,6 +70,14 @@ HF, LTV and solver leverage use **NAVI risk oracle values**. Economic display
|
|
|
70
70
|
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
|
+
`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
|
|
75
|
+
reachable at zero slippage, and a nonzero `maxSlippageBps` needs matching headroom
|
|
76
|
+
above the target. `repay` and `add_collateral` stay available without positive
|
|
77
|
+
equity, but the result must still meet `minHealthFactor`. A `remove_principal`
|
|
78
|
+
target that would need new debt is `ACTION_UNSUPPORTED`. `add_principal` levers
|
|
79
|
+
the amount it adds to the target, or to the current leverage when none is given.
|
|
80
|
+
|
|
73
81
|
## Execution plan v4
|
|
74
82
|
|
|
75
83
|
Older plans must be re-quoted. `funding` identifies wallet collateral/debt or no
|
|
@@ -83,7 +91,7 @@ Collateral input is supplied directly; only borrowed debt is converted. Debt
|
|
|
83
91
|
input may merge with debt flash funding before conversion. A 1x collateral opening
|
|
84
92
|
needs no conversion or flash loan. On a collateral-principal withdrawal/close,
|
|
85
93
|
only the collateral required for debt repayment is sold; the remainder is returned
|
|
86
|
-
as principal. Debt dust remains a separate output.
|
|
94
|
+
as principal. Debt dust remains a separate output.
|
|
87
95
|
|
|
88
96
|
The builder independently validates funding, conversion roles, projected balances,
|
|
89
97
|
repayment math and minimum principal output. Different token types never merge.
|
|
@@ -113,8 +121,8 @@ safe integer range. When using the converter directly, pass a validated
|
|
|
113
121
|
|
|
114
122
|
Keys `(strategyNumericId, strategyVersion)` are permanent execution identities,
|
|
115
123
|
unique per registry definition. Never reassign a deployed key to different assets
|
|
116
|
-
or market. New Caps are created and registered atomically; close retains the Cap.
|
|
117
|
-
Invalid ownership, duplicate Caps/accounts,
|
|
124
|
+
or market/mode. New Caps are created and registered atomically; close retains the Cap.
|
|
125
|
+
Invalid ownership, duplicate Caps/accounts, invalid E-Mode configuration and unknown keys
|
|
118
126
|
fail explicitly. Only **explicit** `retiredRegistryKeys` may be skipped; structural,
|
|
119
127
|
identity and duplicate checks still run first. Retiring a key does not move funds.
|
|
120
128
|
|
|
@@ -134,8 +142,8 @@ The API consequently reports lifetime yield unavailable until a conforming sourc
|
|
|
134
142
|
and complete history watermark are available. Basic positions and risk still work.
|
|
135
143
|
|
|
136
144
|
Custom adapters are trusted application code. Built-in contract deployments target
|
|
137
|
-
Sui mainnet; changing only the client URL does not switch those addresses.
|
|
138
|
-
|
|
145
|
+
Sui mainnet; changing only the client URL does not switch those addresses.
|
|
146
|
+
Isolated phase 2, third-token inputs and delayed redemption are out of scope.
|
|
139
147
|
The exported `strategies.vsuiSui`/`hasuiSui` remain legacy dedicated-market presets
|
|
140
148
|
(keys 1:1/2:1); phase 1 products must use the API-owned main-market registry.
|
|
141
149
|
|
|
@@ -161,3 +169,22 @@ threshold fallback and malformed/retired identities. Historical documents under
|
|
|
161
169
|
phase 1 hosted simulation or signed-wallet acceptance. Each product must progress
|
|
162
170
|
through open simulation → human sample creation → management simulation → human
|
|
163
171
|
management/close, with matching Registry keys and source/artifact revisions.
|
|
172
|
+
|
|
173
|
+
### Strategy E-Mode
|
|
174
|
+
|
|
175
|
+
Set `Strategy.emodeId` together with `market` to use that market's E-Mode (ID `0`
|
|
176
|
+
is valid). `getMarket()` supplies the configured group's collateral LTV/LT;
|
|
177
|
+
debt retains its reserve borrow weight. The data source checks asset direction.
|
|
178
|
+
|
|
179
|
+
Use a **new Multiply Registry strategyVersion** when switching a strategy's mode,
|
|
180
|
+
and retire the previous key through `retiredRegistryKeys`. Existing ordinary Caps
|
|
181
|
+
are not migrated. A newly created Cap enters the configured mode in the same PTB,
|
|
182
|
+
before Multiply registration and funding. A previously initialized Cap, including
|
|
183
|
+
an empty one reopened after close, is reused without a mode query or another enter.
|
|
184
|
+
No operation reads or writes the independent E-Mode Registry.
|
|
185
|
+
|
|
186
|
+
Custom DataSources must return `market.emode = { id, active }` for E-Mode strategies,
|
|
187
|
+
alongside their effective risk parameters. Paused groups disable new exposure;
|
|
188
|
+
the default source can read only that group's configuration to support repayment
|
|
189
|
+
and exit, without reading any account's current mode. Keep the existing final-byte
|
|
190
|
+
simulation requirement, especially with `buildPTBForSimulation`.
|
package/dist/amounts.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import { Pool } from '@naviprotocol/lending';
|
|
2
|
-
import { MarketSnapshot, PositionAmounts } from './types.js';
|
|
2
|
+
import { 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;
|
|
6
6
|
export declare function tokenDecimals(pool: Pick<Pool, 'token'>): number;
|
|
7
7
|
export declare function lendingToRaw(value: string, decimals: number, roundUp?: boolean): string;
|
|
8
|
+
/** A custom source with a rounded-down zero cannot establish an empty Cap without the protocol amount. */
|
|
9
|
+
export declare function positionSides(position: PositionAmounts, market: MarketSnapshot): {
|
|
10
|
+
collateral: boolean;
|
|
11
|
+
debt: boolean;
|
|
12
|
+
};
|
|
13
|
+
export declare function isDustClose(strategy: Strategy, position: PositionAmounts, market: MarketSnapshot): boolean;
|
|
8
14
|
/** Price of one native atom, used only inside the solver. Public prices stay USD/token. */
|
|
9
15
|
export declare function atomPrices(market: MarketSnapshot): {
|
|
10
16
|
collateral: import('bignumber.js').BigNumber;
|
|
@@ -14,6 +20,32 @@ export declare function atomPrices(market: MarketSnapshot): {
|
|
|
14
20
|
export declare function amountCushion(pool: Pick<Pool, 'token'>): import('bignumber.js').BigNumber;
|
|
15
21
|
export declare function supplyCapacity(market: MarketSnapshot): import('bignumber.js').BigNumber;
|
|
16
22
|
export declare function borrowCapacity(market: MarketSnapshot): import('bignumber.js').BigNumber;
|
|
23
|
+
/**
|
|
24
|
+
* Pool cash of the debt reserve, raw in the coin's own decimals: the lending API's `balance` ("pool withdrawable
|
|
25
|
+
* balance"). Not the `Pool<T>` object's balance: the SUI pool stakes most of its SUI and unstakes on withdrawal (LQ-09).
|
|
26
|
+
*/
|
|
27
|
+
export declare function reserveCash(market: MarketSnapshot): import('bignumber.js').BigNumber;
|
|
28
|
+
/**
|
|
29
|
+
* LQ-01 / LQ-05..LQ-10: a main-market strategy flash-loans its debt coin from the same main-market reserve it borrows
|
|
30
|
+
* from, and the flash is still outstanding when the borrow runs. The borrow alone uses borrow-cap headroom
|
|
31
|
+
* (`availableBorrow`, checked separately); every coin taken out — flash, borrow and its fee — must be in the pool at once.
|
|
32
|
+
* A flash-only exit at the borrow cap stays possible while the cash is there (LQ-04). Isolated markets borrow from their
|
|
33
|
+
* own reserve (LQ-02): only the separate checks apply there.
|
|
34
|
+
*/
|
|
35
|
+
export declare function withinSameReserveCapacity(strategy: {
|
|
36
|
+
market: string;
|
|
37
|
+
}, amounts: {
|
|
38
|
+
flashAmount: string;
|
|
39
|
+
borrowAmount: string;
|
|
40
|
+
borrowFee: string;
|
|
41
|
+
}, market: MarketSnapshot): boolean;
|
|
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.
|
|
46
|
+
*/
|
|
47
|
+
export declare const LEVERAGE_TOLERANCE = "0.0001";
|
|
48
|
+
export declare function leverageCeiling(maxLeverage: string): import('bignumber.js').BigNumber;
|
|
17
49
|
/** A lowered borrowing cap must still permit repayment, collateral top-up and exit. */
|
|
18
50
|
export declare function withinLtv(projected: PositionAmounts, before: PositionAmounts, market: MarketSnapshot, allowReduction: boolean): boolean;
|
|
19
51
|
//# 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,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"amounts.d.ts","sourceRoot":"","sources":["../src/amounts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,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F,wBAAgB,SAAS,CACvB,SAAS,EAAE,eAAe,EAC1B,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,cAAc,EACtB,cAAc,EAAE,OAAO,WAiBxB"}
|
package/dist/amounts.js
CHANGED
|
@@ -1,46 +1,92 @@
|
|
|
1
|
-
import {
|
|
2
|
-
const
|
|
3
|
-
function
|
|
4
|
-
const
|
|
5
|
-
return
|
|
6
|
-
Number.isInteger(
|
|
1
|
+
import { decimal as s, BN as n, check as c } from "./utils.js";
|
|
2
|
+
const d = 9;
|
|
3
|
+
function o(e) {
|
|
4
|
+
const t = e.token?.decimals;
|
|
5
|
+
return c(
|
|
6
|
+
Number.isInteger(t) && t >= 0 && t <= 18,
|
|
7
7
|
"MARKET_UNSUPPORTED",
|
|
8
8
|
"Token precision must be an integer from 0 to 18"
|
|
9
|
-
),
|
|
9
|
+
), t;
|
|
10
10
|
}
|
|
11
|
-
function
|
|
12
|
-
return
|
|
11
|
+
function m(e, t, l = !1) {
|
|
12
|
+
return s(e).shiftedBy(t - d).integerValue(l ? n.ROUND_CEIL : n.ROUND_FLOOR).toFixed(0);
|
|
13
13
|
}
|
|
14
|
-
function
|
|
14
|
+
function D(e, t) {
|
|
15
|
+
const l = (r, a, i, u) => a !== void 0 ? (c(
|
|
16
|
+
/^(0|[1-9][0-9]{0,77})$/.test(a) && m(a, i, u) === r,
|
|
17
|
+
"READ_FAILED",
|
|
18
|
+
"Invalid protocol balance or inconsistent native amount"
|
|
19
|
+
), a !== "0") : (c(
|
|
20
|
+
u || i >= d || r !== "0",
|
|
21
|
+
"READ_FAILED",
|
|
22
|
+
"Rounded collateral requires a protocol balance"
|
|
23
|
+
), r !== "0");
|
|
15
24
|
return {
|
|
16
|
-
collateral:
|
|
17
|
-
|
|
25
|
+
collateral: l(
|
|
26
|
+
e.collateralAmount,
|
|
27
|
+
e.protocolCollateralAmount,
|
|
28
|
+
o(t.collateral),
|
|
29
|
+
!1
|
|
30
|
+
),
|
|
31
|
+
debt: l(e.debtAmount, e.protocolDebtAmount, o(t.debt), !0)
|
|
18
32
|
};
|
|
19
33
|
}
|
|
20
|
-
function
|
|
21
|
-
return e.
|
|
34
|
+
function E(e, t, l) {
|
|
35
|
+
return e.allowCollateralDustClose === !0 && o(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);
|
|
22
36
|
}
|
|
23
|
-
function
|
|
24
|
-
return
|
|
37
|
+
function f(e) {
|
|
38
|
+
return {
|
|
39
|
+
collateral: s(e.collateralPrice).shiftedBy(-o(e.collateral)),
|
|
40
|
+
debt: s(e.debtPrice).shiftedBy(-o(e.debt))
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function C(e) {
|
|
44
|
+
return n.maximum(1, new n(1).shiftedBy(o(e) - 6));
|
|
45
|
+
}
|
|
46
|
+
function R(e) {
|
|
47
|
+
return n.maximum(
|
|
25
48
|
0,
|
|
26
|
-
new e
|
|
49
|
+
new n(e.collateral.leftSupply).shiftedBy(o(e.collateral)).integerValue(n.ROUND_FLOOR)
|
|
27
50
|
);
|
|
28
51
|
}
|
|
29
|
-
function
|
|
30
|
-
return new
|
|
52
|
+
function h(e) {
|
|
53
|
+
return new n(m(e.debt.availableBorrow, o(e.debt)));
|
|
54
|
+
}
|
|
55
|
+
function A(e) {
|
|
56
|
+
const t = e.debt.balance;
|
|
57
|
+
return c(
|
|
58
|
+
typeof t == "string" && /^\d+$/.test(t),
|
|
59
|
+
"READ_FAILED",
|
|
60
|
+
"Missing or invalid debt reserve cash"
|
|
61
|
+
), new n(t);
|
|
62
|
+
}
|
|
63
|
+
function p(e, t, l) {
|
|
64
|
+
if (e.market !== "main") return !0;
|
|
65
|
+
const r = new n(t.flashAmount).plus(t.borrowAmount).plus(t.borrowFee);
|
|
66
|
+
return r.isZero() || r.lte(A(l));
|
|
67
|
+
}
|
|
68
|
+
const b = "0.0001";
|
|
69
|
+
function v(e) {
|
|
70
|
+
return new n(e).times(new n(1).plus(b));
|
|
31
71
|
}
|
|
32
|
-
function y(
|
|
33
|
-
const
|
|
34
|
-
return
|
|
72
|
+
function y(e, t, l, r) {
|
|
73
|
+
const a = f(l), i = new n(e.collateralAmount), u = new n(e.debtAmount);
|
|
74
|
+
return u.times(a.debt).times(l.borrowWeight).lte(i.times(a.collateral).times(l.ltv)) ? !0 : r && u.lte(t.debtAmount) && u.times(t.collateralAmount).lte(new n(t.debtAmount).times(i));
|
|
35
75
|
}
|
|
36
76
|
export {
|
|
37
|
-
|
|
38
|
-
|
|
77
|
+
d as LENDING_DECIMALS,
|
|
78
|
+
b as LEVERAGE_TOLERANCE,
|
|
79
|
+
C as amountCushion,
|
|
39
80
|
f as atomPrices,
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
81
|
+
h as borrowCapacity,
|
|
82
|
+
E as isDustClose,
|
|
83
|
+
m as lendingToRaw,
|
|
84
|
+
v as leverageCeiling,
|
|
85
|
+
D as positionSides,
|
|
86
|
+
A as reserveCash,
|
|
87
|
+
R as supplyCapacity,
|
|
88
|
+
o as tokenDecimals,
|
|
89
|
+
y as withinLtv,
|
|
90
|
+
p as withinSameReserveCapacity
|
|
45
91
|
};
|
|
46
92
|
//# 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 } 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/** 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/** 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","
|
|
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,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,GAAg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|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
|
|
2
|
-
import { CapRegistryConfig, RegistryKey, Strategy } from './types.js';
|
|
2
|
+
import { CapRegistryConfig, NaviEnv, RegistryKey, Strategy } from './types.js';
|
|
3
3
|
|
|
4
4
|
export declare const ACCOUNT_CAP_TYPE = "0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap";
|
|
5
|
+
/** Lending `AccountCap` type of each NAVI deployment (stage_v2 is a separate lending package). */
|
|
6
|
+
export declare const ACCOUNT_CAP_TYPES: Readonly<Partial<Record<NaviEnv, string>>>;
|
|
7
|
+
export declare function normalizeEnv(env: unknown): NaviEnv;
|
|
8
|
+
export declare function accountCapType(env: NaviEnv): string;
|
|
9
|
+
/**
|
|
10
|
+
* The default Registry is a prod deployment. Off prod it would bind a stage Cap into the prod
|
|
11
|
+
* Registry, so Cap creation and Registry discovery there need a Registry the caller names.
|
|
12
|
+
*/
|
|
13
|
+
export declare function assertRegistryUsable(env: NaviEnv, explicitRegistry: boolean): void;
|
|
5
14
|
export declare const MAINNET_CAP_REGISTRY: Readonly<CapRegistryConfig>;
|
|
6
15
|
export declare function normalizeCapRegistry(config: CapRegistryConfig): CapRegistryConfig;
|
|
7
16
|
export declare function registryKeyString(key: RegistryKey): string;
|
|
@@ -14,5 +23,5 @@ export interface RegistryEntry {
|
|
|
14
23
|
export declare function decodeRegistryEntries(values: {
|
|
15
24
|
bcs: Uint8Array;
|
|
16
25
|
}[]): RegistryEntry[];
|
|
17
|
-
export declare function registerCreatedCapPTB(tx: Transaction, cap: TransactionObjectArgument, key: RegistryKey, deployment: CapRegistryConfig): void;
|
|
26
|
+
export declare function registerCreatedCapPTB(tx: Transaction, cap: TransactionObjectArgument, key: RegistryKey, deployment: CapRegistryConfig, capType?: string): void;
|
|
18
27
|
//# sourceMappingURL=cap-registry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cap-registry.d.ts","sourceRoot":"","sources":["../src/cap-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"cap-registry.d.ts","sourceRoot":"","sources":["../src/cap-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AACtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAGhF,eAAO,MAAM,gBAAgB,4FAC8D,CAAA;AAE3F,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAGvE,CAAA;AAEF,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CASlD;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAInD;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,QAM3E;AAED,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,iBAAiB,CAI3D,CAAA;AAEF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,CAUjF;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,WAAW,GAAG,MAAM,CAU1D;AAED,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAWrF;AAED,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,WAAW,CAAA;IACxB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,iGAAiG;AACjG,wBAAgB,qBAAqB,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,UAAU,CAAA;CAAE,EAAE,GAAG,aAAa,EAAE,CAiCpF;AAED,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,WAAW,EACf,GAAG,EAAE,yBAAyB,EAC9B,GAAG,EAAE,WAAW,EAChB,UAAU,EAAE,iBAAiB,EAC7B,OAAO,GAAE,MAAyB,QAkBnC"}
|
package/dist/cap-registry.js
CHANGED
|
@@ -1,85 +1,112 @@
|
|
|
1
|
-
import { bcs as
|
|
2
|
-
import { check as
|
|
3
|
-
const
|
|
1
|
+
import { bcs as o } from "@mysten/sui/bcs";
|
|
2
|
+
import { check as n, address as d, uint as y, U64_MAX as p } from "./utils.js";
|
|
3
|
+
const I = "0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap", f = Object.freeze({
|
|
4
|
+
prod: I,
|
|
5
|
+
dev: "0x51e18f149666eff167d6bcaf59d0b9edcf6affe7650bb2bc3d5167a8c9f6f6d0::account::AccountCap"
|
|
6
|
+
});
|
|
7
|
+
function N(e) {
|
|
8
|
+
return e === void 0 ? "prod" : (n(
|
|
9
|
+
// ST-17: 'test' is not accepted until its deployment (AccountCap type, Registry) is known.
|
|
10
|
+
e === "prod" || e === "dev",
|
|
11
|
+
"INVALID_ARGUMENT",
|
|
12
|
+
`Unsupported NAVI env: ${String(e)}`
|
|
13
|
+
), e);
|
|
14
|
+
}
|
|
15
|
+
function _(e) {
|
|
16
|
+
const t = f[e];
|
|
17
|
+
return n(t, "MARKET_UNSUPPORTED", `No known lending AccountCap type for NAVI env ${e}`), t;
|
|
18
|
+
}
|
|
19
|
+
function E(e, t) {
|
|
20
|
+
n(
|
|
21
|
+
e === "prod" || t,
|
|
22
|
+
"MARKET_UNSUPPORTED",
|
|
23
|
+
`NAVI env ${e} has no Multiply Registry: pass capRegistry, or supply an existing Cap through a custom data source`
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
const m = Object.freeze({
|
|
4
27
|
network: "sui:mainnet",
|
|
5
28
|
packageId: "0xe98ff1aab2414aa2e60d0561284d011b3c486d47313b51700a2691ad4d37b162",
|
|
6
29
|
objectId: "0x1fb36a5acfcb96b75f0be8869fd6acebbe7586e3e271b81ae4cdcb8ae4ebdd39"
|
|
7
30
|
});
|
|
8
|
-
function
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
return
|
|
12
|
-
|
|
31
|
+
function b(e) {
|
|
32
|
+
n(e?.network === "sui:mainnet", "INVALID_ARGUMENT", "Unsupported Registry network");
|
|
33
|
+
const t = d(e.packageId), r = d(e.objectId);
|
|
34
|
+
return n(
|
|
35
|
+
t !== d("0x0") && r !== d("0x0"),
|
|
13
36
|
"INVALID_ARGUMENT",
|
|
14
37
|
"Zero Registry address"
|
|
15
|
-
), Object.freeze({ network: e.network, packageId:
|
|
38
|
+
), Object.freeze({ network: e.network, packageId: t, objectId: r });
|
|
16
39
|
}
|
|
17
|
-
function
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
return
|
|
21
|
-
|
|
40
|
+
function A(e) {
|
|
41
|
+
n(e, "INVALID_ARGUMENT", "Missing strategy Registry key");
|
|
42
|
+
const t = y(e.strategyNumericId, !1), r = y(e.strategyVersion, !1);
|
|
43
|
+
return n(
|
|
44
|
+
r < 100000n && t * 100000n + r <= p,
|
|
22
45
|
"INVALID_ARGUMENT",
|
|
23
46
|
"Strategy Registry key is outside contract range"
|
|
24
|
-
), `${
|
|
47
|
+
), `${t}:${r}`;
|
|
25
48
|
}
|
|
26
|
-
function
|
|
27
|
-
const
|
|
28
|
-
for (const
|
|
29
|
-
const a =
|
|
30
|
-
|
|
49
|
+
function T(e) {
|
|
50
|
+
const t = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Set();
|
|
51
|
+
for (const s of e) {
|
|
52
|
+
const a = A(s.registryKey);
|
|
53
|
+
n(!r.has(s.id), "INVALID_ARGUMENT", "Strategy registry contains duplicate ids"), n(!t.has(a), "INVALID_ARGUMENT", "Strategy registry contains duplicate numeric keys"), r.add(s.id), t.set(a, s);
|
|
31
54
|
}
|
|
32
|
-
return
|
|
55
|
+
return t;
|
|
33
56
|
}
|
|
34
|
-
function
|
|
57
|
+
function U(e) {
|
|
35
58
|
try {
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
59
|
+
n(e?.length === 3, "READ_FAILED", "Invalid Registry return values");
|
|
60
|
+
const t = o.vector(o.u64()).parse(e[0].bcs), r = o.vector(o.u64()).parse(e[1].bcs), s = o.vector(o.Address).parse(e[2].bcs);
|
|
61
|
+
n(
|
|
62
|
+
t.length === r.length && t.length === s.length,
|
|
40
63
|
"READ_FAILED",
|
|
41
64
|
"Registry arrays differ in length"
|
|
42
65
|
);
|
|
43
66
|
const a = /* @__PURE__ */ new Set();
|
|
44
|
-
return
|
|
45
|
-
const
|
|
46
|
-
return
|
|
47
|
-
BigInt(c) > 0n && BigInt(
|
|
67
|
+
return t.map((c, g) => {
|
|
68
|
+
const i = r[g], u = `${c}:${i}`;
|
|
69
|
+
return n(
|
|
70
|
+
BigInt(c) > 0n && BigInt(i) > 0n && BigInt(i) < 100000n && BigInt(c) * 100000n + BigInt(i) <= p && !a.has(u),
|
|
48
71
|
"READ_FAILED",
|
|
49
72
|
"Invalid or duplicate Registry key"
|
|
50
|
-
), a.add(
|
|
51
|
-
registryKey: { strategyNumericId: c, strategyVersion:
|
|
52
|
-
capId:
|
|
73
|
+
), a.add(u), {
|
|
74
|
+
registryKey: { strategyNumericId: c, strategyVersion: i },
|
|
75
|
+
capId: d(s[g])
|
|
53
76
|
};
|
|
54
77
|
});
|
|
55
78
|
} catch {
|
|
56
|
-
|
|
79
|
+
n(!1, "READ_FAILED", "Unable to decode complete Multiply Registry");
|
|
57
80
|
}
|
|
58
81
|
}
|
|
59
|
-
function
|
|
60
|
-
|
|
61
|
-
const
|
|
82
|
+
function C(e, t, r, s, a = I) {
|
|
83
|
+
A(r);
|
|
84
|
+
const c = b(s), g = e.moveCall({
|
|
62
85
|
target: "0x2::object::id_address",
|
|
63
|
-
typeArguments: [
|
|
64
|
-
arguments: [
|
|
86
|
+
typeArguments: [a],
|
|
87
|
+
arguments: [t]
|
|
65
88
|
});
|
|
66
89
|
e.moveCall({
|
|
67
|
-
target: `${
|
|
90
|
+
target: `${c.packageId}::multiply_registry::register_mul_for_account_cap`,
|
|
68
91
|
arguments: [
|
|
69
|
-
e.object(
|
|
70
|
-
|
|
71
|
-
e.pure.u64(
|
|
72
|
-
e.pure.u64(
|
|
92
|
+
e.object(c.objectId),
|
|
93
|
+
g,
|
|
94
|
+
e.pure.u64(r.strategyNumericId),
|
|
95
|
+
e.pure.u64(r.strategyVersion)
|
|
73
96
|
]
|
|
74
97
|
});
|
|
75
98
|
}
|
|
76
99
|
export {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
m as
|
|
80
|
-
_ as
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
100
|
+
I as ACCOUNT_CAP_TYPE,
|
|
101
|
+
f as ACCOUNT_CAP_TYPES,
|
|
102
|
+
m as MAINNET_CAP_REGISTRY,
|
|
103
|
+
_ as accountCapType,
|
|
104
|
+
E as assertRegistryUsable,
|
|
105
|
+
U as decodeRegistryEntries,
|
|
106
|
+
T as indexRegistryStrategies,
|
|
107
|
+
b as normalizeCapRegistry,
|
|
108
|
+
N as normalizeEnv,
|
|
109
|
+
C as registerCreatedCapPTB,
|
|
110
|
+
A as registryKeyString
|
|
84
111
|
};
|
|
85
112
|
//# sourceMappingURL=cap-registry.js.map
|
package/dist/cap-registry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cap-registry.js","sources":["../src/cap-registry.ts"],"sourcesContent":["import { bcs } from '@mysten/sui/bcs'\nimport type { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions'\nimport type { CapRegistryConfig, RegistryKey, Strategy } from './types'\nimport { address, check, U64_MAX, uint } from './utils'\n\nexport const ACCOUNT_CAP_TYPE =\n '0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap'\n\nexport const MAINNET_CAP_REGISTRY: Readonly<CapRegistryConfig> = Object.freeze({\n network: 'sui:mainnet',\n packageId: '0xe98ff1aab2414aa2e60d0561284d011b3c486d47313b51700a2691ad4d37b162',\n objectId: '0x1fb36a5acfcb96b75f0be8869fd6acebbe7586e3e271b81ae4cdcb8ae4ebdd39'\n})\n\nexport function normalizeCapRegistry(config: CapRegistryConfig): CapRegistryConfig {\n check(config?.network === 'sui:mainnet', 'INVALID_ARGUMENT', 'Unsupported Registry network')\n const packageId = address(config.packageId),\n objectId = address(config.objectId)\n check(\n packageId !== address('0x0') && objectId !== address('0x0'),\n 'INVALID_ARGUMENT',\n 'Zero Registry address'\n )\n return Object.freeze({ network: config.network, packageId, objectId })\n}\n\nexport function registryKeyString(key: RegistryKey): string {\n check(key, 'INVALID_ARGUMENT', 'Missing strategy Registry key')\n const id = uint(key.strategyNumericId, false),\n version = uint(key.strategyVersion, false)\n check(\n version < 100000n && id * 100000n + version <= U64_MAX,\n 'INVALID_ARGUMENT',\n 'Strategy Registry key is outside contract range'\n )\n return `${id}:${version}`\n}\n\nexport function indexRegistryStrategies(strategies: Strategy[]): Map<string, Strategy> {\n const byKey = new Map<string, Strategy>(),\n ids = new Set<string>()\n for (const strategy of strategies) {\n const key = registryKeyString(strategy.registryKey)\n check(!ids.has(strategy.id), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate ids')\n check(!byKey.has(key), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate numeric keys')\n ids.add(strategy.id)\n byKey.set(key, strategy)\n }\n return byKey\n}\n\nexport interface RegistryEntry {\n registryKey: RegistryKey\n capId: string\n}\n\n/** Decode all rows before using any of them. A malformed response is never an empty registry. */\nexport function decodeRegistryEntries(values: { bcs: Uint8Array }[]): RegistryEntry[] {\n try {\n check(values?.length === 3, 'READ_FAILED', 'Invalid Registry return values')\n const ids = bcs.vector(bcs.u64()).parse(values[0].bcs)\n const versions = bcs.vector(bcs.u64()).parse(values[1].bcs)\n const caps = bcs.vector(bcs.Address).parse(values[2].bcs)\n check(\n ids.length === versions.length && ids.length === caps.length,\n 'READ_FAILED',\n 'Registry arrays differ in length'\n )\n const keys = new Set<string>()\n return ids.map((id, i) => {\n const version = versions[i],\n key = `${id}:${version}`\n check(\n BigInt(id) > 0n &&\n BigInt(version) > 0n &&\n BigInt(version) < 100000n &&\n BigInt(id) * 100000n + BigInt(version) <= U64_MAX &&\n !keys.has(key),\n 'READ_FAILED',\n 'Invalid or duplicate Registry key'\n )\n keys.add(key)\n return {\n registryKey: { strategyNumericId: id, strategyVersion: version },\n capId: address(caps[i])\n }\n })\n } catch {\n check(false, 'READ_FAILED', 'Unable to decode complete Multiply Registry')\n }\n}\n\nexport function registerCreatedCapPTB(\n tx: Transaction,\n cap: TransactionObjectArgument,\n key: RegistryKey,\n deployment: CapRegistryConfig\n) {\n registryKeyString(key)\n const config = normalizeCapRegistry(deployment)\n const capAddress = tx.moveCall({\n target: '0x2::object::id_address',\n typeArguments: [
|
|
1
|
+
{"version":3,"file":"cap-registry.js","sources":["../src/cap-registry.ts"],"sourcesContent":["import { bcs } from '@mysten/sui/bcs'\nimport type { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions'\nimport type { CapRegistryConfig, NaviEnv, RegistryKey, Strategy } from './types'\nimport { address, check, U64_MAX, uint } from './utils'\n\nexport const ACCOUNT_CAP_TYPE =\n '0x66c91a8560cd64d73d93dd1ec7b61f3f21ad2f66553dd3d7038ca69255479bb7::account::AccountCap'\n\n/** Lending `AccountCap` type of each NAVI deployment (stage_v2 is a separate lending package). */\nexport const ACCOUNT_CAP_TYPES: Readonly<Partial<Record<NaviEnv, string>>> = Object.freeze({\n prod: ACCOUNT_CAP_TYPE,\n dev: '0x51e18f149666eff167d6bcaf59d0b9edcf6affe7650bb2bc3d5167a8c9f6f6d0::account::AccountCap'\n})\n\nexport function normalizeEnv(env: unknown): NaviEnv {\n if (env === undefined) return 'prod'\n check(\n // ST-17: 'test' is not accepted until its deployment (AccountCap type, Registry) is known.\n env === 'prod' || env === 'dev',\n 'INVALID_ARGUMENT',\n `Unsupported NAVI env: ${String(env)}`\n )\n return env\n}\n\nexport function accountCapType(env: NaviEnv): string {\n const type = ACCOUNT_CAP_TYPES[env]\n check(type, 'MARKET_UNSUPPORTED', `No known lending AccountCap type for NAVI env ${env}`)\n return type\n}\n\n/**\n * The default Registry is a prod deployment. Off prod it would bind a stage Cap into the prod\n * Registry, so Cap creation and Registry discovery there need a Registry the caller names.\n */\nexport function assertRegistryUsable(env: NaviEnv, explicitRegistry: boolean) {\n check(\n env === 'prod' || explicitRegistry,\n 'MARKET_UNSUPPORTED',\n `NAVI env ${env} has no Multiply Registry: pass capRegistry, or supply an existing Cap through a custom data source`\n )\n}\n\nexport const MAINNET_CAP_REGISTRY: Readonly<CapRegistryConfig> = Object.freeze({\n network: 'sui:mainnet',\n packageId: '0xe98ff1aab2414aa2e60d0561284d011b3c486d47313b51700a2691ad4d37b162',\n objectId: '0x1fb36a5acfcb96b75f0be8869fd6acebbe7586e3e271b81ae4cdcb8ae4ebdd39'\n})\n\nexport function normalizeCapRegistry(config: CapRegistryConfig): CapRegistryConfig {\n check(config?.network === 'sui:mainnet', 'INVALID_ARGUMENT', 'Unsupported Registry network')\n const packageId = address(config.packageId),\n objectId = address(config.objectId)\n check(\n packageId !== address('0x0') && objectId !== address('0x0'),\n 'INVALID_ARGUMENT',\n 'Zero Registry address'\n )\n return Object.freeze({ network: config.network, packageId, objectId })\n}\n\nexport function registryKeyString(key: RegistryKey): string {\n check(key, 'INVALID_ARGUMENT', 'Missing strategy Registry key')\n const id = uint(key.strategyNumericId, false),\n version = uint(key.strategyVersion, false)\n check(\n version < 100000n && id * 100000n + version <= U64_MAX,\n 'INVALID_ARGUMENT',\n 'Strategy Registry key is outside contract range'\n )\n return `${id}:${version}`\n}\n\nexport function indexRegistryStrategies(strategies: Strategy[]): Map<string, Strategy> {\n const byKey = new Map<string, Strategy>(),\n ids = new Set<string>()\n for (const strategy of strategies) {\n const key = registryKeyString(strategy.registryKey)\n check(!ids.has(strategy.id), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate ids')\n check(!byKey.has(key), 'INVALID_ARGUMENT', 'Strategy registry contains duplicate numeric keys')\n ids.add(strategy.id)\n byKey.set(key, strategy)\n }\n return byKey\n}\n\nexport interface RegistryEntry {\n registryKey: RegistryKey\n capId: string\n}\n\n/** Decode all rows before using any of them. A malformed response is never an empty registry. */\nexport function decodeRegistryEntries(values: { bcs: Uint8Array }[]): RegistryEntry[] {\n try {\n check(values?.length === 3, 'READ_FAILED', 'Invalid Registry return values')\n const ids = bcs.vector(bcs.u64()).parse(values[0].bcs)\n const versions = bcs.vector(bcs.u64()).parse(values[1].bcs)\n const caps = bcs.vector(bcs.Address).parse(values[2].bcs)\n check(\n ids.length === versions.length && ids.length === caps.length,\n 'READ_FAILED',\n 'Registry arrays differ in length'\n )\n const keys = new Set<string>()\n return ids.map((id, i) => {\n const version = versions[i],\n key = `${id}:${version}`\n check(\n BigInt(id) > 0n &&\n BigInt(version) > 0n &&\n BigInt(version) < 100000n &&\n BigInt(id) * 100000n + BigInt(version) <= U64_MAX &&\n !keys.has(key),\n 'READ_FAILED',\n 'Invalid or duplicate Registry key'\n )\n keys.add(key)\n return {\n registryKey: { strategyNumericId: id, strategyVersion: version },\n capId: address(caps[i])\n }\n })\n } catch {\n check(false, 'READ_FAILED', 'Unable to decode complete Multiply Registry')\n }\n}\n\nexport function registerCreatedCapPTB(\n tx: Transaction,\n cap: TransactionObjectArgument,\n key: RegistryKey,\n deployment: CapRegistryConfig,\n capType: string = ACCOUNT_CAP_TYPE\n) {\n registryKeyString(key)\n const config = normalizeCapRegistry(deployment)\n const capAddress = tx.moveCall({\n target: '0x2::object::id_address',\n typeArguments: [capType],\n arguments: [cap]\n })\n tx.moveCall({\n target: `${config.packageId}::multiply_registry::register_mul_for_account_cap`,\n arguments: [\n tx.object(config.objectId),\n capAddress,\n tx.pure.u64(key.strategyNumericId),\n tx.pure.u64(key.strategyVersion)\n ]\n })\n}\n"],"names":["ACCOUNT_CAP_TYPE","ACCOUNT_CAP_TYPES","normalizeEnv","env","check","accountCapType","type","assertRegistryUsable","explicitRegistry","MAINNET_CAP_REGISTRY","normalizeCapRegistry","config","packageId","address","objectId","registryKeyString","key","id","uint","version","U64_MAX","indexRegistryStrategies","strategies","byKey","ids","strategy","decodeRegistryEntries","values","bcs","versions","caps","keys","i","registerCreatedCapPTB","tx","cap","deployment","capType","capAddress"],"mappings":";;AAKO,MAAMA,IACX,2FAGWC,IAAgE,OAAO,OAAO;AAAA,EACzF,MAAMD;AAAA,EACN,KAAK;AACP,CAAC;AAEM,SAASE,EAAaC,GAAuB;AAClD,SAAIA,MAAQ,SAAkB,UAC9BC;AAAA;AAAA,IAEED,MAAQ,UAAUA,MAAQ;AAAA,IAC1B;AAAA,IACA,yBAAyB,OAAOA,CAAG,CAAC;AAAA,EAAA,GAE/BA;AACT;AAEO,SAASE,EAAeF,GAAsB;AACnD,QAAMG,IAAOL,EAAkBE,CAAG;AAClC,SAAAC,EAAME,GAAM,sBAAsB,iDAAiDH,CAAG,EAAE,GACjFG;AACT;AAMO,SAASC,EAAqBJ,GAAcK,GAA2B;AAC5E,EAAAJ;AAAA,IACED,MAAQ,UAAUK;AAAA,IAClB;AAAA,IACA,YAAYL,CAAG;AAAA,EAAA;AAEnB;AAEO,MAAMM,IAAoD,OAAO,OAAO;AAAA,EAC7E,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;AAEM,SAASC,EAAqBC,GAA8C;AACjF,EAAAP,EAAMO,GAAQ,YAAY,eAAe,oBAAoB,8BAA8B;AAC3F,QAAMC,IAAYC,EAAQF,EAAO,SAAS,GACxCG,IAAWD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ts
CHANGED
|
@@ -6,6 +6,7 @@ export declare function createMultiplyClient(options?: MultiplyOptions): {
|
|
|
6
6
|
strategy?: Strategy;
|
|
7
7
|
}) => Promise<Position[]>;
|
|
8
8
|
quote: (owner: string, suppliedStrategy: Strategy, action: Action, constraints: Constraints) => Promise<MultiplyQuote>;
|
|
9
|
-
buildPTB: (tx: Transaction,
|
|
9
|
+
buildPTB: (tx: Transaction, q: MultiplyQuote, inputs: BuildInputs) => Promise<BuildResult>;
|
|
10
|
+
buildPTBForSimulation: (tx: Transaction, q: MultiplyQuote, coins: BuildInputs["coins"]) => Promise<BuildResult>;
|
|
10
11
|
};
|
|
11
12
|
//# sourceMappingURL=client.d.ts.map
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"
|
|
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;mBA2rBH,WAAW,KAAK,aAAa,UAAU,WAAW;gCAKrC,WAAW,KAAK,aAAa,SAAS,WAAW,CAAC,OAAO,CAAC;EAK9F"}
|