@gearbox-protocol/sdk 15.1.0-next.22 → 15.1.0-next.23

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.
Files changed (44) hide show
  1. package/dist/cjs/new-sdk/prepare/PrepareApi.js +4 -4
  2. package/dist/cjs/sdk/accounts/intents/index.js +57 -28
  3. package/dist/cjs/sdk/accounts/intents/plan.js +40 -2
  4. package/dist/cjs/sdk/accounts/intents/realize.js +22 -12
  5. package/dist/cjs/sdk/accounts/intents/tail.js +120 -0
  6. package/dist/cjs/sdk/accounts/intents/utils/index.js +1 -0
  7. package/dist/cjs/sdk/accounts/intents/utils/router-path.js +32 -0
  8. package/dist/esm/dev/AccountOpener.js +1 -1
  9. package/dist/esm/dev/withdrawalUtils.js +1 -1
  10. package/dist/esm/new-sdk/prepare/PrepareApi.js +4 -4
  11. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  12. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  13. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +2 -2
  14. package/dist/esm/sdk/accounts/intents/index.js +58 -29
  15. package/dist/esm/sdk/accounts/intents/plan.js +40 -3
  16. package/dist/esm/sdk/accounts/intents/realize.js +22 -12
  17. package/dist/esm/sdk/accounts/intents/tail.js +118 -0
  18. package/dist/esm/sdk/accounts/intents/utils/index.js +2 -2
  19. package/dist/esm/sdk/accounts/intents/utils/router-path.js +32 -1
  20. package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +1 -1
  21. package/dist/esm/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  22. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  23. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  24. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  25. package/dist/esm/sdk/base/TokensMeta.js +3 -3
  26. package/dist/esm/sdk/chain/detectNetwork.js +1 -1
  27. package/dist/esm/sdk/core/createAddressProvider.js +1 -1
  28. package/dist/esm/sdk/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  29. package/dist/esm/sdk/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  30. package/dist/esm/sdk/market/credit/CreditFacadeV310BaseContract.js +1 -1
  31. package/dist/esm/sdk/market/pool/PoolV310Contract.js +1 -1
  32. package/dist/esm/sdk/market/zapper/IETHZapperContract.js +1 -1
  33. package/dist/esm/sdk/market/zapper/ZapperContract.js +1 -1
  34. package/dist/esm/sdk/pools/PoolService.js +1 -1
  35. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +1 -1
  36. package/dist/types/new-sdk/prepare/types.d.ts +22 -8
  37. package/dist/types/sdk/accounts/intents/index.d.ts +13 -6
  38. package/dist/types/sdk/accounts/intents/plan.d.ts +18 -2
  39. package/dist/types/sdk/accounts/intents/realize.d.ts +7 -0
  40. package/dist/types/sdk/accounts/intents/tail.d.ts +52 -0
  41. package/dist/types/sdk/accounts/intents/types.d.ts +46 -10
  42. package/dist/types/sdk/accounts/intents/utils/index.d.ts +2 -2
  43. package/dist/types/sdk/accounts/intents/utils/router-path.d.ts +15 -1
  44. package/package.json +1 -1
@@ -4,10 +4,10 @@ import { assertMarketOperable } from "./guards.js";
4
4
  import { maxProportionalWithdrawal } from "./math.js";
5
5
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
6
6
  import { previewOpenStrategy } from "./open-strategy.js";
7
- import { instantOutput } from "./operations.js";
8
- import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planFinishClaimOnly, planFinishDecreaseLeverage, planFinishWithdraw, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
7
+ import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
9
8
  import { realize } from "./realize.js";
10
9
  import { accountView } from "./view.js";
10
+ import { planTail, projectTail } from "./tail.js";
11
11
  //#region src/sdk/accounts/intents/index.ts
12
12
  /**
13
13
  * Previews of everything a wallet can do to an existing credit account.
@@ -80,10 +80,16 @@ var CreditAccountOperationsService = class extends SDKConstruct {
80
80
  * {@link intentRoutes}; this is the one to call when the delayed route is the
81
81
  * only one of interest.
82
82
  *
83
+ * `preview` is where the intent ends — the account once the redemption has
84
+ * matured, been claimed and the tail has run — because that is what the
85
+ * caller asked for; the half-way state the request itself lands in is
86
+ * `delayed.afterRequest`. Both are validated, so a request whose tail could
87
+ * not be completed is refused instead of started.
88
+ *
83
89
  * @param props - Intent plus account slice, quota reserve and slippage
84
- * @returns The request transaction and what it recorded for the tail, or
85
- * `{ ok: false, reason }` — `noDelayedRoute` when this route does not exist
86
- * for the account at all
90
+ * @returns The request transaction, the state it ends in and what it recorded
91
+ * for the tail, or `{ ok: false, reason }` — `noDelayedRoute` when this route
92
+ * does not exist for the account at all
87
93
  */
88
94
  async startDelayedIntent(props) {
89
95
  const { intent } = props;
@@ -96,11 +102,30 @@ var CreditAccountOperationsService = class extends SDKConstruct {
96
102
  }
97
103
  });
98
104
  if (!result.ok) return result;
99
- if (!result.delayed) throw new Error("startDelayedIntent: plan started no withdrawal");
100
- return {
105
+ const { delayed } = result;
106
+ if (!delayed) throw new Error("startDelayedIntent: plan started no withdrawal");
107
+ if (delayed.settlement === "instant") return {
101
108
  ...result,
102
- delayed: result.delayed
109
+ delayed
103
110
  };
111
+ const request = result.operations.find((op) => op.type === "startDelayedWithdrawal");
112
+ if (!request) throw new Error("startDelayedIntent: no request among the operations");
113
+ try {
114
+ const tail = await projectTail({
115
+ request,
116
+ delayed,
117
+ creditAccount: props.creditAccount,
118
+ sdk: props.sdk,
119
+ quotaReserve: props.quotaReserve
120
+ });
121
+ return {
122
+ ...result,
123
+ preview: tail.state,
124
+ delayed
125
+ };
126
+ } catch (e) {
127
+ return asFailure(e);
128
+ }
104
129
  }
105
130
  /**
106
131
  * Previews a delayable intent both ways at once: settled by the router now,
@@ -149,9 +174,10 @@ var CreditAccountOperationsService = class extends SDKConstruct {
149
174
  * Previews the tail of a delayed intent, once the withdrawal it started has
150
175
  * matured: the claim, then whatever the intent still owes.
151
176
  *
152
- * Serves the two operations that can genuinely be interrupted by a delay — a
153
- * withdrawal and a deleveraging. For the rest, the claim is the whole tail:
154
- * the tokens land on the account and only their quota has to catch up.
177
+ * Serves the three operations that can genuinely be interrupted by a delay —
178
+ * a withdrawal, a deleveraging and an exit. For the rest, the claim is the
179
+ * whole tail: the tokens land on the account and only their quota has to
180
+ * catch up.
155
181
  *
156
182
  * @param props - The recorded intent, the account slice as it stands now, and
157
183
  * the matured claimable
@@ -159,24 +185,11 @@ var CreditAccountOperationsService = class extends SDKConstruct {
159
185
  * an operation are consumed the same way
160
186
  */
161
187
  async finishIntent(props) {
162
- const { intent, claimable } = props;
163
- return plain(await this.#preview(props, () => {
164
- const view = accountView(props.creditAccount, props.sdk);
165
- const claimed = () => {
166
- const output = instantOutput(claimable.outputs);
167
- if (!output) throw new IntentPreviewError("insufficientSourceBalance", "finishIntent: the claim credits nothing to spend");
168
- return output;
169
- };
170
- switch (intent.type) {
171
- case "WITHDRAW_COLLATERAL": return planFinishWithdraw(intent, claimable, claimed(), view);
172
- case "DECREASE_LEVERAGE": return planFinishDecreaseLeverage(claimable, claimed(), view);
173
- case "ADD_COLLATERAL":
174
- case "INCREASE_LEVERAGE":
175
- case "DEPOSIT":
176
- case "DEPOSIT_AND_INCREASE_LEVERAGE": return planFinishClaimOnly(claimable);
177
- default: throw new Error(`${intent.type} - not implemented`);
178
- }
179
- }));
188
+ return plain(await this.#preview(props, () => planTail({
189
+ intent: props.intent,
190
+ claimable: props.claimable,
191
+ view: accountView(props.creditAccount, props.sdk)
192
+ })));
180
193
  }
181
194
  /**
182
195
  * Previews opening a brand-new leveraged position.
@@ -239,7 +252,23 @@ function asFailure(e) {
239
252
  ok: false,
240
253
  reason: e.reason
241
254
  };
255
+ if (isUnroutable(e)) return {
256
+ ok: false,
257
+ reason: "unsupportedTokenPair"
258
+ };
242
259
  throw e;
243
260
  }
261
+ /**
262
+ * How the pathfinder says there is no route: it reverts instead of answering
263
+ * with an empty path, so viem raises a contract error where the rest of the
264
+ * engine raises an {@link IntentPreviewError}. Nothing is wrong — the trade
265
+ * asked for cannot be made, which is a refusal the caller can act on, and one
266
+ * `intentRoutes` in particular must keep as a value so the other route can
267
+ * still be offered.
268
+ */
269
+ function isUnroutable(e) {
270
+ for (let cause = e; cause instanceof Error; cause = cause.cause) if (cause.message.includes("no optimal edge found")) return true;
271
+ return false;
272
+ }
244
273
  //#endregion
245
274
  export { CreditAccountOperationsService, IntentPreviewError, fetchCreditAccountSlice, toCreditAccountSlice };
@@ -114,11 +114,25 @@ function planWithdraw(intent, view) {
114
114
  *
115
115
  * The tail is planned at claim time by {@link planFinishWithdraw}, from the
116
116
  * intent this request records — only then is the claimed amount, and the token
117
- * it arrived in, known.
117
+ * it arrived in, known. An exit records {@link planFinishCloseAccount}'s intent
118
+ * instead, and rebuilds itself from the account rather than from the request.
118
119
  */
119
120
  function planWithdrawDelayed(intent, view) {
120
121
  const { U, T, S, WU, dD, all } = withdrawShape(intent, view);
121
- if (all) throw new IntentPreviewError("noDelayedRoute", "withdraw: taking the whole net value cannot be started as a redemption");
122
+ if (all) {
123
+ const held = view.balanceOf(S);
124
+ if (held <= 0n) throw new IntentPreviewError("insufficientSourceBalance", `withdraw: account holds no ${S} to redeem`);
125
+ return [{
126
+ kind: "request",
127
+ token: S,
128
+ amount: held,
129
+ reserve: 0n,
130
+ record: {
131
+ type: "CLOSE_ACCOUNT",
132
+ to: intent.to
133
+ }
134
+ }];
135
+ }
122
136
  if (!eq(T, U) && !(view.rwaAsset && eq(T, view.rwaAsset))) throw new IntentPreviewError("noDelayedRoute", `withdraw: a delayed route cannot pay out in ${T}`);
123
137
  const payoutIsSource = eq(T, S);
124
138
  return [{
@@ -217,6 +231,29 @@ function planFinishWithdraw(intent, claimable, claimed, view) {
217
231
  }, intent.to)
218
232
  ];
219
233
  }
234
+ /**
235
+ * The tail of an exit: the claim lands, everything the account holds is sold
236
+ * into the underlying, the loan is settled out of the proceeds and the rest
237
+ * goes to the wallet. The account survives it, empty and owing nothing.
238
+ *
239
+ * Nothing is quoted from the request — the same shape {@link planWithdraw}
240
+ * builds for an instant exit is rebuilt here against the account as it stands
241
+ * now, which is the only state that can name these amounts.
242
+ */
243
+ function planFinishCloseAccount(intent, claimable, claimed, view) {
244
+ const wrap = view.rwaAsset && eq(claimed.token, view.rwaAsset) ? [convert(claimed.token, view.underlying, view.balanceOf(claimed.token) + claimed.amount)] : [];
245
+ return [
246
+ claim(claimable),
247
+ ...wrap,
248
+ clearQuotas(),
249
+ { kind: "closeAll" },
250
+ ...view.debt > 0n ? [repay(view.debt)] : [],
251
+ {
252
+ kind: "sweep",
253
+ to: intent.to
254
+ }
255
+ ];
256
+ }
220
257
  /** Nothing is owed beyond the claim: the tokens land and quotas catch up. */
221
258
  function planFinishClaimOnly(claimable) {
222
259
  return [claim(claimable)];
@@ -358,4 +395,4 @@ function assertPositive(amount, flow) {
358
395
  if (amount <= 0n) throw new IntentPreviewError("insufficientSourceBalance", `${flow}: amount must be positive`);
359
396
  }
360
397
  //#endregion
361
- export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planFinishClaimOnly, planFinishDecreaseLeverage, planFinishWithdraw, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed };
398
+ export { RAISED, planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed };
@@ -24,7 +24,7 @@ async function realize(steps, props) {
24
24
  const { underlying } = creditAccount;
25
25
  const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset;
26
26
  const price = convertAmount(sdk, creditAccount.creditManager);
27
- const paths = createRouterPaths({
27
+ const paths = props.paths ?? createRouterPaths({
28
28
  sdk,
29
29
  creditAccount,
30
30
  slippage
@@ -44,6 +44,7 @@ async function realize(steps, props) {
44
44
  };
45
45
  /** Output of the last convert or claim, for `RAISED` amounts. */
46
46
  let raised = 0n;
47
+ /** The request, before the walk's end state can be attached to it. */
47
48
  let delayed;
48
49
  /**
49
50
  * Set by a `clearQuotas` step, which settles the quotas mid-walk instead of
@@ -145,7 +146,7 @@ async function realize(steps, props) {
145
146
  if (pending) throw new IntentPreviewError("withdrawalInProgress", `closeAll: ${pending.token} is a pending withdrawal, claim it first`);
146
147
  if (balances.length > 0) {
147
148
  const leg = await paths.closeAll({ balances });
148
- if (leg.calls.length > 0) push(buildCloseSwapOperation({
149
+ if (leg.calls.length > 0 || leg.minAmount > 0n) push(buildCloseSwapOperation({
149
150
  from: balances,
150
151
  tokenOut: underlying,
151
152
  amountOut: leg.minAmount,
@@ -184,10 +185,15 @@ async function realize(steps, props) {
184
185
  creditAccount,
185
186
  sdk
186
187
  }));
188
+ const queued = preview.outputs.find((o) => o.isDelayed);
187
189
  delayed = {
188
190
  record: step.record,
189
191
  claimableAt: preview.claimableAt,
190
- settlement: preview.outputs.some((o) => o.isDelayed) ? "delayed" : "instant"
192
+ settlement: queued ? "delayed" : "instant",
193
+ claim: queued ? {
194
+ token: asset.underlying.toLowerCase(),
195
+ amount: toTargetDecimals(queued.amount, queued.token, asset.underlying, sdk)
196
+ } : void 0
191
197
  };
192
198
  raised = instantOutput(preview.outputs)?.amount ?? 0n;
193
199
  break;
@@ -265,18 +271,22 @@ async function realize(steps, props) {
265
271
  liquidationPrice: sdk.positions.liquidationPrice(snapshot)
266
272
  };
267
273
  assertCollateralised(paysOut ? sdk.positions.healthFactor(snapshot, { safePrices: true }) : metrics.healthFactor);
274
+ const state = {
275
+ totalValue,
276
+ accountDebt: debt,
277
+ leverage: calcPositionLeverage(totalValue, debt),
278
+ assets,
279
+ quotas: quotasAfter,
280
+ ...metrics
281
+ };
268
282
  return {
269
283
  operations,
270
- state: {
271
- totalValue,
272
- accountDebt: debt,
273
- leverage: calcPositionLeverage(totalValue, debt),
274
- assets,
275
- quotas: quotasAfter,
276
- ...metrics
277
- },
284
+ state,
278
285
  calls: callsOf(operations),
279
- delayed
286
+ delayed: delayed && {
287
+ ...delayed,
288
+ afterRequest: state
289
+ }
280
290
  };
281
291
  }
282
292
  /**
@@ -0,0 +1,118 @@
1
+ import { IntentPreviewError } from "./types.js";
2
+ import { createOraclePaths } from "./utils/router-path.js";
3
+ import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
4
+ import { instantOutput } from "./operations.js";
5
+ import { realize } from "./realize.js";
6
+ import { accountView } from "./view.js";
7
+ //#region src/sdk/accounts/intents/tail.ts
8
+ /**
9
+ * The second half of a delayed intent: the claim, then whatever the intent
10
+ * still owes.
11
+ *
12
+ * Shared by the two callers that need it and must not disagree — the tail as
13
+ * it is previewed days later against the account that really exists, and the
14
+ * tail as it is projected the moment the request is made.
15
+ */
16
+ function planTail(args) {
17
+ const { intent, claimable, view } = args;
18
+ const claimed = () => {
19
+ const output = instantOutput(claimable.outputs);
20
+ if (!output) throw new IntentPreviewError("insufficientSourceBalance", "finishIntent: the claim credits nothing to spend");
21
+ return output;
22
+ };
23
+ switch (intent.type) {
24
+ case "WITHDRAW_COLLATERAL": return planFinishWithdraw(intent, claimable, claimed(), view);
25
+ case "DECREASE_LEVERAGE": return planFinishDecreaseLeverage(claimable, claimed(), view);
26
+ case "CLOSE_ACCOUNT": return planFinishCloseAccount(intent, claimable, claimed(), view);
27
+ case "ADD_COLLATERAL":
28
+ case "INCREASE_LEVERAGE":
29
+ case "DEPOSIT":
30
+ case "DEPOSIT_AND_INCREASE_LEVERAGE": return planFinishClaimOnly(claimable);
31
+ default: throw new Error(`${intent.type} - not implemented`);
32
+ }
33
+ }
34
+ /**
35
+ * Where a delayed intent ends up, worked out at the moment it is started.
36
+ *
37
+ * A request is only half a withdrawal, so the state it lands in is not the
38
+ * answer to "what does this do to my position": the debt is still there, the
39
+ * payout has not been made, and the position sits in a phantom token. What the
40
+ * caller means is the far side — and that side can be walked now, because the
41
+ * request already fixes the claim it will be finished from.
42
+ *
43
+ * So the same tail {@link planTail} builds at claim time is built here against
44
+ * the account as the request leaves it, with the claim it is expected to bring,
45
+ * and walked by the same realiser — with one substitution: routed legs are
46
+ * priced by the oracle rather than the pathfinder, since the funds they trade
47
+ * do not exist yet and no calldata is being produced. The result is an
48
+ * estimate that the engine's guards are nevertheless applied to, so a request
49
+ * that would strand the account is refused before it is sent rather than
50
+ * discovered days later.
51
+ */
52
+ async function projectTail(args) {
53
+ const { request, delayed, creditAccount, sdk, quotaReserve } = args;
54
+ const { claim } = delayed;
55
+ const queued = request.outputs.find((o) => o.isDelayed);
56
+ if (!queued || !claim) throw new Error("projectTail: the request queued nothing to claim");
57
+ const next = sliceAfter(creditAccount, delayed.afterRequest);
58
+ const steps = planTail({
59
+ intent: delayed.record,
60
+ claimable: projectedClaimable(request, queued.token, queued.amount, claim),
61
+ view: accountView(next, sdk)
62
+ });
63
+ const { state, operations } = await realize(steps, {
64
+ creditAccount: next,
65
+ sdk,
66
+ slippage: 0,
67
+ quotaReserve,
68
+ paths: createOraclePaths({
69
+ sdk,
70
+ creditAccount: next
71
+ })
72
+ });
73
+ return {
74
+ state,
75
+ operations
76
+ };
77
+ }
78
+ /**
79
+ * The matured withdrawal the tail will be built from, as the request implies
80
+ * it: the phantom it created is burned and the venue's payout takes its place.
81
+ * It carries no claim calls — those are read from the chain when the claim is
82
+ * real, and nothing here is going to be sent.
83
+ */
84
+ function projectedClaimable(request, phantom, phantomAmount, claim) {
85
+ return {
86
+ token: request.token,
87
+ withdrawalPhantomToken: phantom,
88
+ withdrawalTokenSpent: phantomAmount,
89
+ outputs: [{
90
+ token: claim.token,
91
+ amount: claim.amount,
92
+ isDelayed: false
93
+ }],
94
+ claimCalls: []
95
+ };
96
+ }
97
+ /**
98
+ * The account as one walk left it, shaped as the slice the next walk reads.
99
+ * Masks are carried over from the tokens the account already held; one it
100
+ * picked up along the way has none to carry, which only the router slice
101
+ * would have used.
102
+ */
103
+ function sliceAfter(creditAccount, after) {
104
+ const masks = new Map(creditAccount.tokens.map((t) => [t.token.toLowerCase(), t.mask]));
105
+ return {
106
+ ...creditAccount,
107
+ accountDebt: after.accountDebt,
108
+ tokens: after.assets.map((a) => ({
109
+ token: a.token,
110
+ balance: a.balance,
111
+ quota: after.quotas[a.token]?.balance ?? 0n,
112
+ mask: masks.get(a.token) ?? 0n,
113
+ success: true
114
+ }))
115
+ };
116
+ }
117
+ //#endregion
118
+ export { planTail, projectTail };
@@ -7,5 +7,5 @@ import { calcBorrowedAmountPlusInterestAndFees } from "./borrowed-amount-plus-in
7
7
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./credit-account-slice.js";
8
8
  import { OperationLedger } from "./ledger.js";
9
9
  import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate } from "./quotas-for-update.js";
10
- import { createRouterPaths } from "./router-path.js";
11
- export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, convertAmount, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, pickFattestNonPhantomToken, quotasAfterUpdate, rankAccountTokens, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals };
10
+ import { createOraclePaths, createRouterPaths } from "./router-path.js";
11
+ export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, convertAmount, createOraclePaths, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, pickFattestNonPhantomToken, quotasAfterUpdate, rankAccountTokens, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals };
@@ -1,4 +1,5 @@
1
1
  import { toRouterCaSlice } from "./common.js";
2
+ import { convertAmount } from "./convert-amount.js";
2
3
  //#region src/sdk/accounts/intents/utils/router-path.ts
3
4
  /**
4
5
  * The engine's only door to the pathfinder.
@@ -81,5 +82,35 @@ function createRouterPaths(args) {
81
82
  }
82
83
  };
83
84
  }
85
+ /**
86
+ * The same door, priced by the oracle and opening onto no calldata.
87
+ *
88
+ * For a leg that cannot be quoted yet: the tail of a redemption trades funds
89
+ * that do not exist, along a route the pathfinder will only be able to build
90
+ * once they do. Asking it now would price a swap of nothing, so the amounts
91
+ * come from the oracle instead — an estimate with no slippage floor, which is
92
+ * all a projection days out can honestly be — and the walk yields a state
93
+ * rather than a transaction.
94
+ */
95
+ function createOraclePaths(args) {
96
+ const { sdk, creditAccount } = args;
97
+ const price = convertAmount(sdk, creditAccount.creditManager);
98
+ const estimate = (amount) => ({
99
+ amount,
100
+ minAmount: amount,
101
+ calls: []
102
+ });
103
+ return {
104
+ async swap({ tokenIn, tokenOut, amount }) {
105
+ return estimate(amount > 0n ? price(tokenIn, tokenOut, amount) : 0n);
106
+ },
107
+ async closeAll({ balances }) {
108
+ return estimate(balances.reduce((sum, b) => sum + price(b.token, creditAccount.underlying, b.balance), 0n));
109
+ },
110
+ async openStrategy() {
111
+ throw new Error("oracle paths: opening a position is never projected");
112
+ }
113
+ };
114
+ }
84
115
  //#endregion
85
- export { createRouterPaths };
116
+ export { createOraclePaths, createRouterPaths };
@@ -1,3 +1,4 @@
1
+ import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
1
2
  import { AddressSet } from "../../utils/AddressSet.js";
2
3
  import { bytes32ToString } from "../../utils/bytes32ToString.js";
3
4
  import { ADDRESS_0X0 } from "../../constants/addresses.js";
@@ -19,7 +20,6 @@ import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/Securi
19
20
  import "../../market/rwa/securitize/index.js";
20
21
  import "../../market/index.js";
21
22
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
22
- import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
23
23
  //#region src/sdk/accounts/liquidations/LiquidationsService.ts
24
24
  /**
25
25
  * Service for discovering liquidatable credit accounts and previewing manual
@@ -1,7 +1,7 @@
1
+ import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
1
2
  import { BaseContract } from "../../base/BaseContract.js";
2
3
  import "../../base/index.js";
3
4
  import { decodeDelayedIntent } from "./intent-codec.js";
4
- import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
5
5
  import { InvalidDelayedIntentError } from "./errors.js";
6
6
  //#region src/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.ts
7
7
  const abi = iRedemptionLoggerV310Abi;
@@ -1,5 +1,5 @@
1
- import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
1
  import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
2
+ import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
3
3
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.ts
4
4
  const abi = iWithdrawalCompressorV310Abi;
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
1
  import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
2
+ import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
3
3
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.ts
4
4
  const abi = iWithdrawalCompressorV311Abi;
5
5
  /**
@@ -1,6 +1,6 @@
1
+ import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
1
2
  import { encodeDelayedIntent } from "./intent-codec.js";
2
3
  import { AbstractWithdrawalCompressorContract, iCreditAccountAbi, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal } from "./AbstractWithdrawalCompressorContract.js";
3
- import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
4
4
  import { toWithdrawalStatus } from "./types.js";
5
5
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.ts
6
6
  const abi = iWithdrawalCompressorV313Abi;
@@ -1,12 +1,12 @@
1
+ import { iExpirableAbi } from "../../abi/iExpirable.js";
2
+ import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
3
+ import { iVersionAbi } from "../../abi/iVersion.js";
1
4
  import { AddressMap } from "../utils/AddressMap.js";
2
5
  import { AddressSet } from "../utils/AddressSet.js";
3
6
  import { bytes32ToString } from "../utils/bytes32ToString.js";
4
7
  import { getAssetType } from "../chain/chains.js";
5
8
  import { formatBN } from "../utils/formatter.js";
6
9
  import "../utils/index.js";
7
- import { iExpirableAbi } from "../../abi/iExpirable.js";
8
- import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
9
- import { iVersionAbi } from "../../abi/iVersion.js";
10
10
  import { executeMulticallBatches } from "../utils/viem/executeMulticallBatches.js";
11
11
  //#region src/sdk/base/TokensMeta.ts
12
12
  /**
@@ -1,5 +1,5 @@
1
- import { chains } from "./chains.js";
2
1
  import { ierc20Abi } from "../../abi/iERC20.js";
2
+ import { chains } from "./chains.js";
3
3
  //#region src/sdk/chain/detectNetwork.ts
4
4
  /**
5
5
  * Detects the network type from the given client.
@@ -1,8 +1,8 @@
1
+ import { iVersionAbi } from "../../abi/iVersion.js";
1
2
  import { AP_MARKET_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR } from "../constants/address-provider.js";
2
3
  import { isV310 } from "../constants/versions.js";
3
4
  import "../constants/index.js";
4
5
  import { hexEq } from "../utils/hex.js";
5
- import { iVersionAbi } from "../../abi/iVersion.js";
6
6
  import { AddressProviderV310Contract } from "./AddressProviderV310Contract.js";
7
7
  //#region src/sdk/core/createAddressProvider.ts
8
8
  const OVERRIDE_ADDRESSES = { Mainnet: {
@@ -1,5 +1,5 @@
1
- import { AbstractAdapterContract } from "./AbstractAdapter.js";
2
1
  import { accountMigratorAbi } from "../../../../abi/AccountMigrator.js";
2
+ import { AbstractAdapterContract } from "./AbstractAdapter.js";
3
3
  //#region src/sdk/market/adapters/contracts/AccountMigratorAdapterContract.ts
4
4
  const abi = accountMigratorAbi;
5
5
  const protocolAbi = accountMigratorAbi;
@@ -1,6 +1,6 @@
1
+ import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
1
2
  import { MissingSerializedParamsError } from "../../../base/errors.js";
2
3
  import "../../../base/index.js";
3
- import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
4
4
  import { iERC4626Abi } from "../abi/targetContractAbi.js";
5
5
  import { fnSigToName, swapFromTransfers } from "../transferHelpers.js";
6
6
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
@@ -1,7 +1,7 @@
1
+ import { iPausableAbi } from "../../../abi/iPausable.js";
1
2
  import { iCreditFacadeMulticallV310Abi, iCreditFacadeV310Abi } from "../../../abi/310/generated.js";
2
3
  import { BaseContract } from "../../base/BaseContract.js";
3
4
  import "../../base/index.js";
4
- import { iPausableAbi } from "../../../abi/iPausable.js";
5
5
  //#region src/sdk/market/credit/CreditFacadeV310BaseContract.ts
6
6
  const abi = [
7
7
  ...iCreditFacadeV310Abi,
@@ -1,3 +1,4 @@
1
+ import { iPausableAbi } from "../../../abi/iPausable.js";
1
2
  import { iPoolV310Abi } from "../../../abi/310/generated.js";
2
3
  import { AddressMap } from "../../utils/AddressMap.js";
3
4
  import { RAY } from "../../constants/math.js";
@@ -6,7 +7,6 @@ import { formatBN, formatBNvalue, percentFmt } from "../../utils/formatter.js";
6
7
  import "../../utils/index.js";
7
8
  import { BaseContract } from "../../base/BaseContract.js";
8
9
  import "../../base/index.js";
9
- import { iPausableAbi } from "../../../abi/iPausable.js";
10
10
  import { calcUtilization } from "../math.js";
11
11
  //#region src/sdk/market/pool/PoolV310Contract.ts
12
12
  const abi = [...iPoolV310Abi, ...iPausableAbi];
@@ -1,5 +1,5 @@
1
- import { ZapperContract } from "./ZapperContract.js";
2
1
  import { iethZapperAbi } from "../../../abi/iETHZapper.js";
2
+ import { ZapperContract } from "./ZapperContract.js";
3
3
  //#region src/sdk/market/zapper/IETHZapperContract.ts
4
4
  const abi = iethZapperAbi;
5
5
  var IETHZapperContract = class extends ZapperContract {
@@ -1,6 +1,6 @@
1
+ import { iZapperAbi } from "../../../abi/iZapper.js";
1
2
  import { BaseContract } from "../../base/BaseContract.js";
2
3
  import "../../base/index.js";
3
- import { iZapperAbi } from "../../../abi/iZapper.js";
4
4
  import { UnsupportedZapperFunctionError } from "./errors.js";
5
5
  //#region src/sdk/market/zapper/ZapperContract.ts
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { AddressSet } from "../utils/AddressSet.js";
2
1
  import { ierc20Abi } from "../../abi/iERC20.js";
2
+ import { AddressSet } from "../utils/AddressSet.js";
3
3
  import "../constants/addresses.js";
4
4
  import { PERCENTAGE_FACTOR, RAY } from "../constants/math.js";
5
5
  import "../constants/index.js";
@@ -1,6 +1,6 @@
1
1
  import { errorAbis } from "../../../abi/errors.js";
2
- import { generateCastTraceCall } from "./cast.js";
3
2
  import { iUpdatablePriceFeedAbi } from "../../../abi/iUpdatablePriceFeed.js";
3
+ import { generateCastTraceCall } from "./cast.js";
4
4
  import { simulateMulticall } from "./simulateMulticall.js";
5
5
  import { BaseError, CallExecutionError, ContractFunctionRevertedError, decodeFunctionData, decodeFunctionResult, encodeFunctionData, parseAbi } from "viem";
6
6
  import { getAction, parseAccount } from "viem/utils";