@naviprotocol/multiply 0.2.0-preview.20261102.2 → 0.2.0-preview.20261118.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/dist/planner.js CHANGED
@@ -1,16 +1,16 @@
1
- import { check as a, uint as G, decimal as R, BN as w, ceil as q, floor as P, MultiplyError as ee } from "./utils.js";
2
- import { validateConversion as k } from "./converters.js";
3
- import { atomPrices as te, amountCushion as se, borrowCapacity as ae, supplyCapacity as re, withinLtv as ue } from "./amounts.js";
4
- const l = (t) => new w(t);
5
- function Y(t, i) {
6
- const h = te(i), A = l(t.collateralAmount).times(h.collateral), n = l(t.debtAmount).times(h.debt), E = A.minus(n);
1
+ import { check as r, uint as X, decimal as S, BN as h, sameCoin as k, ceil as F, floor as D, MultiplyError as B } from "./utils.js";
2
+ import { validateConversion as ne } from "./converters.js";
3
+ import { atomPrices as ae, amountCushion as le, borrowCapacity as pe, supplyCapacity as ce, withinLtv as de } from "./amounts.js";
4
+ const o = (i) => new h(i);
5
+ function ee(i, n) {
6
+ const E = ae(n), b = o(i.collateralAmount).times(E.collateral), u = o(i.debtAmount).times(E.debt), L = b.minus(u);
7
7
  return {
8
- healthFactor: n.isZero() ? null : A.times(i.liquidationThreshold).div(n.times(i.borrowWeight)).toFixed(12),
9
- leverage: A.isZero() && n.isZero() || E.lte(0) ? null : A.div(E).toFixed(12)
8
+ healthFactor: u.isZero() ? null : b.times(n.liquidationThreshold).div(u.times(n.borrowWeight)).toFixed(12),
9
+ leverage: b.isZero() && u.isZero() || L.lte(0) ? null : b.div(L).toFixed(12)
10
10
  };
11
11
  }
12
- function ce(t, i) {
13
- a(
12
+ function Ne(i, n) {
13
+ r(
14
14
  [
15
15
  "open",
16
16
  "add_principal",
@@ -19,65 +19,78 @@ function ce(t, i) {
19
19
  "repay",
20
20
  "add_collateral",
21
21
  "close"
22
- ].includes(t?.type),
22
+ ].includes(i?.type),
23
23
  "INVALID_ARGUMENT",
24
24
  "Unknown Multiply action"
25
- ), ["open", "add_principal", "remove_principal", "repay", "add_collateral"].includes(t.type) && (a("amount" in t, "INVALID_ARGUMENT", "This action requires an amount"), G(t.amount, !1)), (t.type === "open" || t.type === "set_leverage") && R(t.targetLeverage, "1"), "targetLeverage" in t && t.targetLeverage !== void 0 && R(t.targetLeverage, "1"), a(
26
- Number.isInteger(i?.maxSlippageBps) && i.maxSlippageBps >= 0 && i.maxSlippageBps < 1e4,
25
+ ), ["open", "add_principal", "remove_principal", "repay", "add_collateral"].includes(i.type) && (r("amount" in i, "INVALID_ARGUMENT", "This action requires an amount"), X(i.amount, !1)), (i.type === "open" || i.type === "set_leverage") && S(i.targetLeverage, "1"), "targetLeverage" in i && i.targetLeverage !== void 0 && S(i.targetLeverage, "1"), r(
26
+ Number.isInteger(n?.maxSlippageBps) && n.maxSlippageBps >= 0 && n.maxSlippageBps < 1e4,
27
27
  "INVALID_ARGUMENT",
28
28
  "Slippage must be integer bps in [0, 10000)"
29
- ), R(i.minHealthFactor, "1"), i.maxLeverage !== void 0 && R(i.maxLeverage, "1");
29
+ ), S(n.minHealthFactor, "1"), n.maxLeverage !== void 0 && S(n.maxLeverage, "1");
30
30
  }
31
- async function ve(t, i, h) {
32
- const A = i.filter((p) => p.supports(t.coinIn, t.coinOut)), n = await Promise.allSettled(A.map((p) => p.quote(t))), E = [];
33
- for (let p = 0; p < n.length; p++) {
34
- const u = n[p];
35
- u.status === "fulfilled" && (k(u.value, t, A[p].id), E.push(u.value));
31
+ async function Ae(i, n, E) {
32
+ const b = n.filter((v) => v.supports(i.coinIn, i.coinOut)), u = await Promise.allSettled(b.map((v) => v.quote(i))), L = [];
33
+ for (let v = 0; v < u.length; v++) {
34
+ const a = u[v];
35
+ if (a.status === "fulfilled")
36
+ ne(a.value, i, b[v].id), L.push(a.value);
37
+ else if (!(a.reason instanceof B) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
38
+ a.reason.code
39
+ ))
40
+ throw a.reason;
36
41
  }
37
- if (E.length)
38
- return E.sort((p, u) => l(u.minOutput.amount).comparedTo(p.minOutput.amount) || p.converterId.localeCompare(u.converterId))[0];
39
- a(
40
- h.supports(t.coinIn, t.coinOut),
42
+ if (L.length)
43
+ return L.sort((v, a) => o(a.minOutput.amount).comparedTo(v.minOutput.amount) || v.converterId.localeCompare(a.converterId))[0];
44
+ r(
45
+ E.supports(i.coinIn, i.coinOut),
41
46
  "NO_CONVERSION_ROUTE",
42
47
  "No converter supports this pair"
43
48
  );
44
49
  try {
45
- const p = await h.quote(t);
46
- return k(p, t, h.id), p;
47
- } catch (p) {
48
- throw new ee(
49
- "NO_CONVERSION_ROUTE",
50
- `All eligible converters failed; fallback: ${p instanceof Error ? p.message : String(p)}`
50
+ const v = await E.quote(i);
51
+ return ne(v, i, E.id), v;
52
+ } catch (v) {
53
+ if (!(v instanceof B) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
54
+ v.code
55
+ ))
56
+ throw v;
57
+ const a = v.code === "CONVERSION_AMOUNT_TOO_SMALL" && u.every(
58
+ (p) => p.status === "rejected" && p.reason instanceof B && p.reason.code === "CONVERSION_AMOUNT_TOO_SMALL"
59
+ );
60
+ throw new B(
61
+ a ? "CONVERSION_AMOUNT_TOO_SMALL" : "NO_CONVERSION_ROUTE",
62
+ "No eligible executable conversion route"
51
63
  );
52
64
  }
53
65
  }
54
- async function fe(t, i, h, A, n, E, p) {
55
- const u = l(A.collateralAmount), c = l(A.debtAmount), { collateral: C, debt: N } = te(n);
56
- a(
57
- C.gt(0) && N.gt(0) && R(n.ltv).lte(1) && R(n.liquidationThreshold).lte(1) && R(n.borrowWeight).gte(1),
66
+ async function Te(i, n, E, b, u, L, v) {
67
+ const a = o(b.collateralAmount), p = o(b.debtAmount), { collateral: N, debt: T } = ae(u);
68
+ r(
69
+ N.gt(0) && T.gt(0) && S(u.ltv).lte(1) && S(u.liquidationThreshold).lte(1) && S(u.borrowWeight).gte(1),
58
70
  "READ_FAILED",
59
71
  "Invalid market risk or price data"
60
72
  );
61
- const B = u.times(C).minus(c.times(N));
62
- a(
63
- u.isZero() && c.isZero() || B.gt(0),
73
+ const Z = a.times(N).minus(p.times(T));
74
+ r(
75
+ a.isZero() && p.isZero() || Z.gt(0),
64
76
  "POSITION_UNSUPPORTED",
65
77
  "Position has non-positive equity"
66
78
  );
67
- const M = Y(A, n), ie = "targetLeverage" in i ? i.targetLeverage : void 0, m = R(ie ?? M.leverage ?? "1", "1");
68
- i.type === "set_leverage" && a(
69
- m.minus(M.leverage ?? "1").abs().gt("0.000001"),
79
+ const Y = ee(b, u), se = "targetLeverage" in n ? n.targetLeverage : void 0, s = S(se ?? Y.leverage ?? "1", "1");
80
+ n.type === "set_leverage" && r(
81
+ s.minus(Y.leverage ?? "1").abs().gt("0.000001"),
70
82
  "NO_OP",
71
83
  "Position already has the requested leverage"
72
- ), G(E), G(n.flash.feeBps), a(
73
- Number.isSafeInteger(n.observedAt) && Date.now() - n.observedAt <= 12e4 && n.observedAt <= Date.now() + 5e3,
84
+ ), X(L), X(u.flash.feeBps), r(
85
+ Number.isSafeInteger(u.observedAt) && Date.now() - u.observedAt <= 12e4 && u.observedAt <= Date.now() + 5e3,
74
86
  "STALE_QUOTE",
75
87
  "Market snapshot is stale"
76
- ), h.maxLeverage && a(m.lte(h.maxLeverage), "CONSTRAINT_VIOLATION", "Target exceeds maxLeverage");
77
- const j = [], Z = [], Q = [], e = {
78
- version: 2,
79
- snapshot: A,
80
- market: n,
88
+ ), E.maxLeverage && r(s.lte(E.maxLeverage), "CONSTRAINT_VIOLATION", "Target exceeds maxLeverage");
89
+ const M = [], P = [], Q = [], t = {
90
+ version: 4,
91
+ funding: { kind: "none" },
92
+ snapshot: b,
93
+ market: u,
81
94
  conversions: [],
82
95
  direction: "increase",
83
96
  flashAmount: "0",
@@ -85,212 +98,288 @@ async function fe(t, i, h, A, n, E, p) {
85
98
  borrowAmount: "0",
86
99
  borrowFee: "0",
87
100
  withdrawAmount: "0",
88
- collateralAfter: u.toFixed(0),
89
- debtAfter: c.toFixed(0),
90
- minCollateralAfter: u.toFixed(0)
91
- }, $ = (r) => l(q(r.times(l(n.flash.feeBps).div(1e4).plus(1)))), oe = (r) => l(P(r.times(E).div(1e4))), L = (r, d) => {
92
- const x = r.times(C), v = x.minus(d.times(N));
93
- return v.gt(0) && x.div(v).minus(m).abs().lte(m.times("0.0001"));
94
- }, le = Date.now() + 45e3;
95
- let ne = 0;
96
- const z = async (r, d) => {
97
- const x = le - Date.now();
98
- a(
99
- ++ne <= 32 && x > 0,
101
+ collateralAfter: a.toFixed(0),
102
+ debtAfter: p.toFixed(0),
103
+ minCollateralAfter: a.toFixed(0)
104
+ }, W = (l) => o(F(l.times(o(u.flash.feeBps).div(1e4).plus(1)))), re = (l) => o(D(l.times(L).div(1e4))), U = (l, f) => {
105
+ const C = l.times(N), g = C.minus(f.times(T));
106
+ return g.gt(0) && C.div(g).minus(s).abs().lte(s.times("0.0001"));
107
+ }, ue = Date.now() + 45e3;
108
+ let me = 0;
109
+ const z = async (l, f) => {
110
+ const C = ue - Date.now();
111
+ r(
112
+ ++me <= 32 && C > 0,
100
113
  "NO_CONVERGENCE",
101
114
  "Conversion quote budget exhausted"
102
115
  );
103
- let v;
116
+ let g;
104
117
  try {
105
118
  return await Promise.race([
106
- p({
107
- amountIn: r,
108
- coinIn: d ? t.debtCoinType : t.collateralCoinType,
109
- coinOut: d ? t.collateralCoinType : t.debtCoinType,
110
- slippageBps: h.maxSlippageBps
119
+ v({
120
+ amountIn: l,
121
+ coinIn: f ? i.debtCoinType : i.collateralCoinType,
122
+ coinOut: f ? i.collateralCoinType : i.debtCoinType,
123
+ slippageBps: E.maxSlippageBps
111
124
  }),
112
- new Promise((o, s) => {
113
- v = setTimeout(
114
- () => s(new ee("NO_CONVERGENCE", "Conversion quote time budget exhausted")),
115
- x
125
+ new Promise((m, _) => {
126
+ g = setTimeout(
127
+ () => _(new B("NO_CONVERGENCE", "Conversion quote time budget exhausted")),
128
+ C
116
129
  );
117
130
  })
118
131
  ]);
119
132
  } finally {
120
- clearTimeout(v);
133
+ clearTimeout(g);
121
134
  }
122
- }, J = (r, d) => j.push({ coinType: r, amount: d });
123
- if (i.type === "repay" || i.type === "add_collateral")
124
- if (e.direction = i.type, J(
125
- i.type === "repay" ? t.debtCoinType : t.collateralCoinType,
126
- i.amount
127
- ), i.type === "repay") {
128
- e.debtAfter = w.maximum(0, c.minus(i.amount)).toFixed(0);
129
- const r = w.maximum(0, l(i.amount).minus(c)).toFixed(0);
130
- r !== "0" && Z.push({ coinType: t.debtCoinType, amount: r });
131
- } else e.collateralAfter = e.minCollateralAfter = u.plus(i.amount).toFixed(0);
132
- else if (i.type === "open" || i.type === "add_principal" || i.type === "set_leverage" && m.gt(M.leverage ?? "1")) {
133
- const r = l("amount" in i ? i.amount : "0");
134
- r.gt(0) && J(t.principalCoinType, r.toFixed(0));
135
- const d = async (y) => {
136
- const S = await z(r.plus(y).toFixed(0), !0), D = $(y), F = oe(D), V = u.plus(S.expectedOutput.amount), K = c.plus(D).plus(F);
135
+ }, te = (l, f) => M.push({ coinType: l, amount: f });
136
+ if (n.type === "repay" || n.type === "add_collateral")
137
+ if (t.direction = n.type, te(
138
+ n.type === "repay" ? i.debtCoinType : i.collateralCoinType,
139
+ n.amount
140
+ ), n.type === "repay") {
141
+ t.debtAfter = h.maximum(0, p.minus(n.amount)).toFixed(0);
142
+ const l = h.maximum(0, o(n.amount).minus(p)).toFixed(0);
143
+ l !== "0" && P.push({ coinType: i.debtCoinType, amount: l });
144
+ } else t.collateralAfter = t.minCollateralAfter = a.plus(n.amount).toFixed(0);
145
+ else if (n.type === "open" || n.type === "add_principal" || n.type === "set_leverage" && s.gt(Y.leverage ?? "1")) {
146
+ const l = o("amount" in n ? n.amount : "0"), f = "inputCoinType" in n && n.inputCoinType ? n.inputCoinType : i.principalCoinType, C = k(f, i.collateralCoinType);
147
+ l.gt(0) && te(f, l.toFixed(0));
148
+ const g = async (I) => {
149
+ const q = I.plus(C ? 0 : l), H = q.gt(0) ? await z(q.toFixed(0), !0) : void 0, V = W(I), G = re(V), ie = a.plus(C ? l : 0).plus(H?.expectedOutput.amount ?? 0), oe = p.plus(V).plus(G);
137
150
  return {
138
- q: S,
139
- F: y,
140
- repayment: D,
141
- fee: F,
142
- c: V,
143
- d: K,
144
- residual: K.times(N).minus(V.times(C).times(m.minus(1)).div(m))
151
+ q: H,
152
+ F: I,
153
+ repayment: V,
154
+ fee: G,
155
+ c: ie,
156
+ d: oe,
157
+ residual: oe.times(T).minus(ie.times(N).times(s.minus(1)).div(s))
145
158
  };
146
- }, x = l(
147
- q(B.plus(r.times(N)).times(m.minus(1)).div(N).times(2).plus(1))
159
+ }, m = o(
160
+ F(
161
+ Z.plus(l.times(C ? N : T)).times(s.minus(1)).div(T).times(2).plus(1)
162
+ )
148
163
  );
149
- let v = l(0), o = x, s, f, _ = l(0);
150
- const g = async () => {
151
- if (v = l(0), o = x, s = r.gt(0) ? await d(v) : void 0, s && L(s.c, s.d)) return !0;
152
- a(
153
- !s || s.residual.lt(0),
164
+ let _ = o(0), d = m, e, c, w = o(0);
165
+ const A = async () => {
166
+ if (_ = o(0), d = m, e = l.gt(0) ? await g(_) : void 0, e && U(e.c, e.d)) return !0;
167
+ r(
168
+ !e || e.residual.lt(0),
154
169
  "ACTION_UNSUPPORTED",
155
170
  "This contribution requires deleveraging; use set_leverage separately"
156
- ), _ = s?.residual ?? c.times(N).minus(u.times(C).times(m.minus(1)).div(m)), f = await d(o);
157
- for (let y = 0; f.residual.lt(0) && y < 4 && !L(f.c, f.d); y++)
158
- o = o.times(2), f = await d(o);
159
- return L(f.c, f.d) ? (s = f, !0) : (a(f.residual.gte(0), "NO_CONVERGENCE", "Could not bracket leverage"), !1);
171
+ ), w = e?.residual ?? p.times(T).minus(a.times(N).times(s.minus(1)).div(s)), c = await g(d);
172
+ for (let I = 0; c.residual.lt(0) && I < 4 && !U(c.c, c.d); I++)
173
+ d = d.times(2), c = await g(d);
174
+ return U(c.c, c.d) ? (e = c, !0) : (r(c.residual.gte(0), "NO_CONVERGENCE", "Could not bracket leverage"), !1);
160
175
  };
161
- let O = await g(), I = 0, b = 0, T;
162
- for (let y = 0; !O && y < 24; y++) {
163
- const S = o.minus(v), D = l(
164
- P(
165
- v.plus(S.times(_.negated()).div(f.residual.minus(_)))
176
+ let O = await A(), x = 0, y = 0, R;
177
+ for (let I = 0; !O && I < 24; I++) {
178
+ const q = d.minus(_), H = o(
179
+ D(
180
+ _.plus(q.times(w.negated()).div(c.residual.minus(w)))
166
181
  )
167
- ), F = w.maximum(v.plus(1), w.minimum(o, D));
168
- if (s = await d(F), O = L(s.c, s.d), O) break;
169
- const V = s.residual.abs();
170
- b = T && V.gte(T.times("0.9")) ? b + 1 : 0, T = V, S.lte(1) || b >= 3 ? (a(
171
- I < 2,
182
+ ), V = h.maximum(_.plus(1), h.minimum(d, H));
183
+ if (e = await g(V), O = U(e.c, e.d), O) break;
184
+ const G = e.residual.abs();
185
+ y = R && G.gte(R.times("0.9")) ? y + 1 : 0, R = G, q.lte(1) || y >= 3 ? (r(
186
+ x < 2,
172
187
  "NO_CONVERGENCE",
173
188
  "Conversion quotes could not achieve the requested leverage within tolerance"
174
- ), I++, O = await g(), b = 0, T = void 0) : s.residual.lt(0) ? (v = F, _ = s.residual) : (o = F, f = s);
189
+ ), x++, O = await A(), y = 0, R = void 0) : e.residual.lt(0) ? (_ = V, w = e.residual) : (d = V, c = e);
175
190
  }
176
- a(
177
- O && s,
191
+ r(
192
+ O && e,
178
193
  "NO_CONVERGENCE",
179
194
  "Conversion quotes could not achieve the requested leverage within tolerance"
180
- ), e.conversions = [s.q], e.flashAmount = s.F.toFixed(0), e.flashRepayment = e.borrowAmount = s.repayment.toFixed(0), e.borrowFee = s.fee.toFixed(0), e.collateralAfter = s.c.toFixed(0), e.minCollateralAfter = u.plus(s.q.minOutput.amount).toFixed(0), e.debtAfter = s.d.toFixed(0);
181
- } else {
182
- e.direction = "decrease", a(u.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
183
- const r = i.type === "close", d = l(i.type === "remove_principal" ? i.amount : 0);
184
- a(
185
- d.times(N).lt(B) || r,
195
+ ), t.conversions = e.q ? [
196
+ {
197
+ ...e.q,
198
+ id: "increase",
199
+ purpose: e.F.gt(0) ? "leverage" : "input",
200
+ source: C || l.isZero() ? "flash" : e.F.gt(0) ? "wallet-and-flash" : "wallet"
201
+ }
202
+ ] : [], t.flashAmount = e.F.toFixed(0), t.flashRepayment = t.borrowAmount = e.repayment.toFixed(0), t.borrowFee = e.fee.toFixed(0), t.collateralAfter = e.c.toFixed(0), t.minCollateralAfter = a.plus(C ? l : 0).plus(e.q?.minOutput.amount ?? 0).toFixed(0), t.debtAfter = e.d.toFixed(0);
203
+ } else if (k(i.principalCoinType, i.collateralCoinType)) {
204
+ t.direction = "decrease", r(a.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
205
+ const l = n.type === "close", f = o(n.type === "remove_principal" ? n.amount : 0);
206
+ r(
207
+ l || f.times(N).lt(Z),
186
208
  "CONSTRAINT_VIOLATION",
187
209
  "Withdrawal consumes all equity; use close"
188
210
  );
189
- const x = c.isZero() ? c : l(q(c.times("1.0001").plus(se(n.debt)))), v = async (g) => {
190
- const O = await z(g.toFixed(0), !1), I = l(O.minOutput.amount).minus(d), b = r || m.eq(1) ? x : w.minimum(c, l(P(I.div(l(n.flash.feeBps).div(1e4).plus(1))))), T = w.maximum(0, c.minus(b)), y = u.minus(g);
211
+ const C = p.isZero() ? p : o(F(p.times("1.0001").plus(le(u.debt)))), g = async (A) => {
212
+ const O = A.gt(0) ? await z(A.toFixed(0), !1) : void 0, x = o(O?.minOutput.amount ?? 0), y = l || s.eq(1) ? C : h.minimum(p, o(D(x.div(o(u.flash.feeBps).div(1e4).plus(1))))), R = l ? a : A.plus(f), I = a.minus(R), q = h.maximum(0, p.minus(y));
191
213
  return {
192
214
  q: O,
193
- W: g,
194
- R: b,
195
- repayment: $(b),
215
+ W: A,
216
+ R: y,
217
+ total: R,
218
+ c: I,
219
+ d: q,
220
+ repayment: W(y),
221
+ available: x,
222
+ residual: q.times(T).minus(I.times(N).times(s.minus(1)).div(s))
223
+ };
224
+ }, m = l || s.eq(1), _ = a.minus(f);
225
+ let d = p.isZero() ? o(0) : l || s.eq(1) ? o(F(W(C).times(T).div(N).times("1.01"))) : o(
226
+ F(
227
+ p.times(T).minus(a.minus(f).times(N).times(s.minus(1)).div(s)).times(s).div(N)
228
+ )
229
+ );
230
+ m && (d = h.minimum(d, _));
231
+ let e;
232
+ for (let A = 0; A < 20; A++) {
233
+ r(
234
+ d.gte(0) && d.plus(l ? 0 : f).lte(a),
235
+ "CONSTRAINT_VIOLATION",
236
+ "Insufficient collateral to repay debt and withdraw principal"
237
+ ), e = await g(d);
238
+ const O = e.repayment.minus(e.available);
239
+ if (r(
240
+ !m || d.lt(_) || O.lte(0),
241
+ "CONSTRAINT_VIOLATION",
242
+ "Insufficient collateral to repay debt and withdraw principal"
243
+ ), (l || s.eq(1)) && O.lt(0) && d.gt(0) && A < 2) {
244
+ const R = o(F(d.times(e.repayment).div(e.available)));
245
+ if (R.gt(0) && R.lt(d)) {
246
+ d = R;
247
+ continue;
248
+ }
249
+ }
250
+ if (O.lte(0) && (l || U(e.c, e.d))) break;
251
+ const x = l || s.eq(1) ? O.times(T).div(N) : e.residual.times(s).div(N);
252
+ let y = h.maximum(1, o(F(d.plus(x.times("1.01")).plus(O.gt(0) ? 1 : 0))));
253
+ m && (y = h.minimum(y, _)), r(A < 19 && !y.eq(d), "NO_CONVERGENCE", "No feasible collateral-principal decrease"), d = y;
254
+ }
255
+ r(
256
+ e && e.repayment.lte(e.available),
257
+ "NO_CONVERGENCE",
258
+ "Missing collateral-principal decrease plan"
259
+ ), t.conversions = e.q ? [{ ...e.q, id: "repayment", purpose: "repayment", source: "withdrawal" }] : [], t.flashAmount = e.R.toFixed(0), t.flashRepayment = e.repayment.toFixed(0), t.withdrawAmount = e.total.toFixed(0), t.collateralAfter = t.minCollateralAfter = e.c.toFixed(0), t.debtAfter = e.d.toFixed(0);
260
+ const c = e.total.minus(e.W);
261
+ c.gt(0) && (P.push({ coinType: i.principalCoinType, amount: c.toFixed(0) }), Q.push({ coinType: i.principalCoinType, amount: c.toFixed(0) }));
262
+ const w = o(e.q?.expectedOutput.amount ?? 0).minus(e.repayment).plus(h.maximum(0, e.R.minus(p)));
263
+ w.gt(0) && P.push({ coinType: i.debtCoinType, amount: D(w) });
264
+ } else {
265
+ t.direction = "decrease", r(a.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
266
+ const l = n.type === "close", f = o(n.type === "remove_principal" ? n.amount : 0);
267
+ r(
268
+ f.times(T).lt(Z) || l,
269
+ "CONSTRAINT_VIOLATION",
270
+ "Withdrawal consumes all equity; use close"
271
+ );
272
+ const C = p.isZero() ? p : o(F(p.times("1.0001").plus(le(u.debt)))), g = async (c) => {
273
+ const w = await z(c.toFixed(0), !1), A = o(w.minOutput.amount).minus(f), O = l || s.eq(1) ? C : h.minimum(p, o(D(A.div(o(u.flash.feeBps).div(1e4).plus(1))))), x = h.maximum(0, p.minus(O)), y = a.minus(c);
274
+ return {
275
+ q: w,
276
+ W: c,
277
+ R: O,
278
+ repayment: W(O),
196
279
  c: y,
197
- d: T,
198
- residual: T.times(N).minus(y.times(C).times(m.minus(1)).div(m)),
199
- available: I
280
+ d: x,
281
+ residual: x.times(T).minus(y.times(N).times(s.minus(1)).div(s)),
282
+ available: A
200
283
  };
201
284
  };
202
- let o;
203
- if (r) o = await v(u);
285
+ let m;
286
+ if (l) m = await g(a);
204
287
  else {
205
- let g = l(
206
- q(
207
- c.times(N).minus(u.times(C).times(m.minus(1)).div(m)).plus(d.times(N)).times(m).div(C)
288
+ let c = o(
289
+ F(
290
+ p.times(T).minus(a.times(N).times(s.minus(1)).div(s)).plus(f.times(T)).times(s).div(N)
208
291
  )
209
292
  );
210
- m.eq(1) && (g = l(q(x.plus(d).times(N).div(C).times("1.01")))), g = w.maximum(1, w.minimum(u, g));
211
- for (let O = 0; O < 20; O++) {
212
- o = await v(g);
213
- const I = o.repayment.plus(d).minus(o.q.minOutput.amount);
214
- if (o.R.gte(0) && I.lte(0) && L(o.c, o.d)) break;
215
- const b = m.eq(1) ? I.times(N).div(C) : o.residual.times(m).div(C), T = w.maximum(
293
+ s.eq(1) && (c = o(F(C.plus(f).times(T).div(N).times("1.01")))), c = h.maximum(1, h.minimum(a, c));
294
+ for (let w = 0; w < 20; w++) {
295
+ m = await g(c);
296
+ const A = m.repayment.plus(f).minus(m.q.minOutput.amount);
297
+ if (m.R.gte(0) && A.lte(0) && U(m.c, m.d)) break;
298
+ const O = s.eq(1) ? A.times(T).div(N) : m.residual.times(s).div(N), x = h.maximum(
216
299
  1,
217
- l(q(g.plus(b.times("1.01")).plus(I.gt(0) ? 1 : 0)))
300
+ o(F(c.plus(O.times("1.01")).plus(A.gt(0) ? 1 : 0)))
218
301
  );
219
- a(
220
- T.lt(u) && !T.eq(g) && O < 19,
302
+ r(
303
+ x.lt(a) && !x.eq(c) && w < 19,
221
304
  "NO_CONVERGENCE",
222
305
  "No feasible deleverage route within constraints"
223
- ), g = T;
306
+ ), c = x;
224
307
  }
225
308
  }
226
- a(o && o.R.gte(0), "NO_CONVERGENCE", "Missing decrease plan");
227
- const s = w.maximum(0, o.R.minus(c)), f = l(o.q.expectedOutput.amount).plus(s).minus(o.repayment), _ = l(o.q.minOutput.amount).minus(o.repayment);
228
- a(
229
- _.gte(d) && _.gte(0),
309
+ r(m && m.R.gte(0), "NO_CONVERGENCE", "Missing decrease plan");
310
+ const _ = h.maximum(0, m.R.minus(p)), d = o(m.q.expectedOutput.amount).plus(_).minus(m.repayment), e = o(m.q.minOutput.amount).minus(m.repayment);
311
+ r(
312
+ e.gte(f) && e.gte(0),
230
313
  "CONSTRAINT_VIOLATION",
231
314
  "Conversion cannot cover flash repayment and withdrawal"
232
- ), e.conversions = [o.q], e.flashAmount = o.R.toFixed(0), e.flashRepayment = o.repayment.toFixed(0), e.withdrawAmount = o.W.toFixed(0), e.collateralAfter = e.minCollateralAfter = o.c.toFixed(0), e.debtAfter = o.d.toFixed(0), f.gt(0) && Z.push({ coinType: t.principalCoinType, amount: P(f) }), _.gt(0) && Q.push({ coinType: t.principalCoinType, amount: P(_) });
315
+ ), t.conversions = [
316
+ { ...m.q, id: "withdrawal", purpose: "repayment", source: "withdrawal" }
317
+ ], t.flashAmount = m.R.toFixed(0), t.flashRepayment = m.repayment.toFixed(0), t.withdrawAmount = m.W.toFixed(0), t.collateralAfter = t.minCollateralAfter = m.c.toFixed(0), t.debtAfter = m.d.toFixed(0), d.gt(0) && P.push({ coinType: i.principalCoinType, amount: D(d) }), e.gt(0) && Q.push({ coinType: i.principalCoinType, amount: D(e) });
233
318
  }
234
- for (const r of [
235
- e.flashAmount,
236
- e.flashRepayment,
237
- e.borrowAmount,
238
- e.borrowFee,
239
- e.withdrawAmount,
240
- e.collateralAfter,
241
- e.debtAfter
319
+ M.length && (t.funding = {
320
+ kind: k(M[0].coinType, i.collateralCoinType) ? "collateral" : "debt",
321
+ input: M[0]
322
+ });
323
+ for (const l of [
324
+ t.flashAmount,
325
+ t.flashRepayment,
326
+ t.borrowAmount,
327
+ t.borrowFee,
328
+ t.withdrawAmount,
329
+ t.collateralAfter,
330
+ t.debtAfter
242
331
  ])
243
- G(r);
244
- const H = l(e.flashAmount);
245
- a(
246
- H.isZero() || H.gte(n.flash.min) && H.lte(n.flash.max),
332
+ X(l);
333
+ const J = o(t.flashAmount);
334
+ r(
335
+ J.isZero() || J.gte(u.flash.min) && J.lte(u.flash.max),
247
336
  "CAPACITY_EXCEEDED",
248
337
  "Flash liquidity limit exceeded"
249
- ), a(
250
- l(e.borrowAmount).plus(e.borrowFee).lte(ae(n)),
338
+ ), r(
339
+ o(t.borrowAmount).plus(t.borrowFee).lte(pe(u)),
251
340
  "CAPACITY_EXCEEDED",
252
341
  "Borrow liquidity limit exceeded"
253
- ), a(
254
- l(e.collateralAfter).minus(u).lte(re(n)),
342
+ ), r(
343
+ o(t.collateralAfter).minus(a).lte(ce(u)),
255
344
  "CAPACITY_EXCEEDED",
256
345
  "Supply capacity exceeded"
257
346
  );
258
- const W = { collateralAmount: e.collateralAfter, debtAmount: e.debtAfter }, U = Y(
259
- { ...W, collateralAmount: e.minCollateralAfter },
260
- n
347
+ const K = { collateralAmount: t.collateralAfter, debtAmount: t.debtAfter }, j = ee(
348
+ { ...K, collateralAmount: t.minCollateralAfter },
349
+ u
261
350
  );
262
- a(
263
- U.healthFactor === null || l(U.healthFactor).gte(h.minHealthFactor),
351
+ r(
352
+ j.healthFactor === null || o(j.healthFactor).gte(E.minHealthFactor),
264
353
  "CONSTRAINT_VIOLATION",
265
354
  "Minimum output does not meet health factor constraint"
266
- ), a(
267
- ue(
268
- { ...W, collateralAmount: e.minCollateralAfter },
269
- A,
270
- n,
271
- e.direction !== "increase"
355
+ ), r(
356
+ de(
357
+ { ...K, collateralAmount: t.minCollateralAfter },
358
+ b,
359
+ u,
360
+ t.direction !== "increase"
272
361
  ),
273
362
  "CONSTRAINT_VIOLATION",
274
363
  "Projected debt exceeds collateral LTV"
275
- ), h.maxLeverage && U.leverage && a(
276
- l(U.leverage).lte(h.maxLeverage),
364
+ ), E.maxLeverage && j.leverage && r(
365
+ o(j.leverage).lte(E.maxLeverage),
277
366
  "CONSTRAINT_VIOLATION",
278
367
  "Maximum leverage exceeded"
279
368
  );
280
- const X = Y(W, n);
281
- return ["open", "add_principal", "remove_principal", "set_leverage"].includes(i.type) && a(
282
- X.leverage !== null && l(X.leverage).minus(m).abs().lte(m.times("0.0001")),
369
+ const $ = ee(K, u);
370
+ return ["open", "add_principal", "remove_principal", "set_leverage"].includes(n.type) && r(
371
+ $.leverage !== null && o($.leverage).minus(s).abs().lte(s.times("0.0001")),
283
372
  "NO_CONVERGENCE",
284
373
  "Conversion quote cannot achieve the requested leverage within tolerance"
285
374
  ), {
286
- execution: e,
287
- estimate: { inputs: j, outputs: Z, minOutputs: Q, ...X }
375
+ execution: t,
376
+ estimate: { inputs: M, outputs: P, minOutputs: Q, ...$ }
288
377
  };
289
378
  }
290
379
  export {
291
- ve as chooseConversion,
292
- Y as metrics,
293
- fe as plan,
294
- ce as validateAction
380
+ Ae as chooseConversion,
381
+ ee as metrics,
382
+ Te as plan,
383
+ Ne as validateAction
295
384
  };
296
385
  //# sourceMappingURL=planner.js.map