@naviprotocol/multiply 0.0.0-stage → 0.2.0-preview.20261102.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 +175 -2
- package/dist/client.d.ts +11 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +477 -0
- package/dist/client.js.map +1 -0
- package/dist/converters.d.ts +16 -0
- package/dist/converters.d.ts.map +1 -0
- package/dist/converters.js +233 -0
- package/dist/converters.js.map +1 -0
- package/dist/data-source.d.ts +11 -0
- package/dist/data-source.d.ts.map +1 -0
- package/dist/data-source.js +220 -0
- package/dist/data-source.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/planner.d.ts +28 -0
- package/dist/planner.d.ts.map +1 -0
- package/dist/planner.js +250 -0
- package/dist/planner.js.map +1 -0
- package/dist/strategies.d.ts +21 -0
- package/dist/strategies.d.ts.map +1 -0
- package/dist/strategies.js +25 -0
- package/dist/strategies.js.map +1 -0
- package/dist/types.d.ts +177 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.d.ts +25 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +83 -0
- package/dist/utils.js.map +1 -0
- package/package.json +51 -4
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @naviprotocol/multiply
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AccountCap-based NAVI Multiply strategy engine for wallets, Auto Vault and Open API.
|
|
4
|
+
Default NAVI reads, native Volo/Haedal quotes and Astros fallback are included.
|
|
5
|
+
The package builds composable Sui PTBs. It never signs or broadcasts transactions.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Transaction } from '@mysten/sui/transactions'
|
|
9
|
+
import { createMultiplyClient, strategies } from '@naviprotocol/multiply'
|
|
10
|
+
|
|
11
|
+
const multiply = createMultiplyClient()
|
|
12
|
+
const positions = await multiply.getPosition(address, {
|
|
13
|
+
strategy: strategies.vsuiSui, // omit to read all configured strategies
|
|
14
|
+
})
|
|
15
|
+
const quote = await multiply.quote(
|
|
16
|
+
address,
|
|
17
|
+
strategies.vsuiSui,
|
|
18
|
+
{ type: 'open', amount: '10000000000', targetLeverage: '2' },
|
|
19
|
+
{ minHealthFactor: '1.15', maxSlippageBps: 50, maxLeverage: '3' },
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
const tx = new Transaction()
|
|
23
|
+
const input = tx.splitCoins(tx.gas, ['10000000000'])[0]
|
|
24
|
+
const built = await multiply.buildPTB(tx, quote, {
|
|
25
|
+
coins: [{ coinType: strategies.vsuiSui.principalCoinType, coin: input }],
|
|
26
|
+
})
|
|
27
|
+
// Astros route change goes directly to address; the caller handles the remaining assets.
|
|
28
|
+
if (built.createdAccountCap) tx.transferObjects([built.createdAccountCap], address)
|
|
29
|
+
if (built.coins.length) tx.transferObjects(built.coins.map(c => c.coin), address)
|
|
30
|
+
tx.setSender(address)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Public API
|
|
34
|
+
|
|
35
|
+
| Method | Behavior |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `getPosition(address, { strategy? })` | Always returns an array. Missing Cap → `[]`; existing empty Cap → zero position. Returns Cap, amounts, HF and leverage. |
|
|
38
|
+
| `quote(address, strategy, action, constraints)` | Resolves the Cap and reads the snapshot internally. Does not create chain objects. Produces a JSON-serializable estimate and a frozen, versioned execution plan. |
|
|
39
|
+
| `buildPTB(tx, quote, inputs)` | Rechecks Cap, market, fees, state drift and expiry, then appends commands. Returns Cap and every remaining Coin for the caller to use. |
|
|
40
|
+
|
|
41
|
+
Actions: `open`, `add_principal`, `remove_principal`, `set_leverage`, `repay`,
|
|
42
|
+
`add_collateral`, `close`. Amounts are **raw integer strings**, never JS numbers.
|
|
43
|
+
Leverage/HF use decimal strings; slippage uses integer basis points. An action
|
|
44
|
+
with an `amount` requires a positive u64 value. `set_leverage` takes
|
|
45
|
+
`targetLeverage`; add/remove principal optionally take it and otherwise preserve
|
|
46
|
+
the current estimated leverage. `close` takes no amount.
|
|
47
|
+
|
|
48
|
+
`estimate.inputs` defines the required Coin types and amounts. Supply one Coin
|
|
49
|
+
per type; the builder splits only the quoted amount and returns its remainder.
|
|
50
|
+
Repay overpayment is returned. Removing principal guarantees **at least** the
|
|
51
|
+
requested output; any surplus also returns to the caller. `healthFactor: null`
|
|
52
|
+
means no debt; `leverage: null` means an empty position or non-positive equity; inspect the returned balances. These ratios use NAVI's
|
|
53
|
+
oracle valuation, which can differ from a token's market or redemption value.
|
|
54
|
+
|
|
55
|
+
`execution` is opaque to callers. Do not modify it, reroute during build or cache
|
|
56
|
+
it beyond `expiresAt`. Min outputs include conversion wear/fees before slippage.
|
|
57
|
+
The solver recomputes leverage with conversion quotes, flash fees and NAVI borrow
|
|
58
|
+
fees. One atomic conversion leg is used per initial-release plan, so the total
|
|
59
|
+
slippage budget applies to that leg. Exact integer arithmetic is used throughout.
|
|
60
|
+
|
|
61
|
+
## Converters and injection
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import {
|
|
65
|
+
createMultiplyClient, createNaviDataSource, voloConverter, haedalConverter,
|
|
66
|
+
} from '@naviprotocol/multiply'
|
|
67
|
+
|
|
68
|
+
const multiply = createMultiplyClient({
|
|
69
|
+
client,
|
|
70
|
+
dataSource: createNaviDataSource({ client }), // optional, or your DataSource
|
|
71
|
+
converters: [voloConverter({ client }), haedalConverter({ client })],
|
|
72
|
+
// fallbackConverter: customConverter, // optional; default is Astros
|
|
73
|
+
})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
A strategy describes tokens and lending market, not a converter. Eligible primary
|
|
77
|
+
converters are compared by minimum net output, then stable ID. If none can quote,
|
|
78
|
+
the fallback is used. A malformed primary quote fails instead of becoming a
|
|
79
|
+
silently accepted route. Volo uses its live `get_amount_out` view; Haedal uses
|
|
80
|
+
live conversion views and configured fees. Only immediate Coin → Coin conversion
|
|
81
|
+
is supported. Native instant redemption can become unavailable; requesting a new
|
|
82
|
+
quote can select the fallback. A build never silently selects another route.
|
|
83
|
+
|
|
84
|
+
Astros uses the published `@naviprotocol/astros-aggregator-sdk@2.0.7` with its default
|
|
85
|
+
fee and positive-slippage behavior. Route change is transferred directly to the
|
|
86
|
+
user in `quote.address`, independently of the transaction sender or gas sponsor.
|
|
87
|
+
It is not included in `built.coins`. The engine's other remaining coins are still
|
|
88
|
+
returned to the caller. Its numeric route builder limits supported amounts to safe
|
|
89
|
+
JS integers; larger routes are explicitly rejected. Minimum output, health factor
|
|
90
|
+
and flash repayment checks remain enforced; extra fees can cause a PTB to abort
|
|
91
|
+
if those bounds cannot be met.
|
|
92
|
+
|
|
93
|
+
When calling the exported Astros converter directly, pass the real user address as
|
|
94
|
+
the fourth build argument: `converter.buildPTB(tx, quote, coin, { changeRecipient: address })`.
|
|
95
|
+
A missing, malformed or zero recipient is rejected before appending swap commands.
|
|
96
|
+
|
|
97
|
+
A custom `DataSource` must supply complete, coherent, verified Cap/position/risk/
|
|
98
|
+
price/fee data and prepare the oracle commands for its network. Failures must not
|
|
99
|
+
be converted to empty positions. Custom converters and data sources execute
|
|
100
|
+
trusted application code. Built-in deployments target **Sui mainnet**; passing a
|
|
101
|
+
testnet client alone does not switch their contract addresses.
|
|
102
|
+
|
|
103
|
+
## AccountCap and Vault integration
|
|
104
|
+
|
|
105
|
+
New Caps use `navi:multiply:v1:<strategyId>` as the name and the strategy definition
|
|
106
|
+
as the description. Existing Caps are reused after close. A default reader
|
|
107
|
+
excludes Caps registered to the Lending E-Mode product, validates strategy
|
|
108
|
+
metadata, and rejects duplicates. It never registers a Multiply Cap as an E-Mode
|
|
109
|
+
product Cap.
|
|
110
|
+
|
|
111
|
+
**One wallet/strategy is enforced by discovery and SDK checks only.** Two concurrent
|
|
112
|
+
transactions or direct contract calls can create duplicate names; renaming or
|
|
113
|
+
transferring a Cap can bypass this convention. A contract registry is needed for
|
|
114
|
+
a chain-enforced uniqueness guarantee. Names/descriptions are not authorization.
|
|
115
|
+
|
|
116
|
+
Auto Vault can inject a resolver for wrapped Caps and pass a PTB result through
|
|
117
|
+
`inputs.accountCap`. The resolver/caller is responsible for binding that transaction
|
|
118
|
+
result to the quoted Cap and snapshot; a transaction result cannot be authenticated
|
|
119
|
+
by its JS handle. Plain object-ID overrides must match the quoted ID. The engine
|
|
120
|
+
keeps Cap transfer/wrapping and final Coin custody with the caller, except for
|
|
121
|
+
Astros route change, which is refunded directly to `quote.address`. Vault integrations
|
|
122
|
+
must account for that refund policy or inject a converter with their custody policy.
|
|
123
|
+
|
|
124
|
+
Open API should retain quotes server-side or authenticate its quote envelope.
|
|
125
|
+
The SHA-256 checksum detects accidental mutation; it is **not** a signature or
|
|
126
|
+
permission to trust arbitrary client-supplied routes. A composed PTB must be
|
|
127
|
+
simulated by its caller before signing. HF, minimum conversion output, requested
|
|
128
|
+
principal output and optional maximum leverage are also enforced on chain. Close
|
|
129
|
+
reads the current balance in the PTB and asserts that both balances are zero.
|
|
130
|
+
|
|
131
|
+
## Initial release boundaries
|
|
132
|
+
|
|
133
|
+
- Built-in strategies: `vsuiSui`, `hasuiSui`, in their dedicated NAVI markets.
|
|
134
|
+
Main-market flash liquidity is independent of the position market.
|
|
135
|
+
- Principal must equal debt; collateral must be distinct. The default reader
|
|
136
|
+
currently supports nine-decimal pools. An unsupported E-Mode override is rejected.
|
|
137
|
+
- Delayed redemption/claim workflows, generic mixed-asset positions, cross-market
|
|
138
|
+
position aggregation, APY/history and on-chain unique-Cap registration are not
|
|
139
|
+
implemented. The data source checks assets in the selected market; it cannot
|
|
140
|
+
establish exclusive use of a Cap across every other market.
|
|
141
|
+
- Source reads and quote→build checks do not lock chain state. Changed liquidity,
|
|
142
|
+
prices or fees can make the transaction abort. Discard a partially built PTB
|
|
143
|
+
after a builder/network error; obtain a fresh quote rather than reuse it.
|
|
144
|
+
- Package publication is a separate release step. The implementation is accompanied
|
|
145
|
+
by mainnet simulation evidence, not signed/persisted chain transactions.
|
|
146
|
+
|
|
147
|
+
## Reproduce
|
|
148
|
+
|
|
149
|
+
From the monorepo root (Node 24 and pnpm 10.1.0 used for the recorded run):
|
|
150
|
+
|
|
151
|
+
```sh
|
|
152
|
+
pnpm install --frozen-lockfile
|
|
153
|
+
pnpm --filter @naviprotocol/lending --filter @naviprotocol/astros-aggregator-sdk build
|
|
154
|
+
pnpm --filter @naviprotocol/multiply typecheck
|
|
155
|
+
pnpm --filter @naviprotocol/multiply build
|
|
156
|
+
pnpm --filter @naviprotocol/multiply test:e2e
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The test runner was committed before implementation (`57804f1`, with live-schema
|
|
160
|
+
fixture corrections in `fba268f`). No unit tests or mocked protocol implementations
|
|
161
|
+
were added. See [failure inventory](e2e/FAILURE-MATRIX.md) and [verification notes](docs/verification.md).
|
|
162
|
+
|
|
163
|
+
Each run writes input, frozen quotes, unsigned transaction bytes, commands, actual
|
|
164
|
+
post-operation balances/HF, simulation responses, a report and SHA-256 manifest
|
|
165
|
+
under `out/multiply/`. `MULTIPLY_E2E_ADDRESS` selects a **public funded simulation
|
|
166
|
+
address**; its key is neither read nor required. Defaults use the public NAVI
|
|
167
|
+
oracle sender. `MULTIPLY_E2E_ONLY` selects scenarios; only a complete run constitutes
|
|
168
|
+
full-suite evidence. Live chain state and service availability can change results.
|
|
169
|
+
The lifecycle fixture is real VM execution with a transient injected snapshot;
|
|
170
|
+
it does not prove persisted discovery or concurrent uniqueness.
|
|
171
|
+
|
|
172
|
+
The packed-package consumer replay is documented in the verification report.
|
|
173
|
+
|
|
174
|
+
The package pins published Lending 2.1.0 and Astros 2.0.7 dependencies. The clean
|
|
175
|
+
package consumer installs only the Multiply tarball locally and resolves these
|
|
176
|
+
dependencies from npm, without workspace links or dependency overrides.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Transaction } from '@mysten/sui/transactions';
|
|
2
|
+
import { Action, BuildInputs, BuildResult, Constraints, MultiplyOptions, MultiplyQuote, Position, Strategy } from './types.js';
|
|
3
|
+
|
|
4
|
+
export declare function createMultiplyClient(options?: MultiplyOptions): {
|
|
5
|
+
getPosition: (owner: string, query?: {
|
|
6
|
+
strategy?: Strategy;
|
|
7
|
+
}) => Promise<Position[]>;
|
|
8
|
+
quote: (owner: string, suppliedStrategy: Strategy, action: Action, constraints: Constraints) => Promise<MultiplyQuote>;
|
|
9
|
+
buildPTB: (tx: Transaction, suppliedQuote: MultiplyQuote, inputs: BuildInputs) => Promise<BuildResult>;
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,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;AAiBhB,wBAAgB,oBAAoB,CAAC,OAAO,GAAE,eAAoB;yBAoEvD,MAAM,UACN;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAC7B,OAAO,CAAC,QAAQ,EAAE,CAAC;mBAuBb,MAAM,oBACK,QAAQ,UAClB,MAAM,eACD,WAAW,KACvB,OAAO,CAAC,aAAa,CAAC;mBAoEnB,WAAW,iBACA,aAAa,UACpB,WAAW,KAClB,OAAO,CAAC,WAAW,CAAC;EA6axB"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
import { voloConverter as le, haedalConverter as ue, astrosConverter as pe, validateConversion as me } from "./converters.js";
|
|
2
|
+
import { defaultClient as de, createNaviDataSource as ge } from "./data-source.js";
|
|
3
|
+
import { strategies as Ce, capName as X } from "./strategies.js";
|
|
4
|
+
import { validateAction as ae, metrics as oe, plan as be, chooseConversion as fe } from "./planner.js";
|
|
5
|
+
import { check as i, jsonCopy as P, checksum as $, address as y, sameCoin as F, BN as s, minOutputGuard as Y, uint as M, coinType as W } from "./utils.js";
|
|
6
|
+
function Te(v = {}) {
|
|
7
|
+
const R = v.client ?? de(), C = v.dataSource ?? ge({ client: R, services: v.services }), J = v.converters ?? [le({ client: R }), ue({ client: R })], K = v.fallbackConverter ?? pe({ services: v.services }), L = /* @__PURE__ */ new Map();
|
|
8
|
+
for (const e of [...J, K])
|
|
9
|
+
i(!L.has(e.id), "INVALID_ARGUMENT", `Duplicate converter id: ${e.id}`), L.set(e.id, e);
|
|
10
|
+
const ne = v.strategies ?? Object.values(Ce);
|
|
11
|
+
function U(e) {
|
|
12
|
+
i(
|
|
13
|
+
typeof e?.id == "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(e.id),
|
|
14
|
+
"INVALID_ARGUMENT",
|
|
15
|
+
"Strategy id must be a stable ASCII slug"
|
|
16
|
+
), i(
|
|
17
|
+
typeof e.market == "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(e.market),
|
|
18
|
+
"INVALID_ARGUMENT",
|
|
19
|
+
"Missing market"
|
|
20
|
+
), i(
|
|
21
|
+
e.emodeId === void 0,
|
|
22
|
+
"STRATEGY_UNSUPPORTED",
|
|
23
|
+
"E-Mode risk overrides are not supported in this release"
|
|
24
|
+
);
|
|
25
|
+
const p = {
|
|
26
|
+
...e,
|
|
27
|
+
principalCoinType: W(e.principalCoinType),
|
|
28
|
+
collateralCoinType: W(e.collateralCoinType),
|
|
29
|
+
debtCoinType: W(e.debtCoinType)
|
|
30
|
+
};
|
|
31
|
+
return i(
|
|
32
|
+
F(p.principalCoinType, p.debtCoinType) && !F(p.collateralCoinType, p.debtCoinType),
|
|
33
|
+
"STRATEGY_UNSUPPORTED",
|
|
34
|
+
"Requires principal = debt and a distinct collateral token"
|
|
35
|
+
), p;
|
|
36
|
+
}
|
|
37
|
+
async function B(e, p) {
|
|
38
|
+
const u = (await C.listAccountCaps(e)).filter((m) => m.strategyId === p.id);
|
|
39
|
+
i(
|
|
40
|
+
u.length <= 1,
|
|
41
|
+
"DUPLICATE_ACCOUNT_CAP",
|
|
42
|
+
"More than one Multiply Cap exists for this wallet and strategy"
|
|
43
|
+
);
|
|
44
|
+
const t = u[0];
|
|
45
|
+
return t && (y(t.id), y(t.accountOwner), i(
|
|
46
|
+
t.name === X(p.id),
|
|
47
|
+
"INVALID_ACCOUNT_CAP",
|
|
48
|
+
"Cap name does not match strategy"
|
|
49
|
+
), t.strategy && i(
|
|
50
|
+
await $(U(t.strategy)) === await $(p),
|
|
51
|
+
"INVALID_ACCOUNT_CAP",
|
|
52
|
+
"Stored strategy definition differs from the requested market or tokens"
|
|
53
|
+
)), t;
|
|
54
|
+
}
|
|
55
|
+
async function ce(e, p = {}) {
|
|
56
|
+
e = y(e);
|
|
57
|
+
const u = [];
|
|
58
|
+
for (const t of (p.strategy ? [p.strategy] : ne).map(
|
|
59
|
+
U
|
|
60
|
+
)) {
|
|
61
|
+
const m = await B(e, t);
|
|
62
|
+
if (!m) continue;
|
|
63
|
+
const a = await C.readMarket(t), c = await C.readPosition(m, t, a);
|
|
64
|
+
M(c.collateralAmount), M(c.debtAmount), u.push({
|
|
65
|
+
address: e,
|
|
66
|
+
strategy: t,
|
|
67
|
+
accountCap: m,
|
|
68
|
+
...c,
|
|
69
|
+
...oe(c, a)
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return u;
|
|
73
|
+
}
|
|
74
|
+
async function re(e, p, u, t) {
|
|
75
|
+
e = y(e), i(e !== y("0x0"), "INVALID_ARGUMENT", "Multiply owner cannot be zero"), ae(u, t);
|
|
76
|
+
const m = U(p), a = await B(e, m);
|
|
77
|
+
i(
|
|
78
|
+
a || u.type === "open",
|
|
79
|
+
"POSITION_NOT_FOUND",
|
|
80
|
+
"Only open may create a Multiply Cap"
|
|
81
|
+
);
|
|
82
|
+
const c = await C.readMarket(m), b = a ? await C.readPosition(a, m, c) : { collateralAmount: "0", debtAmount: "0" };
|
|
83
|
+
M(b.collateralAmount), M(b.debtAmount);
|
|
84
|
+
const g = b.collateralAmount === "0" && b.debtAmount === "0";
|
|
85
|
+
if (i(
|
|
86
|
+
u.type !== "open" || g,
|
|
87
|
+
"POSITION_EXISTS",
|
|
88
|
+
"Use add_principal or set_leverage for an existing position"
|
|
89
|
+
), i(
|
|
90
|
+
u.type === "open" || !g,
|
|
91
|
+
"POSITION_NOT_FOUND",
|
|
92
|
+
"Empty position; use open to reuse this Cap"
|
|
93
|
+
), "targetLeverage" in u && u.targetLeverage) {
|
|
94
|
+
const f = s.minimum(
|
|
95
|
+
new s(c.ltv).div(c.borrowWeight),
|
|
96
|
+
new s(c.liquidationThreshold).div(
|
|
97
|
+
new s(c.borrowWeight).times(t.minHealthFactor)
|
|
98
|
+
)
|
|
99
|
+
), Q = new s(1).minus(new s(1).div(u.targetLeverage));
|
|
100
|
+
i(
|
|
101
|
+
Q.lte(f),
|
|
102
|
+
"CONSTRAINT_VIOLATION",
|
|
103
|
+
"Target leverage exceeds protocol or health factor limits"
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
const n = await C.readBorrowFeeBps(c, a?.accountOwner), I = await be(
|
|
107
|
+
m,
|
|
108
|
+
u,
|
|
109
|
+
t,
|
|
110
|
+
b,
|
|
111
|
+
c,
|
|
112
|
+
n,
|
|
113
|
+
(f) => fe(f, J, K)
|
|
114
|
+
), _ = {
|
|
115
|
+
address: e,
|
|
116
|
+
strategy: m,
|
|
117
|
+
action: P(u),
|
|
118
|
+
constraints: P(t),
|
|
119
|
+
expiresAt: Math.min(
|
|
120
|
+
Date.now() + 12e4,
|
|
121
|
+
...I.execution.conversions.map((f) => f.expiresAt)
|
|
122
|
+
),
|
|
123
|
+
estimate: I.estimate,
|
|
124
|
+
execution: {
|
|
125
|
+
...I.execution,
|
|
126
|
+
accountCap: a ? { kind: "existing", ...a } : { kind: "create", name: X(m.id) },
|
|
127
|
+
checksum: ""
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
return _.execution.checksum = await $(_), P(_);
|
|
131
|
+
}
|
|
132
|
+
async function ie(e, p, u) {
|
|
133
|
+
const t = P(p);
|
|
134
|
+
i(t.execution?.version === 1, "INVALID_QUOTE", "Unknown quote version");
|
|
135
|
+
const m = t.execution.checksum;
|
|
136
|
+
t.execution.checksum = "", i(
|
|
137
|
+
m === await $(t),
|
|
138
|
+
"INVALID_QUOTE",
|
|
139
|
+
"Quote contents have changed; request a fresh quote"
|
|
140
|
+
), t.execution.checksum = m, i(
|
|
141
|
+
Number.isSafeInteger(t.expiresAt) && t.expiresAt > Date.now(),
|
|
142
|
+
"QUOTE_EXPIRED",
|
|
143
|
+
"Multiply quote expired"
|
|
144
|
+
), i(y(t.address) !== y("0x0"), "INVALID_ARGUMENT", "Multiply owner cannot be zero"), U(t.strategy), ae(t.action, t.constraints);
|
|
145
|
+
const a = t.execution, c = t.strategy, b = u.coins ?? [];
|
|
146
|
+
i(
|
|
147
|
+
b.length === t.estimate.inputs.length,
|
|
148
|
+
"INVALID_INPUTS",
|
|
149
|
+
"Provide exactly the quoted input coins"
|
|
150
|
+
);
|
|
151
|
+
for (const o of t.estimate.inputs)
|
|
152
|
+
i(
|
|
153
|
+
b.filter((l) => F(l.coinType, o.coinType)).length === 1,
|
|
154
|
+
"INVALID_INPUTS",
|
|
155
|
+
`Missing or duplicate input: ${o.coinType}`
|
|
156
|
+
);
|
|
157
|
+
for (const o of a.conversions)
|
|
158
|
+
i(
|
|
159
|
+
L.has(o.converterId),
|
|
160
|
+
"INVALID_CONVERSION",
|
|
161
|
+
"Quoted converter is not configured"
|
|
162
|
+
), me(
|
|
163
|
+
o,
|
|
164
|
+
{
|
|
165
|
+
coinIn: o.input.coinType,
|
|
166
|
+
coinOut: o.expectedOutput.coinType,
|
|
167
|
+
amountIn: o.input.amount,
|
|
168
|
+
slippageBps: t.constraints.maxSlippageBps
|
|
169
|
+
},
|
|
170
|
+
o.converterId
|
|
171
|
+
);
|
|
172
|
+
const g = await B(t.address, c);
|
|
173
|
+
a.accountCap.kind === "create" ? i(
|
|
174
|
+
!g && !u.accountCap,
|
|
175
|
+
"STALE_QUOTE",
|
|
176
|
+
"Cap was created since quote or an unexpected Cap was supplied"
|
|
177
|
+
) : (i(
|
|
178
|
+
g && g.id === a.accountCap.id && g.accountOwner === a.accountCap.accountOwner,
|
|
179
|
+
"STALE_QUOTE",
|
|
180
|
+
"AccountCap changed since quote"
|
|
181
|
+
), typeof u.accountCap == "string" && i(y(u.accountCap) === y(g.id), "INVALID_INPUTS", "Wrong AccountCap"));
|
|
182
|
+
const n = await C.readMarket(c);
|
|
183
|
+
for (const o of [
|
|
184
|
+
"package",
|
|
185
|
+
"storage",
|
|
186
|
+
"priceOracle",
|
|
187
|
+
"incentiveV2",
|
|
188
|
+
"incentiveV3",
|
|
189
|
+
"limter"
|
|
190
|
+
])
|
|
191
|
+
i(n.config[o] === a.market.config[o], "STALE_QUOTE", `Market ${o} changed`);
|
|
192
|
+
i(
|
|
193
|
+
n.collateral.contract.pool === a.market.collateral.contract.pool && n.debt.contract.pool === a.market.debt.contract.pool && n.flash.poolId === a.market.flash.poolId,
|
|
194
|
+
"STALE_QUOTE",
|
|
195
|
+
"Pool configuration changed"
|
|
196
|
+
);
|
|
197
|
+
const I = g ? await C.readPosition(g, c, n) : { collateralAmount: "0", debtAmount: "0" }, _ = new s(I.collateralAmount).minus(a.snapshot.collateralAmount), f = new s(I.debtAmount).minus(a.snapshot.debtAmount);
|
|
198
|
+
i(
|
|
199
|
+
_.gte(0) && _.lte(new s(a.snapshot.collateralAmount).times("0.0001").plus(1e3)) && f.gte(0) && f.lte(new s(a.snapshot.debtAmount).times("0.0001").plus(1e3)),
|
|
200
|
+
"STALE_QUOTE",
|
|
201
|
+
"Position changed since quote"
|
|
202
|
+
);
|
|
203
|
+
const Q = await C.readBorrowFeeBps(n, g?.accountOwner);
|
|
204
|
+
i(
|
|
205
|
+
new s(a.borrowAmount).times(Q).div(1e4).integerValue().lte(a.borrowFee),
|
|
206
|
+
"STALE_QUOTE",
|
|
207
|
+
"Borrow fee increased"
|
|
208
|
+
), i(n.flash.feeBps === a.market.flash.feeBps, "STALE_QUOTE", "Flash fee changed");
|
|
209
|
+
const q = {
|
|
210
|
+
collateralAmount: new s(a.minCollateralAfter).plus(_).toFixed(0),
|
|
211
|
+
debtAmount: new s(a.debtAfter).plus(t.action.type === "close" ? 0 : f).toFixed(0)
|
|
212
|
+
}, S = oe(q, n);
|
|
213
|
+
i(
|
|
214
|
+
S.healthFactor === null || new s(S.healthFactor).gte(t.constraints.minHealthFactor),
|
|
215
|
+
"STALE_QUOTE",
|
|
216
|
+
"Updated market no longer satisfies HF"
|
|
217
|
+
), i(
|
|
218
|
+
Number.isSafeInteger(n.observedAt) && Date.now() - n.observedAt <= 12e4,
|
|
219
|
+
"STALE_QUOTE",
|
|
220
|
+
"Current market snapshot is stale"
|
|
221
|
+
), t.constraints.maxLeverage && S.leverage && i(
|
|
222
|
+
new s(S.leverage).lte(t.constraints.maxLeverage),
|
|
223
|
+
"STALE_QUOTE",
|
|
224
|
+
"Updated market exceeds maximum leverage"
|
|
225
|
+
), i(
|
|
226
|
+
new s(q.debtAmount).times(n.debtPrice).times(n.borrowWeight).lte(new s(q.collateralAmount).times(n.collateralPrice).times(n.ltv)),
|
|
227
|
+
"STALE_QUOTE",
|
|
228
|
+
"Updated market exceeds LTV"
|
|
229
|
+
), i(
|
|
230
|
+
new s(a.flashAmount).lte(n.flash.max) && (a.flashAmount === "0" || new s(a.flashAmount).gte(n.flash.min)),
|
|
231
|
+
"CAPACITY_EXCEEDED",
|
|
232
|
+
"Flash capacity changed"
|
|
233
|
+
), i(
|
|
234
|
+
new s(a.collateralAfter).minus(a.snapshot.collateralAmount).lte(new s(n.collateral.leftSupply).shiftedBy(9)),
|
|
235
|
+
"CAPACITY_EXCEEDED",
|
|
236
|
+
"Supply capacity changed"
|
|
237
|
+
), i(
|
|
238
|
+
new s(a.borrowAmount).plus(a.borrowFee).lte(n.debt.availableBorrow),
|
|
239
|
+
"CAPACITY_EXCEEDED",
|
|
240
|
+
"Borrow liquidity changed"
|
|
241
|
+
), await C.prepareOracle(e, c, n);
|
|
242
|
+
const r = n.config, k = a.accountCap.kind === "create" ? e.moveCall({ target: `${r.package}::lending::create_account` }) : void 0, A = k ?? u.accountCap ?? e.object(a.accountCap.id);
|
|
243
|
+
k && (e.moveCall({
|
|
244
|
+
target: `${r.package}::account::set_account_name`,
|
|
245
|
+
arguments: [k, e.pure.string(X(c.id))]
|
|
246
|
+
}), e.moveCall({
|
|
247
|
+
target: `${r.package}::account::set_account_description`,
|
|
248
|
+
arguments: [k, e.pure.string(JSON.stringify(c))]
|
|
249
|
+
}));
|
|
250
|
+
const T = [], G = (o, l) => {
|
|
251
|
+
const d = b.find((O) => F(O.coinType, o)), w = e.splitCoins(d.coin, [l])[0];
|
|
252
|
+
return T.push(d), w;
|
|
253
|
+
}, E = (o, l) => e.moveCall({
|
|
254
|
+
target: "0x2::coin::from_balance",
|
|
255
|
+
typeArguments: [l],
|
|
256
|
+
arguments: [o]
|
|
257
|
+
}), se = (o, l) => e.moveCall({ target: "0x2::coin::into_balance", typeArguments: [l], arguments: [o] }), Z = (o) => e.moveCall({
|
|
258
|
+
target: `${r.package}::incentive_v3::deposit_with_account_cap`,
|
|
259
|
+
typeArguments: [c.collateralCoinType],
|
|
260
|
+
arguments: [
|
|
261
|
+
e.object("0x6"),
|
|
262
|
+
e.object(r.storage),
|
|
263
|
+
e.object(n.collateral.contract.pool),
|
|
264
|
+
e.pure.u8(n.collateral.id),
|
|
265
|
+
o,
|
|
266
|
+
e.object(r.incentiveV2),
|
|
267
|
+
e.object(r.incentiveV3),
|
|
268
|
+
A
|
|
269
|
+
]
|
|
270
|
+
}), x = (o) => E(
|
|
271
|
+
e.moveCall({
|
|
272
|
+
target: `${r.package}::incentive_v3::repay_with_account_cap`,
|
|
273
|
+
typeArguments: [c.debtCoinType],
|
|
274
|
+
arguments: [
|
|
275
|
+
e.object("0x6"),
|
|
276
|
+
e.object(r.priceOracle),
|
|
277
|
+
e.object(r.storage),
|
|
278
|
+
e.object(n.debt.contract.pool),
|
|
279
|
+
e.pure.u8(n.debt.id),
|
|
280
|
+
o,
|
|
281
|
+
e.object(r.incentiveV2),
|
|
282
|
+
e.object(r.incentiveV3),
|
|
283
|
+
A
|
|
284
|
+
]
|
|
285
|
+
}),
|
|
286
|
+
c.debtCoinType
|
|
287
|
+
);
|
|
288
|
+
let D, V;
|
|
289
|
+
if (a.flashAmount !== "0") {
|
|
290
|
+
const o = e.moveCall({
|
|
291
|
+
target: `${n.flash.config.package}::lending::flash_loan_with_ctx_v2`,
|
|
292
|
+
typeArguments: [c.debtCoinType],
|
|
293
|
+
arguments: [
|
|
294
|
+
e.object(n.flash.config.flashloanConfig),
|
|
295
|
+
e.object(n.flash.poolId),
|
|
296
|
+
e.pure.u64(a.flashAmount),
|
|
297
|
+
e.object("0x5")
|
|
298
|
+
]
|
|
299
|
+
});
|
|
300
|
+
D = E(o[0], c.debtCoinType), V = o[1];
|
|
301
|
+
}
|
|
302
|
+
const ee = (o) => V ? E(
|
|
303
|
+
e.moveCall({
|
|
304
|
+
target: `${n.flash.config.package}::lending::flash_repay_with_ctx`,
|
|
305
|
+
typeArguments: [c.debtCoinType],
|
|
306
|
+
arguments: [
|
|
307
|
+
e.object("0x6"),
|
|
308
|
+
e.object(n.flash.config.storage),
|
|
309
|
+
e.object(n.flash.poolId),
|
|
310
|
+
V,
|
|
311
|
+
se(o, c.debtCoinType)
|
|
312
|
+
]
|
|
313
|
+
}),
|
|
314
|
+
c.debtCoinType
|
|
315
|
+
) : o, te = async (o) => {
|
|
316
|
+
const l = a.conversions[0], d = await L.get(l.converterId).buildPTB(e, l, o, {
|
|
317
|
+
changeRecipient: t.address
|
|
318
|
+
});
|
|
319
|
+
return Y(e, d.coinOut, l.minOutput.amount), T.push(...d.change), d.coinOut;
|
|
320
|
+
};
|
|
321
|
+
if (a.direction === "repay")
|
|
322
|
+
T.push({
|
|
323
|
+
coinType: c.debtCoinType,
|
|
324
|
+
coin: x(G(c.debtCoinType, t.estimate.inputs[0].amount))
|
|
325
|
+
});
|
|
326
|
+
else if (a.direction === "add_collateral")
|
|
327
|
+
Z(G(c.collateralCoinType, t.estimate.inputs[0].amount));
|
|
328
|
+
else if (a.direction === "increase") {
|
|
329
|
+
let o = D;
|
|
330
|
+
if (t.estimate.inputs.length) {
|
|
331
|
+
const l = G(c.principalCoinType, t.estimate.inputs[0].amount);
|
|
332
|
+
o ? e.mergeCoins(o, [l]) : o = l;
|
|
333
|
+
}
|
|
334
|
+
if (i(o, "INVALID_QUOTE", "Increase plan has no funds"), Z(await te(o)), V) {
|
|
335
|
+
const l = e.moveCall({
|
|
336
|
+
target: `${r.package}::incentive_v3::borrow_with_account_cap_v2`,
|
|
337
|
+
typeArguments: [c.debtCoinType],
|
|
338
|
+
arguments: [
|
|
339
|
+
e.object("0x6"),
|
|
340
|
+
e.object(r.priceOracle),
|
|
341
|
+
e.object(r.storage),
|
|
342
|
+
e.object(n.debt.contract.pool),
|
|
343
|
+
e.pure.u8(n.debt.id),
|
|
344
|
+
e.pure.u64(a.borrowAmount),
|
|
345
|
+
e.object(r.incentiveV2),
|
|
346
|
+
e.object(r.incentiveV3),
|
|
347
|
+
A,
|
|
348
|
+
e.object("0x5")
|
|
349
|
+
]
|
|
350
|
+
});
|
|
351
|
+
T.push({ coinType: c.debtCoinType, coin: ee(E(l, c.debtCoinType)) });
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
const o = D ? x(D) : void 0;
|
|
355
|
+
let l = e.pure.u64(
|
|
356
|
+
a.withdrawAmount
|
|
357
|
+
);
|
|
358
|
+
if (t.action.type === "close") {
|
|
359
|
+
const h = e.moveCall({
|
|
360
|
+
target: `${r.package}::account::account_owner`,
|
|
361
|
+
arguments: [A]
|
|
362
|
+
});
|
|
363
|
+
e.moveCall({
|
|
364
|
+
target: `${r.package}::lending::update_state_of_user`,
|
|
365
|
+
arguments: [e.object("0x6"), e.object(r.storage), h]
|
|
366
|
+
});
|
|
367
|
+
const j = e.moveCall({
|
|
368
|
+
target: `${r.package}::logic::user_collateral_balance`,
|
|
369
|
+
arguments: [e.object(r.storage), e.pure.u8(n.collateral.id), h]
|
|
370
|
+
}), H = e.moveCall({ target: "0x1::u256::try_as_u64", arguments: [j] });
|
|
371
|
+
l = e.moveCall({
|
|
372
|
+
target: "0x1::option::destroy_some",
|
|
373
|
+
typeArguments: ["u64"],
|
|
374
|
+
arguments: [H]
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
const d = E(
|
|
378
|
+
e.moveCall({
|
|
379
|
+
target: `${r.package}::incentive_v3::withdraw_with_account_cap_v2`,
|
|
380
|
+
typeArguments: [c.collateralCoinType],
|
|
381
|
+
arguments: [
|
|
382
|
+
e.object("0x6"),
|
|
383
|
+
e.object(r.priceOracle),
|
|
384
|
+
e.object(r.storage),
|
|
385
|
+
e.object(n.collateral.contract.pool),
|
|
386
|
+
e.pure.u8(n.collateral.id),
|
|
387
|
+
l,
|
|
388
|
+
e.object(r.incentiveV2),
|
|
389
|
+
e.object(r.incentiveV3),
|
|
390
|
+
A,
|
|
391
|
+
e.object("0x5")
|
|
392
|
+
]
|
|
393
|
+
}),
|
|
394
|
+
c.collateralCoinType
|
|
395
|
+
), w = e.splitCoins(d, [a.withdrawAmount])[0];
|
|
396
|
+
T.push({ coinType: c.collateralCoinType, coin: d });
|
|
397
|
+
const O = await te(w);
|
|
398
|
+
o && e.mergeCoins(O, [o]);
|
|
399
|
+
const N = ee(O);
|
|
400
|
+
t.action.type === "remove_principal" && Y(e, N, t.action.amount);
|
|
401
|
+
for (const h of t.estimate.minOutputs) Y(e, N, h.amount);
|
|
402
|
+
T.push({ coinType: c.principalCoinType, coin: N });
|
|
403
|
+
}
|
|
404
|
+
const z = e.moveCall({
|
|
405
|
+
target: `${r.package}::account::account_owner`,
|
|
406
|
+
arguments: [A]
|
|
407
|
+
});
|
|
408
|
+
if (t.action.type === "close")
|
|
409
|
+
for (const [o, l] of [
|
|
410
|
+
["user_collateral_balance", n.collateral.id],
|
|
411
|
+
["user_loan_balance", n.debt.id]
|
|
412
|
+
]) {
|
|
413
|
+
const d = e.moveCall({
|
|
414
|
+
target: `${r.package}::logic::${o}`,
|
|
415
|
+
arguments: [e.object(r.storage), e.pure.u8(l), z]
|
|
416
|
+
}), w = e.moveCall({
|
|
417
|
+
target: "0x1::u256::checked_sub",
|
|
418
|
+
arguments: [e.pure.u256("0"), d]
|
|
419
|
+
});
|
|
420
|
+
e.moveCall({
|
|
421
|
+
target: "0x1::option::destroy_some",
|
|
422
|
+
typeArguments: ["u256"],
|
|
423
|
+
arguments: [w]
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
if (t.constraints.maxLeverage !== void 0) {
|
|
427
|
+
const o = (h, j) => e.moveCall({
|
|
428
|
+
target: `${r.package}::logic::${h}`,
|
|
429
|
+
arguments: [
|
|
430
|
+
e.object("0x6"),
|
|
431
|
+
e.object(r.priceOracle),
|
|
432
|
+
e.object(r.storage),
|
|
433
|
+
e.pure.u8(j),
|
|
434
|
+
z
|
|
435
|
+
]
|
|
436
|
+
}), l = (h, j) => {
|
|
437
|
+
const H = e.moveCall({
|
|
438
|
+
target: "0x1::u256::checked_mul",
|
|
439
|
+
arguments: [h, e.pure.u256(j)]
|
|
440
|
+
});
|
|
441
|
+
return e.moveCall({
|
|
442
|
+
target: "0x1::option::destroy_some",
|
|
443
|
+
typeArguments: ["u256"],
|
|
444
|
+
arguments: [H]
|
|
445
|
+
});
|
|
446
|
+
}, d = new s(t.constraints.maxLeverage).shiftedBy(12).integerValue(s.ROUND_FLOOR), w = l(
|
|
447
|
+
o("user_collateral_value", n.collateral.id),
|
|
448
|
+
d.minus("1e12").toFixed(0)
|
|
449
|
+
), O = l(o("user_loan_value", n.debt.id), d.toFixed(0)), N = e.moveCall({
|
|
450
|
+
target: "0x1::u256::checked_sub",
|
|
451
|
+
arguments: [w, O]
|
|
452
|
+
});
|
|
453
|
+
e.moveCall({
|
|
454
|
+
target: "0x1::option::destroy_some",
|
|
455
|
+
typeArguments: ["u256"],
|
|
456
|
+
arguments: [N]
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
return e.moveCall({
|
|
460
|
+
target: `${r.limter}::navi_adaptor::verify_navi_position_healthy`,
|
|
461
|
+
arguments: [
|
|
462
|
+
e.object("0x6"),
|
|
463
|
+
e.object(r.storage),
|
|
464
|
+
e.object(r.priceOracle),
|
|
465
|
+
z,
|
|
466
|
+
e.pure.u256(
|
|
467
|
+
new s(t.constraints.minHealthFactor).shiftedBy(27).integerValue(s.ROUND_CEIL).toFixed(0)
|
|
468
|
+
)
|
|
469
|
+
]
|
|
470
|
+
}), { coins: T, accountCap: A, createdAccountCap: k };
|
|
471
|
+
}
|
|
472
|
+
return { getPosition: ce, quote: re, buildPTB: ie };
|
|
473
|
+
}
|
|
474
|
+
export {
|
|
475
|
+
Te as createMultiplyClient
|
|
476
|
+
};
|
|
477
|
+
//# sourceMappingURL=client.js.map
|