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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/planner.js CHANGED
@@ -1,18 +1,19 @@
1
- import { quoteStakingSnapshot as Ce } from "./native-staking.js";
2
- import { validateMarketMode as Re, assertModeExposure as xe } from "./emode.js";
3
- import { check as u, uint as B, decimal as G, BN as I, sameCoin as X, MultiplyError as q, floor as M, ceil as F } from "./utils.js";
4
- import { validateConversion as pe } from "./converters.js";
5
- import { atomPrices as Ee, leverageLimit as _e, isDustClose as be, amountCushion as ge, borrowCapacity as Se, withinSameReserveCapacity as Le, supplyCapacity as Ve, withinLtv as Fe } from "./amounts.js";
6
- const t = (i) => new I(i), ue = "Target leverage needs new debt after this withdrawal; use set_leverage separately";
7
- function me(i, n) {
8
- const R = Ee(n), w = t(i.collateralAmount).times(R.collateral), r = t(i.debtAmount).times(R.debt), U = w.minus(r);
1
+ import { quoteRedemptionSnapshot as Le } from "./native-redemption.js";
2
+ import { quoteStakingSnapshot as ge } from "./native-staking.js";
3
+ import { validateMarketMode as Ve, assertModeExposure as qe } from "./emode.js";
4
+ import { BN as R, check as p, uint as M, decimal as Y, sameCoin as H, MultiplyError as b, floor as X, ceil as S } from "./utils.js";
5
+ import { validateConversion as ae } from "./converters.js";
6
+ import { atomPrices as we, leverageLimit as ye, isDustClose as Fe, amountCushion as Re, borrowCapacity as Ue, withinSameReserveCapacity as De, supplyCapacity as Pe, withinLtv as Me } from "./amounts.js";
7
+ const e = (o) => new R(o), ce = "Target leverage needs new debt after this withdrawal; use set_leverage separately";
8
+ function de(o, s) {
9
+ const w = we(s), x = e(o.collateralAmount).times(w.collateral), r = e(o.debtAmount).times(w.debt), U = x.minus(r);
9
10
  return {
10
- healthFactor: r.isZero() ? null : w.times(n.liquidationThreshold).div(r.times(n.borrowWeight)).toFixed(12),
11
- leverage: w.isZero() && r.isZero() || U.lte(0) ? null : w.div(U).toFixed(12)
11
+ healthFactor: r.isZero() ? null : x.times(s.liquidationThreshold).div(r.times(s.borrowWeight)).toFixed(12),
12
+ leverage: x.isZero() && r.isZero() || U.lte(0) ? null : x.div(U).toFixed(12)
12
13
  };
13
14
  }
14
- function Be(i, n) {
15
- u(
15
+ function Ye(o, s) {
16
+ p(
16
17
  [
17
18
  "open",
18
19
  "add_principal",
@@ -21,91 +22,91 @@ function Be(i, n) {
21
22
  "repay",
22
23
  "add_collateral",
23
24
  "close"
24
- ].includes(i?.type),
25
+ ].includes(o?.type),
25
26
  "INVALID_ARGUMENT",
26
27
  "Unknown Multiply action"
27
- ), ["open", "add_principal", "remove_principal", "repay", "add_collateral"].includes(i.type) && (u("amount" in i, "INVALID_ARGUMENT", "This action requires an amount"), B(i.amount, !1)), (i.type === "open" || i.type === "set_leverage") && G(i.targetLeverage, "1"), "targetLeverage" in i && i.targetLeverage !== void 0 && G(i.targetLeverage, "1"), u(
28
- Number.isInteger(n?.maxSlippageBps) && n.maxSlippageBps >= 0 && n.maxSlippageBps < 1e4,
28
+ ), ["open", "add_principal", "remove_principal", "repay", "add_collateral"].includes(o.type) && (p("amount" in o, "INVALID_ARGUMENT", "This action requires an amount"), M(o.amount, !1)), (o.type === "open" || o.type === "set_leverage") && Y(o.targetLeverage, "1"), "targetLeverage" in o && o.targetLeverage !== void 0 && Y(o.targetLeverage, "1"), p(
29
+ Number.isInteger(s?.maxSlippageBps) && s.maxSlippageBps >= 0 && s.maxSlippageBps < 1e4,
29
30
  "INVALID_ARGUMENT",
30
31
  "Slippage must be integer bps in [0, 10000)"
31
- ), G(n.minHealthFactor, "1"), n.maxLeverage !== void 0 && G(n.maxLeverage, "1");
32
+ ), Y(s.minHealthFactor, "1"), s.maxLeverage !== void 0 && Y(s.maxLeverage, "1");
32
33
  }
33
- async function Ge(i, n, R) {
34
- const w = n.filter((C) => C.supports(i.coinIn, i.coinOut)), r = await Promise.allSettled(w.map((C) => C.quote(i))), U = [];
35
- for (let C = 0; C < r.length; C++) {
36
- const x = r[C];
37
- if (x.status === "fulfilled")
38
- pe(x.value, i, w[C].id), U.push(x.value);
39
- else if (!(x.reason instanceof q) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
40
- x.reason.code
34
+ async function je(o, s, w) {
35
+ const x = s.filter((g) => g.supports(o.coinIn, o.coinOut)), r = await Promise.allSettled(x.map((g) => g.quote(o))), U = [];
36
+ for (let g = 0; g < r.length; g++) {
37
+ const q = r[g];
38
+ if (q.status === "fulfilled")
39
+ ae(q.value, o, x[g].id), U.push(q.value);
40
+ else if (!(q.reason instanceof b) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
41
+ q.reason.code
41
42
  ))
42
- throw x.reason;
43
+ throw q.reason;
43
44
  }
44
45
  if (U.length)
45
- return U.sort((C, x) => t(x.minOutput.amount).comparedTo(C.minOutput.amount) || C.converterId.localeCompare(x.converterId))[0];
46
- u(
47
- R.supports(i.coinIn, i.coinOut),
46
+ return U.sort((g, q) => e(q.minOutput.amount).comparedTo(g.minOutput.amount) || g.converterId.localeCompare(q.converterId))[0];
47
+ p(
48
+ w.supports(o.coinIn, o.coinOut),
48
49
  "NO_CONVERSION_ROUTE",
49
50
  "No converter supports this pair"
50
51
  );
51
52
  try {
52
- const C = await R.quote(i);
53
- return pe(C, i, R.id), C;
54
- } catch (C) {
55
- if (!(C instanceof q) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
56
- C.code
53
+ const g = await w.quote(o);
54
+ return ae(g, o, w.id), g;
55
+ } catch (g) {
56
+ if (!(g instanceof b) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
57
+ g.code
57
58
  ))
58
- throw C;
59
- const x = C.code === "CONVERSION_AMOUNT_TOO_SMALL" && r.every(
60
- (Z) => Z.status === "rejected" && Z.reason instanceof q && Z.reason.code === "CONVERSION_AMOUNT_TOO_SMALL"
59
+ throw g;
60
+ const q = g.code === "CONVERSION_AMOUNT_TOO_SMALL" && r.every(
61
+ (j) => j.status === "rejected" && j.reason instanceof b && j.reason.code === "CONVERSION_AMOUNT_TOO_SMALL"
61
62
  );
62
- throw new q(
63
- x ? "CONVERSION_AMOUNT_TOO_SMALL" : "NO_CONVERSION_ROUTE",
63
+ throw new b(
64
+ q ? "CONVERSION_AMOUNT_TOO_SMALL" : "NO_CONVERSION_ROUTE",
64
65
  "No eligible executable conversion route"
65
66
  );
66
67
  }
67
68
  }
68
- async function Ze(i, n, R, w, r, U, C, x, Z) {
69
- Re(i, r);
70
- const c = t(w.collateralAmount), d = t(w.debtAmount), { collateral: O, debt: f } = Ee(r);
71
- u(
72
- O.gt(0) && f.gt(0) && G(r.ltv).lte(1) && G(r.liquidationThreshold).lte(1) && G(r.borrowWeight).gte(1),
69
+ async function Qe(o, s, w, x, r, U, g, q, j, Oe, xe, fe, Ne = !0) {
70
+ Ve(o, r);
71
+ const O = e(x.collateralAmount), v = e(x.debtAmount), { collateral: N, debt: A } = we(r);
72
+ p(
73
+ N.gt(0) && A.gt(0) && Y(r.ltv).lte(1) && Y(r.liquidationThreshold).lte(1) && Y(r.borrowWeight).gte(1),
73
74
  "READ_FAILED",
74
75
  "Invalid market risk or price data"
75
76
  );
76
- const Y = c.times(O).minus(d.times(f));
77
- u(
78
- c.isZero() && d.isZero() || Y.gt(0) || (n.type === "repay" || n.type === "add_collateral") && d.gt(0),
77
+ const J = O.times(N).minus(v.times(A));
78
+ p(
79
+ O.isZero() && v.isZero() || J.gt(0) || (s.type === "repay" || s.type === "add_collateral") && v.gt(0),
79
80
  "POSITION_UNSUPPORTED",
80
81
  "Position has non-positive equity"
81
82
  );
82
- const j = me(w, r), $ = "targetLeverage" in n ? n.targetLeverage : void 0, s = $ === void 0 && j.leverage !== null ? c.times(O).div(Y) : G($ ?? "1", "1");
83
- n.type === "set_leverage" && u(
84
- s.minus(j.leverage ?? "1").abs().gt("0.000001"),
83
+ const K = de(x, r), ie = "targetLeverage" in s ? s.targetLeverage : void 0, n = ie === void 0 && K.leverage !== null ? O.times(N).div(J) : Y(ie ?? "1", "1");
84
+ s.type === "set_leverage" && p(
85
+ n.minus(K.leverage ?? "1").abs().gt("0.000001"),
85
86
  "NO_OP",
86
87
  "Position already has the requested leverage"
87
- ), B(U), B(r.flash.feeBps), u(
88
+ ), M(U), M(r.flash.feeBps), p(
88
89
  Number.isSafeInteger(r.observedAt) && Date.now() - r.observedAt <= 12e4 && r.observedAt <= Date.now() + 5e3,
89
90
  "STALE_QUOTE",
90
91
  "Market snapshot is stale"
91
92
  );
92
- const oe = n.type === "open" || n.type === "add_principal" || n.type === "set_leverage" && s.gt(j.leverage ?? "1");
93
- R.maxLeverage && oe && $ !== void 0 && u(s.lte(R.maxLeverage), "CONSTRAINT_VIOLATION", "Target exceeds maxLeverage");
94
- const ce = _e(
95
- R.maxLeverage,
96
- n,
93
+ const oe = s.type === "open" || s.type === "add_principal" || s.type === "set_leverage" && n.gt(K.leverage ?? "1"), Ae = s.type === "open" || s.type === "set_leverage" && oe ? "0.001" : "0.0001";
94
+ w.maxLeverage && oe && ie !== void 0 && p(n.lte(w.maxLeverage), "CONSTRAINT_VIOLATION", "Target exceeds maxLeverage");
95
+ const Te = ye(
96
+ w.maxLeverage,
97
+ s,
97
98
  oe ? "increase" : "decrease",
98
- j.leverage
99
+ K.leverage
99
100
  );
100
- ce && u(
101
- s.lte(ce),
101
+ Te && p(
102
+ n.lte(Te),
102
103
  "CONSTRAINT_VIOLATION",
103
- $ === void 0 ? "Current leverage exceeds maxLeverage" : "Target exceeds maxLeverage"
104
+ ie === void 0 ? "Current leverage exceeds maxLeverage" : "Target exceeds maxLeverage"
104
105
  );
105
- const Q = [], z = [], ne = [], p = {
106
+ const $ = [], k = [], re = [], C = {
106
107
  version: 4,
107
108
  funding: { kind: "none" },
108
- snapshot: w,
109
+ snapshot: x,
109
110
  market: r,
110
111
  conversions: [],
111
112
  direction: "increase",
@@ -114,408 +115,503 @@ async function Ze(i, n, R, w, r, U, C, x, Z) {
114
115
  borrowAmount: "0",
115
116
  borrowFee: "0",
116
117
  withdrawAmount: "0",
117
- collateralAfter: c.toFixed(0),
118
- debtAfter: d.toFixed(0),
119
- minCollateralAfter: c.toFixed(0)
120
- }, k = (e) => t(F(e.times(t(r.flash.feeBps).div(1e4).plus(1)))), he = (e) => t(M(e.times(U).div(1e4))), se = n.type === "add_principal" ? t(n.amount).times(
121
- X(n.inputCoinType || i.principalCoinType, i.collateralCoinType) ? O : f
122
- ) : void 0, H = (e, m) => {
123
- const N = e.times(O), h = N.minus(m.times(f));
124
- return h.gt(0) ? se && se.gt(0) ? m.times(f).minus(N.times(s.minus(1)).div(s)).abs().lte(I.maximum(se.times("0.0001"), f)) : N.div(h).minus(s).abs().lte(s.times("0.0001")) : !1;
125
- }, ye = Date.now() + 45e3;
126
- let Ie = 0;
127
- const le = async (e) => {
128
- const m = ye - Date.now();
129
- u(
130
- ++Ie <= 32 && m > 0,
118
+ collateralAfter: O.toFixed(0),
119
+ debtAfter: v.toFixed(0),
120
+ minCollateralAfter: O.toFixed(0)
121
+ }, Q = (i) => e(S(i.times(e(r.flash.feeBps).div(1e4).plus(1)))), Se = (i) => e(X(i.times(U).div(1e4))), ue = s.type === "add_principal" ? e(s.amount).times(
122
+ H(s.inputCoinType || o.principalCoinType, o.collateralCoinType) ? N : A
123
+ ) : void 0, B = (i, u) => {
124
+ const _ = i.times(N), y = _.minus(u.times(A));
125
+ return y.gt(0) ? ue && ue.gt(0) ? u.times(A).minus(_.times(n.minus(1)).div(n)).abs().lte(R.maximum(ue.times("0.0001"), A)) : _.div(y).minus(n).abs().lte(n.times(Ae)) : !1;
126
+ }, ve = xe ?? { deadline: Date.now() + 45e3, count: 0 }, ee = async (i) => {
127
+ const u = ve.deadline - Date.now();
128
+ p(
129
+ ++ve.count <= 32 && u > 0,
131
130
  "NO_CONVERGENCE",
132
131
  "Conversion quote budget exhausted"
133
132
  );
134
- let N;
133
+ let _;
135
134
  try {
136
135
  return await Promise.race([
137
- e(),
138
- new Promise((h, a) => {
139
- N = setTimeout(
140
- () => a(new q("NO_CONVERGENCE", "Conversion quote time budget exhausted")),
141
- m
136
+ i(),
137
+ new Promise((y, a) => {
138
+ _ = setTimeout(
139
+ () => a(new b("NO_CONVERGENCE", "Conversion quote time budget exhausted")),
140
+ u
142
141
  );
143
142
  })
144
143
  ]);
145
144
  } finally {
146
- clearTimeout(N);
145
+ clearTimeout(_);
147
146
  }
148
- }, ae = (e, m) => le(
149
- () => C({
150
- amountIn: e,
151
- coinIn: m ? i.debtCoinType : i.collateralCoinType,
152
- coinOut: m ? i.collateralCoinType : i.debtCoinType,
153
- slippageBps: R.maxSlippageBps
147
+ }, me = (i, u) => ee(
148
+ () => g({
149
+ amountIn: i,
150
+ coinIn: u ? o.debtCoinType : o.collateralCoinType,
151
+ coinOut: u ? o.collateralCoinType : o.debtCoinType,
152
+ slippageBps: w.maxSlippageBps
154
153
  })
155
- ), de = (e, m) => Q.push({ coinType: e, amount: m });
156
- if (n.type === "close" && be(i, w, r))
157
- p.direction = "decrease";
158
- else if (n.type === "repay" || n.type === "add_collateral")
159
- if (p.direction = n.type, de(
160
- n.type === "repay" ? i.debtCoinType : i.collateralCoinType,
161
- n.amount
162
- ), n.type === "repay") {
163
- p.debtAfter = I.maximum(0, d.minus(n.amount)).toFixed(0);
164
- const e = I.maximum(0, t(n.amount).minus(d)).toFixed(0);
165
- e !== "0" && z.push({ coinType: i.debtCoinType, amount: e });
166
- } else p.collateralAfter = p.minCollateralAfter = c.plus(n.amount).toFixed(0);
154
+ ), Ce = (i, u) => $.push({ coinType: i, amount: u });
155
+ if (s.type === "close" && Fe(o, x, r))
156
+ C.direction = "decrease";
157
+ else if (s.type === "repay" || s.type === "add_collateral")
158
+ if (C.direction = s.type, Ce(
159
+ s.type === "repay" ? o.debtCoinType : o.collateralCoinType,
160
+ s.amount
161
+ ), s.type === "repay") {
162
+ C.debtAfter = R.maximum(0, v.minus(s.amount)).toFixed(0);
163
+ const i = R.maximum(0, e(s.amount).minus(v)).toFixed(0);
164
+ i !== "0" && k.push({ coinType: o.debtCoinType, amount: i });
165
+ } else C.collateralAfter = C.minCollateralAfter = O.plus(s.amount).toFixed(0);
167
166
  else if (oe) {
168
- const e = t("amount" in n ? n.amount : "0"), m = "inputCoinType" in n && n.inputCoinType ? n.inputCoinType : i.principalCoinType, N = X(m, i.collateralCoinType);
169
- e.gt(0) && de(m, e.toFixed(0));
170
- const h = async (o, L) => {
171
- const K = o.plus(N ? 0 : e), W = {
172
- amountIn: K.toFixed(0),
173
- coinIn: i.debtCoinType,
174
- coinOut: i.collateralCoinType,
175
- slippageBps: R.maxSlippageBps
176
- }, P = K.gt(0) ? L ? Ce(L, W) : await ae(K.toFixed(0), !0) : void 0;
177
- P && pe(P, W, L?.converterId ?? P.converterId);
178
- const re = k(o), ve = he(re), Te = c.plus(N ? e : 0).plus(P?.expectedOutput.amount ?? 0), Ae = d.plus(re).plus(ve);
167
+ const i = e("amount" in s ? s.amount : "0"), u = "inputCoinType" in s && s.inputCoinType ? s.inputCoinType : o.principalCoinType, _ = H(u, o.collateralCoinType);
168
+ i.gt(0) && Ce(u, i.toFixed(0));
169
+ const y = async (l, F) => {
170
+ const te = l.plus(_ ? 0 : i), z = {
171
+ amountIn: te.toFixed(0),
172
+ coinIn: o.debtCoinType,
173
+ coinOut: o.collateralCoinType,
174
+ slippageBps: w.maxSlippageBps
175
+ }, W = te.gt(0) ? F ? ge(F, z) : await me(te.toFixed(0), !0) : void 0;
176
+ W && ae(W, z, F?.converterId ?? W.converterId);
177
+ const pe = Q(l), _e = Se(pe), he = O.plus(_ ? i : 0).plus(W?.expectedOutput.amount ?? 0), Ie = v.plus(pe).plus(_e);
179
178
  return {
180
- q: P,
181
- F: o,
182
- repayment: re,
183
- fee: ve,
184
- c: Te,
185
- d: Ae,
186
- residual: Ae.times(f).minus(Te.times(O).times(s.minus(1)).div(s))
179
+ q: W,
180
+ F: l,
181
+ repayment: pe,
182
+ fee: _e,
183
+ c: he,
184
+ d: Ie,
185
+ residual: Ie.times(A).minus(he.times(N).times(n.minus(1)).div(n))
187
186
  };
188
- }, a = (o) => ({
189
- ...p,
190
- conversions: o.q ? [
187
+ }, a = (l) => ({
188
+ ...C,
189
+ conversions: l.q ? [
191
190
  {
192
- ...o.q,
191
+ ...l.q,
193
192
  id: "increase",
194
- purpose: o.F.gt(0) ? "leverage" : "input",
195
- source: N || e.isZero() ? "flash" : o.F.gt(0) ? "wallet-and-flash" : "wallet"
193
+ purpose: l.F.gt(0) ? "leverage" : "input",
194
+ source: _ || i.isZero() ? "flash" : l.F.gt(0) ? "wallet-and-flash" : "wallet"
196
195
  }
197
196
  ] : [],
198
- flashAmount: o.F.toFixed(0),
199
- flashRepayment: o.repayment.toFixed(0),
200
- borrowAmount: o.repayment.toFixed(0),
201
- borrowFee: o.fee.toFixed(0),
202
- collateralAfter: o.c.toFixed(0),
203
- minCollateralAfter: c.plus(N ? e : 0).plus(o.q?.minOutput.amount ?? 0).toFixed(0),
204
- debtAfter: o.d.toFixed(0)
197
+ flashAmount: l.F.toFixed(0),
198
+ flashRepayment: l.repayment.toFixed(0),
199
+ borrowAmount: l.repayment.toFixed(0),
200
+ borrowFee: l.fee.toFixed(0),
201
+ collateralAfter: l.c.toFixed(0),
202
+ minCollateralAfter: O.plus(_ ? i : 0).plus(l.q?.minOutput.amount ?? 0).toFixed(0),
203
+ debtAfter: l.d.toFixed(0)
205
204
  });
206
- let b = f.div(O), v = !0, l;
207
- if (Z)
205
+ let L = A.div(N), T = Ne, c;
206
+ if (j)
208
207
  try {
209
- if (l = await le(Z), l) {
210
- Ce(l, {
211
- coinIn: i.debtCoinType,
212
- coinOut: i.collateralCoinType,
213
- amountIn: l.minInput,
208
+ if (c = await ee(j), c) {
209
+ ge(c, {
210
+ coinIn: o.debtCoinType,
211
+ coinOut: o.collateralCoinType,
212
+ amountIn: c.minInput,
214
213
  slippageBps: 0
215
214
  });
216
- const o = B(l.suiSupply), L = B(l.lstSupply);
217
- b = (o === 0n || L === 0n ? t(1) : t(L.toString()).div(o.toString())).times(
218
- t(1).minus(t(l.feeRate).div(l.feeDenominator))
215
+ const l = M(c.suiSupply), F = M(c.lstSupply);
216
+ L = (l === 0n || F === 0n ? e(1) : e(F.toString()).div(l.toString())).times(
217
+ e(1).minus(e(c.feeRate).div(c.feeDenominator))
219
218
  );
220
219
  }
221
- } catch (o) {
222
- if (!(o instanceof q) || ![
220
+ } catch (l) {
221
+ if (!(l instanceof b) || ![
223
222
  "SNAPSHOT_UNAVAILABLE",
224
223
  "CONVERTER_UNAVAILABLE",
225
224
  "CONVERSION_AMOUNT_TOO_SMALL",
226
225
  "NO_CONVERSION_ROUTE"
227
- ].includes(o.code))
228
- throw o;
229
- v = !1, l = void 0;
226
+ ].includes(l.code))
227
+ throw l;
228
+ T = !1, c = void 0;
230
229
  }
231
- else if (x && s.gt(1))
230
+ else if (q && n.gt(1))
232
231
  try {
233
- const o = await le(x);
234
- o && (B(o.input.amount, !1), B(o.output.amount, !1), u(
235
- X(o.input.coinType, i.debtCoinType) && X(o.output.coinType, i.collateralCoinType) && Number.isSafeInteger(o.expiresAt) && o.expiresAt > Date.now(),
232
+ const l = await ee(q);
233
+ l && (M(l.input.amount, !1), M(l.output.amount, !1), p(
234
+ H(l.input.coinType, o.debtCoinType) && H(l.output.coinType, o.collateralCoinType) && Number.isSafeInteger(l.expiresAt) && l.expiresAt > Date.now(),
236
235
  "INVALID_CONVERSION",
237
236
  "Invalid staking rate hint"
238
- ), b = t(o.output.amount).div(o.input.amount));
239
- } catch (o) {
240
- if (!(o instanceof q) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
241
- o.code
237
+ ), L = e(l.output.amount).div(l.input.amount));
238
+ } catch (l) {
239
+ if (!(l instanceof b) || !["CONVERTER_UNAVAILABLE", "CONVERSION_AMOUNT_TOO_SMALL", "NO_CONVERSION_ROUTE"].includes(
240
+ l.code
242
241
  ))
243
- throw o;
244
- v = !1;
242
+ throw l;
243
+ T = !1;
245
244
  }
246
- const _ = t(1).plus(t(r.flash.feeBps).div(1e4)).times(t(1).plus(t(U).div(1e4))), D = f.times(_).times(s).minus(O.times(b).times(s.minus(1))), T = t(
247
- M(
248
- c.plus(e.times(N ? t(1) : b)).times(O).times(s.minus(1)).minus(d.times(f).times(s)).div(D)
245
+ const Z = e(1).plus(e(r.flash.feeBps).div(1e4)).times(e(1).plus(e(U).div(1e4))), D = A.times(Z).times(n).minus(N.times(L).times(n.minus(1))), t = e(
246
+ X(
247
+ O.plus(i.times(_ ? e(1) : L)).times(N).times(n.minus(1)).minus(v.times(A).times(n)).div(D)
249
248
  )
250
249
  );
251
- let g;
252
- if (v && D.gt(0) && T.isFinite() && T.gte(0) && T.lte("18446744073709551615"))
250
+ let h;
251
+ if (T && D.gt(0) && t.isFinite() && t.gte(0) && t.lte("18446744073709551615"))
253
252
  try {
254
- const o = await h(T, l);
255
- if (H(o.c, o.d))
253
+ const l = await y(t, c);
254
+ if (B(l.c, l.d))
256
255
  try {
257
- Oe(a(o)), g = o;
258
- } catch (L) {
259
- if (!(L instanceof q) || L.code !== "NO_CONVERGENCE") throw L;
256
+ ne(a(l)), h = l;
257
+ } catch (F) {
258
+ if (!(F instanceof b) || F.code !== "NO_CONVERGENCE") throw F;
260
259
  }
261
- } catch (o) {
262
- if (!(o instanceof q) || ![
260
+ } catch (l) {
261
+ if (!(l instanceof b) || ![
263
262
  "SNAPSHOT_UNAVAILABLE",
264
263
  "CONVERTER_UNAVAILABLE",
265
264
  "CONVERSION_AMOUNT_TOO_SMALL",
266
265
  "NO_CONVERSION_ROUTE",
267
266
  "CAPACITY_EXCEEDED",
268
267
  "CONSTRAINT_VIOLATION"
269
- ].includes(o.code))
270
- throw o;
268
+ ].includes(l.code))
269
+ throw l;
271
270
  }
272
- const V = t(
273
- F(
274
- Y.plus(e.times(N ? O : f)).times(s.minus(1)).div(f).times(2).plus(1)
271
+ const I = e(
272
+ S(
273
+ J.plus(i.times(_ ? N : A)).times(n.minus(1)).div(A).times(2).plus(1)
275
274
  )
276
275
  );
277
- let A = t(0), y = V, E = g, S, ee = t(0);
278
- const fe = async () => {
279
- if (A = t(0), y = V, E = e.gt(0) ? await h(A) : void 0, E && H(E.c, E.d)) return !0;
280
- u(
281
- !E || E.residual.lt(0),
276
+ let f = e(0), E = I, m = h, d, V = e(0);
277
+ const P = async () => {
278
+ if (f = e(0), E = I, m = i.gt(0) ? await y(f) : void 0, m && B(m.c, m.d)) return !0;
279
+ p(
280
+ !m || m.residual.lt(0),
282
281
  "ACTION_UNSUPPORTED",
283
282
  "This contribution requires deleveraging; use set_leverage separately"
284
- ), ee = E?.residual ?? d.times(f).minus(c.times(O).times(s.minus(1)).div(s)), S = await h(y);
285
- for (let o = 0; S.residual.lt(0) && o < 4 && !H(S.c, S.d); o++)
286
- y = y.times(2), S = await h(y);
287
- return H(S.c, S.d) ? (E = S, !0) : (u(S.residual.gte(0), "NO_CONVERGENCE", "Could not bracket leverage"), !1);
283
+ ), V = m?.residual ?? v.times(A).minus(O.times(N).times(n.minus(1)).div(n)), d = await y(E);
284
+ for (let l = 0; d.residual.lt(0) && l < 4 && !B(d.c, d.d); l++)
285
+ E = E.times(2), d = await y(E);
286
+ return B(d.c, d.d) ? (m = d, !0) : (p(d.residual.gte(0), "NO_CONVERGENCE", "Could not bracket leverage"), !1);
288
287
  };
289
- let J = g !== void 0 || await fe(), Ne = 0, te = 0, ie;
290
- for (let o = 0; !J && o < 24; o++) {
291
- const L = y.minus(A), K = t(
292
- M(
293
- A.plus(L.times(ee.negated()).div(S.residual.minus(ee)))
288
+ let G = h !== void 0 || await P(), Ee = 0, se = 0, le;
289
+ for (let l = 0; !G && l < 24; l++) {
290
+ const F = E.minus(f), te = e(
291
+ X(
292
+ f.plus(F.times(V.negated()).div(d.residual.minus(V)))
294
293
  )
295
- ), W = I.maximum(A.plus(1), I.minimum(y, K));
296
- if (E = await h(W), J = H(E.c, E.d), J) break;
297
- const P = E.residual.abs();
298
- te = ie && P.gte(ie.times("0.9")) ? te + 1 : 0, ie = P, L.lte(1) || te >= 3 ? (u(
299
- Ne < 2,
294
+ ), z = R.maximum(f.plus(1), R.minimum(E, te));
295
+ if (m = await y(z), G = B(m.c, m.d), G) break;
296
+ const W = m.residual.abs();
297
+ se = le && W.gte(le.times("0.9")) ? se + 1 : 0, le = W, F.lte(1) || se >= 3 ? (p(
298
+ Ee < 2,
300
299
  "NO_CONVERGENCE",
301
300
  "Conversion quotes could not achieve the requested leverage within tolerance"
302
- ), Ne++, J = await fe(), te = 0, ie = void 0) : E.residual.lt(0) ? (A = W, ee = E.residual) : (y = W, S = E);
301
+ ), Ee++, G = await P(), se = 0, le = void 0) : m.residual.lt(0) ? (f = z, V = m.residual) : (E = z, d = m);
303
302
  }
304
- u(
305
- J && E,
303
+ p(
304
+ G && m,
306
305
  "NO_CONVERGENCE",
307
306
  "Conversion quotes could not achieve the requested leverage within tolerance"
308
- ), Object.assign(p, a(E));
309
- } else if (X(i.principalCoinType, i.collateralCoinType)) {
310
- p.direction = "decrease", u(c.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
311
- const e = n.type === "close", m = t(n.type === "remove_principal" ? n.amount : 0);
312
- u(
313
- e || m.times(O).lt(Y),
307
+ ), Object.assign(C, a(m));
308
+ } else if (H(o.principalCoinType, o.collateralCoinType)) {
309
+ C.direction = "decrease", p(O.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
310
+ const i = s.type === "close", u = e(s.type === "remove_principal" ? s.amount : 0);
311
+ p(
312
+ i || u.times(N).lt(J),
314
313
  "CONSTRAINT_VIOLATION",
315
314
  "Withdrawal consumes all equity; use close"
316
315
  );
317
- const N = d.isZero() ? d : t(F(d.times("1.0001").plus(ge(r.debt)))), h = async (T) => {
318
- const g = T.gt(0) ? await ae(T.toFixed(0), !1) : void 0, V = t(g?.minOutput.amount ?? 0), A = e || s.eq(1) ? N : I.minimum(d, t(M(V.div(t(r.flash.feeBps).div(1e4).plus(1))))), y = e ? c : T.plus(m), E = c.minus(y), S = I.maximum(0, d.minus(A));
316
+ const _ = v.isZero() ? v : e(S(v.times("1.0001").plus(Re(r.debt)))), y = async (t) => {
317
+ const h = t.gt(0) ? await me(t.toFixed(0), !1) : void 0, I = e(h?.minOutput.amount ?? 0), f = i || n.eq(1) ? _ : R.minimum(v, e(X(I.div(e(r.flash.feeBps).div(1e4).plus(1))))), E = i ? O : t.plus(u), m = O.minus(E), d = R.maximum(0, v.minus(f));
319
318
  return {
320
- q: g,
321
- W: T,
322
- R: A,
323
- total: y,
324
- c: E,
325
- d: S,
326
- repayment: k(A),
327
- available: V,
328
- residual: S.times(f).minus(E.times(O).times(s.minus(1)).div(s))
319
+ q: h,
320
+ W: t,
321
+ R: f,
322
+ total: E,
323
+ c: m,
324
+ d,
325
+ repayment: Q(f),
326
+ available: I,
327
+ residual: d.times(A).minus(m.times(N).times(n.minus(1)).div(n))
329
328
  };
330
- }, a = e || s.eq(1), b = c.minus(m);
331
- let v = d.isZero() ? t(0) : e || s.eq(1) ? t(F(k(N).times(f).div(O).times("1.01"))) : t(
332
- F(
333
- d.times(f).minus(c.minus(m).times(O).times(s.minus(1)).div(s)).times(s).div(O)
329
+ }, a = i || n.eq(1), L = O.minus(u);
330
+ let T = v.isZero() ? e(0) : i || n.eq(1) ? e(S(Q(_).times(A).div(N).times("1.01"))) : e(
331
+ S(
332
+ v.times(A).minus(O.minus(u).times(N).times(n.minus(1)).div(n)).times(n).div(N)
334
333
  )
335
334
  );
336
- u(a || v.gte(0), "ACTION_UNSUPPORTED", ue), a && (v = I.minimum(v, b));
337
- let l;
338
- for (let T = 0; T < 20; T++) {
339
- u(
340
- v.gte(0) && v.plus(e ? 0 : m).lte(c),
335
+ p(a || T.gte(0), "ACTION_UNSUPPORTED", ce), a && (T = R.minimum(T, L));
336
+ let c;
337
+ for (let t = 0; t < 20; t++) {
338
+ p(
339
+ T.gte(0) && T.plus(i ? 0 : u).lte(O),
341
340
  "CONSTRAINT_VIOLATION",
342
341
  "Insufficient collateral to repay debt and withdraw principal"
343
- ), l = await h(v);
344
- const g = l.repayment.minus(l.available);
345
- if (u(
346
- !a || v.lt(b) || g.lte(0),
342
+ ), c = await y(T);
343
+ const h = c.repayment.minus(c.available);
344
+ if (p(
345
+ !a || T.lt(L) || h.lte(0),
347
346
  "CONSTRAINT_VIOLATION",
348
347
  "Insufficient collateral to repay debt and withdraw principal"
349
- ), (e || s.eq(1)) && g.lt(0) && v.gt(0) && T < 2) {
350
- const y = t(F(v.times(l.repayment).div(l.available)));
351
- if (y.gt(0) && y.lt(v)) {
352
- v = y;
348
+ ), (i || n.eq(1)) && h.lt(0) && T.gt(0) && t < 2) {
349
+ const E = e(S(T.times(c.repayment).div(c.available)));
350
+ if (E.gt(0) && E.lt(T)) {
351
+ T = E;
353
352
  continue;
354
353
  }
355
354
  }
356
- if (g.lte(0) && (e || H(l.c, l.d))) break;
357
- const V = e || s.eq(1) ? g.times(f).div(O) : l.residual.times(s).div(O);
358
- let A = I.maximum(1, t(F(v.plus(V.times("1.01")).plus(g.gt(0) ? 1 : 0))));
359
- a && (A = I.minimum(A, b)), u(T < 19 && !A.eq(v), "NO_CONVERGENCE", "No feasible collateral-principal decrease"), v = A;
355
+ if (h.lte(0) && (i || B(c.c, c.d))) break;
356
+ const I = i || n.eq(1) ? h.times(A).div(N) : c.residual.times(n).div(N);
357
+ let f = R.maximum(1, e(S(T.plus(I.times("1.01")).plus(h.gt(0) ? 1 : 0))));
358
+ a && (f = R.minimum(f, L)), p(t < 19 && !f.eq(T), "NO_CONVERGENCE", "No feasible collateral-principal decrease"), T = f;
360
359
  }
361
- u(
362
- l && l.repayment.lte(l.available),
360
+ p(
361
+ c && c.repayment.lte(c.available),
363
362
  "NO_CONVERGENCE",
364
363
  "Missing collateral-principal decrease plan"
365
- ), p.conversions = l.q ? [{ ...l.q, id: "repayment", purpose: "repayment", source: "withdrawal" }] : [], p.flashAmount = l.R.toFixed(0), p.flashRepayment = l.repayment.toFixed(0), p.withdrawAmount = l.total.toFixed(0), p.collateralAfter = p.minCollateralAfter = l.c.toFixed(0), p.debtAfter = l.d.toFixed(0);
366
- const _ = l.total.minus(l.W);
367
- _.gt(0) && (z.push({ coinType: i.principalCoinType, amount: _.toFixed(0) }), ne.push({ coinType: i.principalCoinType, amount: _.toFixed(0) }));
368
- const D = t(l.q?.expectedOutput.amount ?? 0).minus(l.repayment).plus(I.maximum(0, l.R.minus(d)));
369
- D.gt(0) && z.push({ coinType: i.debtCoinType, amount: M(D) });
364
+ ), C.conversions = c.q ? [{ ...c.q, id: "repayment", purpose: "repayment", source: "withdrawal" }] : [], C.flashAmount = c.R.toFixed(0), C.flashRepayment = c.repayment.toFixed(0), C.withdrawAmount = c.total.toFixed(0), C.collateralAfter = C.minCollateralAfter = c.c.toFixed(0), C.debtAfter = c.d.toFixed(0);
365
+ const Z = c.total.minus(c.W);
366
+ Z.gt(0) && (k.push({ coinType: o.principalCoinType, amount: Z.toFixed(0) }), re.push({ coinType: o.principalCoinType, amount: Z.toFixed(0) }));
367
+ const D = e(c.q?.expectedOutput.amount ?? 0).minus(c.repayment).plus(R.maximum(0, c.R.minus(v)));
368
+ D.gt(0) && k.push({ coinType: o.debtCoinType, amount: X(D) });
370
369
  } else {
371
- if (p.direction = "decrease", n.type === "close" && c.isZero() && w.protocolCollateralAmount && w.protocolCollateralAmount !== "0")
372
- throw new q(
370
+ if (C.direction = "decrease", s.type === "close" && O.isZero() && x.protocolCollateralAmount && x.protocolCollateralAmount !== "0")
371
+ throw new b(
373
372
  "POSITION_UNSUPPORTED",
374
373
  "This pool does not support collateral dust cleanup"
375
374
  );
376
- u(c.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
377
- const e = n.type === "close", m = t(n.type === "remove_principal" ? n.amount : 0);
378
- u(
379
- m.times(f).lt(Y) || e,
375
+ p(O.gt(0), "POSITION_NOT_FOUND", "No collateral to withdraw");
376
+ const i = s.type === "close", u = e(s.type === "remove_principal" ? s.amount : 0);
377
+ p(
378
+ u.times(A).lt(J) || i,
380
379
  "CONSTRAINT_VIOLATION",
381
380
  "Withdrawal consumes all equity; use close"
382
381
  );
383
- const N = d.isZero() ? d : t(F(d.times("1.0001").plus(ge(r.debt)))), h = async (_) => {
384
- const D = await ae(_.toFixed(0), !1), T = t(D.minOutput.amount).minus(m), g = e || s.eq(1) ? N : I.minimum(d, t(M(T.div(t(r.flash.feeBps).div(1e4).plus(1))))), V = I.maximum(0, d.minus(g)), A = c.minus(_);
382
+ const _ = v.isZero() ? v : e(S(v.times("1.0001").plus(Re(r.debt)))), y = async (t, h) => {
383
+ const I = {
384
+ coinIn: o.collateralCoinType,
385
+ coinOut: o.debtCoinType,
386
+ amountIn: t.toFixed(0),
387
+ slippageBps: w.maxSlippageBps
388
+ }, f = h ? Le(h, I) : await me(t.toFixed(0), !1);
389
+ h && ae(f, I, h.converterId);
390
+ const E = e(f.minOutput.amount).minus(u), m = i || n.eq(1) ? _ : R.minimum(v, e(X(E.div(e(r.flash.feeBps).div(1e4).plus(1))))), d = R.maximum(0, v.minus(m)), V = O.minus(t);
385
391
  return {
386
- q: D,
387
- W: _,
388
- R: g,
389
- repayment: k(g),
390
- c: A,
391
- d: V,
392
- residual: V.times(f).minus(A.times(O).times(s.minus(1)).div(s)),
393
- available: T
392
+ q: f,
393
+ W: t,
394
+ R: m,
395
+ repayment: Q(m),
396
+ c: V,
397
+ d,
398
+ residual: d.times(A).minus(V.times(N).times(n.minus(1)).div(n)),
399
+ available: E
394
400
  };
395
401
  };
396
402
  let a;
397
- if (e) a = await h(c);
398
- else {
399
- let _ = t(
400
- F(
401
- d.times(f).minus(c.times(O).times(s.minus(1)).div(s)).plus(m.times(f)).times(s).div(O)
402
- )
403
- );
404
- u(s.eq(1) || _.gte(0), "ACTION_UNSUPPORTED", ue);
405
- const D = !s.eq(1) && d.times(f).lt(c.times(O).minus(m.times(f)).times(s.minus(1)).div(s));
406
- s.eq(1) && (_ = t(F(N.plus(m).times(f).div(O).times("1.01")))), _ = I.maximum(1, I.minimum(c, _));
407
- for (let T = 0; T < 20; T++) {
408
- a = await h(_);
409
- const g = a.repayment.plus(m).minus(a.q.minOutput.amount);
410
- if (s.eq(1) && g.lt(0) && T < 2) {
411
- const y = t(F(_.times(a.repayment.plus(m)).div(a.q.minOutput.amount)));
412
- if (y.gt(0) && y.lt(_)) {
413
- _ = y;
414
- continue;
403
+ const L = (t) => ({
404
+ ...C,
405
+ conversions: [
406
+ { ...t.q, id: "withdrawal", purpose: "repayment", source: "withdrawal" }
407
+ ],
408
+ flashAmount: t.R.toFixed(0),
409
+ flashRepayment: t.repayment.toFixed(0),
410
+ withdrawAmount: t.W.toFixed(0),
411
+ collateralAfter: t.c.toFixed(0),
412
+ minCollateralAfter: t.c.toFixed(0),
413
+ debtAfter: t.d.toFixed(0)
414
+ });
415
+ let T;
416
+ if (!i && fe && Ne)
417
+ try {
418
+ const t = await ee(fe);
419
+ if (t) {
420
+ M(t.input.amount, !1), M(t.output.amount, !1), p(
421
+ H(t.input.coinType, o.collateralCoinType) && H(t.output.coinType, o.debtCoinType) && Number.isSafeInteger(t.expiresAt) && t.expiresAt > Date.now(),
422
+ "INVALID_CONVERSION",
423
+ "Invalid redemption rate hint"
424
+ );
425
+ const h = e(t.output.amount).div(t.input.amount).times(e(1).minus(e(w.maxSlippageBps).div(1e4))), I = n.minus(1).div(n), f = e(1).plus(e(r.flash.feeBps).div(1e4)), E = h.minus(f.times(I).times(N).div(A)), m = n.eq(1) ? e(S(Q(_).plus(u).div(h))) : e(
426
+ S(
427
+ f.times(v.minus(I.times(O).times(N).div(A))).plus(u).div(E)
428
+ )
429
+ );
430
+ if ((n.eq(1) || E.gt(0)) && m.isFinite() && m.gt(0) && m.lte(O)) {
431
+ const d = await y(m);
432
+ if (T = d, d.R.gte(0) && d.repayment.plus(u).lte(d.q.minOutput.amount) && B(d.c, d.d))
433
+ try {
434
+ ne(L(d)), a = d;
435
+ } catch (V) {
436
+ if (!(V instanceof b) || !["NO_CONVERGENCE", "CAPACITY_EXCEEDED", "CONSTRAINT_VIOLATION"].includes(
437
+ V.code
438
+ ))
439
+ throw V;
440
+ }
415
441
  }
416
442
  }
417
- if (a.R.gte(0) && g.lte(0) && H(a.c, a.d)) break;
418
- const V = s.eq(1) ? g.times(f).div(O) : a.residual.times(s).div(O), A = I.maximum(
419
- 1,
420
- t(F(_.plus(V.times("1.01")).plus(g.gt(0) ? 1 : 0)))
443
+ } catch (t) {
444
+ if (!(t instanceof b) || ![
445
+ "SNAPSHOT_UNAVAILABLE",
446
+ "CONVERTER_UNAVAILABLE",
447
+ "CONVERSION_AMOUNT_TOO_SMALL",
448
+ "NO_CONVERSION_ROUTE"
449
+ ].includes(t.code))
450
+ throw t;
451
+ }
452
+ if (Oe)
453
+ try {
454
+ const t = await ee(Oe);
455
+ if (t) {
456
+ const h = e(t.suiSupply).div(t.lstSupply).times(e(1).minus(e(t.feeRate).div(t.feeDenominator))).times(e(1).minus(e(w.maxSlippageBps).div(1e4))), I = n.minus(1).div(n), f = e(1).plus(e(r.flash.feeBps).div(1e4)), E = h.minus(f.times(I).times(N).div(A)), m = i ? O : n.eq(1) ? e(S(Q(_).plus(u).div(h))) : e(
457
+ S(
458
+ f.times(v.minus(I.times(O).times(N).div(A))).plus(u).div(E)
459
+ )
460
+ );
461
+ if ((i || n.eq(1) || E.gt(0)) && m.isFinite() && m.gt(0) && m.lte(O))
462
+ for (const d of i ? [0] : [0, 1, -1, 2, -2, 3, -3, 4]) {
463
+ const V = m.plus(d);
464
+ if (!V.gt(0) || V.gt(O)) continue;
465
+ const P = await y(V, t);
466
+ if (!(P.R.lt(0) || P.repayment.plus(u).gt(P.q.minOutput.amount) || !i && !B(P.c, P.d)))
467
+ try {
468
+ ne(L(P)), a = P;
469
+ break;
470
+ } catch (G) {
471
+ if (!(G instanceof b) || !["NO_CONVERGENCE", "CAPACITY_EXCEEDED", "CONSTRAINT_VIOLATION"].includes(
472
+ G.code
473
+ ))
474
+ throw G;
475
+ }
476
+ }
477
+ }
478
+ } catch (t) {
479
+ if (!(t instanceof b) || ![
480
+ "SNAPSHOT_UNAVAILABLE",
481
+ "CONVERTER_UNAVAILABLE",
482
+ "CONVERSION_AMOUNT_TOO_SMALL",
483
+ "NO_CONVERSION_ROUTE"
484
+ ].includes(t.code))
485
+ throw t;
486
+ }
487
+ if (!a)
488
+ if (i) a = await y(O);
489
+ else {
490
+ let t = e(
491
+ S(
492
+ v.times(A).minus(O.times(N).times(n.minus(1)).div(n)).plus(u.times(A)).times(n).div(N)
493
+ )
421
494
  );
422
- if (!(A.lt(c) && !A.eq(_) && T < 19))
423
- throw D ? new q("ACTION_UNSUPPORTED", ue) : new q("NO_CONVERGENCE", "No feasible deleverage route within constraints");
424
- _ = A;
495
+ p(n.eq(1) || t.gte(0), "ACTION_UNSUPPORTED", ce);
496
+ const h = !n.eq(1) && v.times(A).lt(O.times(N).minus(u.times(A)).times(n.minus(1)).div(n));
497
+ n.eq(1) && (t = e(S(_.plus(u).times(A).div(N).times("1.01")))), t = R.maximum(1, R.minimum(O, t)), T && T.q.expiresAt > Date.now() && (t = T.W);
498
+ for (let I = 0; I < 20; I++) {
499
+ a = I === 0 && T && T.W.eq(t) && T.q.expiresAt > Date.now() ? T : await y(t);
500
+ const f = a.repayment.plus(u).minus(a.q.minOutput.amount);
501
+ if (n.eq(1) && f.lt(0) && I < 2) {
502
+ const d = e(
503
+ S(t.times(a.repayment.plus(u)).div(a.q.minOutput.amount))
504
+ );
505
+ if (d.gt(0) && d.lt(t)) {
506
+ t = d;
507
+ continue;
508
+ }
509
+ }
510
+ if (a.R.gte(0) && f.lte(0) && B(a.c, a.d)) break;
511
+ const E = n.eq(1) ? f.times(A).div(N) : a.residual.times(n).div(N), m = R.maximum(
512
+ 1,
513
+ e(S(t.plus(E.times("1.01")).plus(f.gt(0) ? 1 : 0)))
514
+ );
515
+ if (!(m.lt(O) && !m.eq(t) && I < 19))
516
+ throw h ? new b("ACTION_UNSUPPORTED", ce) : new b(
517
+ "NO_CONVERGENCE",
518
+ "No feasible deleverage route within constraints"
519
+ );
520
+ t = m;
521
+ }
425
522
  }
426
- }
427
- u(a && a.R.gte(0), "NO_CONVERGENCE", "Missing decrease plan");
428
- const b = I.maximum(0, a.R.minus(d)), v = t(a.q.expectedOutput.amount).plus(b).minus(a.repayment), l = t(a.q.minOutput.amount).minus(a.repayment);
429
- u(
430
- l.gte(m) && l.gte(0),
523
+ p(a && a.R.gte(0), "NO_CONVERGENCE", "Missing decrease plan");
524
+ const c = R.maximum(0, a.R.minus(v)), Z = e(a.q.expectedOutput.amount).plus(c).minus(a.repayment), D = e(a.q.minOutput.amount).minus(a.repayment);
525
+ p(
526
+ D.gte(u) && D.gte(0),
431
527
  "CONSTRAINT_VIOLATION",
432
528
  "Conversion cannot cover flash repayment and withdrawal"
433
- ), p.conversions = [
529
+ ), C.conversions = [
434
530
  { ...a.q, id: "withdrawal", purpose: "repayment", source: "withdrawal" }
435
- ], p.flashAmount = a.R.toFixed(0), p.flashRepayment = a.repayment.toFixed(0), p.withdrawAmount = a.W.toFixed(0), p.collateralAfter = p.minCollateralAfter = a.c.toFixed(0), p.debtAfter = a.d.toFixed(0), v.gt(0) && z.push({ coinType: i.principalCoinType, amount: M(v) }), l.gt(0) && ne.push({ coinType: i.principalCoinType, amount: M(l) });
531
+ ], C.flashAmount = a.R.toFixed(0), C.flashRepayment = a.repayment.toFixed(0), C.withdrawAmount = a.W.toFixed(0), C.collateralAfter = C.minCollateralAfter = a.c.toFixed(0), C.debtAfter = a.d.toFixed(0), Z.gt(0) && k.push({ coinType: o.principalCoinType, amount: X(Z) }), D.gt(0) && re.push({ coinType: o.principalCoinType, amount: X(D) });
436
532
  }
437
- Q.length && (p.funding = {
438
- kind: X(Q[0].coinType, i.collateralCoinType) ? "collateral" : "debt",
439
- input: Q[0]
533
+ $.length && (C.funding = {
534
+ kind: H($[0].coinType, o.collateralCoinType) ? "collateral" : "debt",
535
+ input: $[0]
440
536
  });
441
- function Oe(e) {
442
- for (const v of [
443
- e.flashAmount,
444
- e.flashRepayment,
445
- e.borrowAmount,
446
- e.borrowFee,
447
- e.withdrawAmount,
448
- e.collateralAfter,
449
- e.debtAfter
537
+ function ne(i) {
538
+ for (const T of [
539
+ i.flashAmount,
540
+ i.flashRepayment,
541
+ i.borrowAmount,
542
+ i.borrowFee,
543
+ i.withdrawAmount,
544
+ i.collateralAfter,
545
+ i.debtAfter
450
546
  ])
451
- B(v);
452
- const m = t(e.flashAmount);
453
- u(
454
- m.isZero() || m.gte(r.flash.min) && m.lte(r.flash.max),
547
+ M(T);
548
+ const u = e(i.flashAmount);
549
+ p(
550
+ u.isZero() || u.gte(r.flash.min) && u.lte(r.flash.max),
455
551
  "CAPACITY_EXCEEDED",
456
552
  "Flash liquidity limit exceeded"
457
- ), u(
458
- t(e.borrowAmount).plus(e.borrowFee).lte(Se(r)),
553
+ ), p(
554
+ e(i.borrowAmount).plus(i.borrowFee).lte(Ue(r)),
459
555
  "CAPACITY_EXCEEDED",
460
556
  "Borrow liquidity limit exceeded"
461
- ), u(
462
- Le(i, e, r),
557
+ ), p(
558
+ De(o, i, r),
463
559
  "CAPACITY_EXCEEDED",
464
560
  "Flash and borrow from the same reserve exceed its cash"
465
- ), u(
466
- t(e.collateralAfter).minus(c).lte(Ve(r)),
561
+ ), p(
562
+ e(i.collateralAfter).minus(O).lte(Pe(r)),
467
563
  "CAPACITY_EXCEEDED",
468
564
  "Supply capacity exceeded"
469
- ), xe(n, e, r);
470
- const N = {
471
- collateralAmount: e.collateralAfter,
472
- debtAmount: e.debtAfter
473
- }, h = me(
474
- { ...N, collateralAmount: e.minCollateralAfter },
565
+ ), qe(s, i, r);
566
+ const _ = {
567
+ collateralAmount: i.collateralAfter,
568
+ debtAmount: i.debtAfter
569
+ }, y = de(
570
+ { ..._, collateralAmount: i.minCollateralAfter },
475
571
  r
476
572
  );
477
- u(
478
- h.healthFactor === null || t(h.healthFactor).gte(R.minHealthFactor),
573
+ p(
574
+ y.healthFactor === null || e(y.healthFactor).gte(w.minHealthFactor),
479
575
  "CONSTRAINT_VIOLATION",
480
576
  "Minimum output does not meet health factor constraint"
481
- ), u(
482
- Fe(
483
- { ...N, collateralAmount: e.minCollateralAfter },
484
- w,
577
+ ), p(
578
+ Me(
579
+ { ..._, collateralAmount: i.minCollateralAfter },
580
+ x,
485
581
  r,
486
- e.direction !== "increase"
582
+ i.direction !== "increase"
487
583
  ),
488
584
  "CONSTRAINT_VIOLATION",
489
585
  "Projected debt exceeds collateral LTV"
490
586
  );
491
- const a = _e(
492
- R.maxLeverage,
493
- n,
494
- e.direction,
495
- j.leverage
587
+ const a = ye(
588
+ w.maxLeverage,
589
+ s,
590
+ i.direction,
591
+ K.leverage
496
592
  );
497
- a && h.leverage && u(
498
- t(h.leverage).lte(a),
593
+ a && y.leverage && p(
594
+ e(y.leverage).lte(a),
499
595
  "CONSTRAINT_VIOLATION",
500
596
  "Leverage at the minimum conversion output exceeds maxLeverage"
501
597
  );
502
- const b = me(N, r);
503
- return ["open", "add_principal", "remove_principal", "set_leverage"].includes(n.type) && u(
504
- b.leverage !== null && t(b.leverage).minus(s).abs().lte(s.times("0.0001")),
598
+ const L = de(_, r);
599
+ return ["open", "add_principal", "remove_principal", "set_leverage"].includes(s.type) && p(
600
+ L.leverage !== null && e(L.leverage).minus(n).abs().lte(n.times(Ae)),
505
601
  "NO_CONVERGENCE",
506
602
  "Conversion quote cannot achieve the requested leverage within tolerance"
507
- ), b;
603
+ ), L;
508
604
  }
509
- const we = Oe(p);
605
+ const be = ne(C);
510
606
  return {
511
- execution: p,
512
- estimate: { inputs: Q, outputs: z, minOutputs: ne, ...we }
607
+ execution: C,
608
+ estimate: { inputs: $, outputs: k, minOutputs: re, ...be }
513
609
  };
514
610
  }
515
611
  export {
516
- Ge as chooseConversion,
517
- me as metrics,
518
- Ze as plan,
519
- Be as validateAction
612
+ je as chooseConversion,
613
+ de as metrics,
614
+ Qe as plan,
615
+ Ye as validateAction
520
616
  };
521
617
  //# sourceMappingURL=planner.js.map