@lifi/composer-sdk 0.3.0 → 0.4.0-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +21 -0
  2. package/dist/client.cjs +1 -1
  3. package/dist/client.cjs.map +1 -1
  4. package/dist/client.js +1 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/errors.cjs +26 -3
  7. package/dist/errors.cjs.map +1 -1
  8. package/dist/errors.d.cts +46 -2
  9. package/dist/errors.d.ts +46 -2
  10. package/dist/errors.js +24 -2
  11. package/dist/errors.js.map +1 -1
  12. package/dist/generated/materialisers.generated.cjs +8 -2
  13. package/dist/generated/materialisers.generated.cjs.map +1 -1
  14. package/dist/generated/materialisers.generated.d.cts +1 -1
  15. package/dist/generated/materialisers.generated.d.ts +1 -1
  16. package/dist/generated/materialisers.generated.js +6 -1
  17. package/dist/generated/materialisers.generated.js.map +1 -1
  18. package/dist/generated/operations.generated.cjs +39 -1
  19. package/dist/generated/operations.generated.cjs.map +1 -1
  20. package/dist/generated/operations.generated.d.cts +111 -2
  21. package/dist/generated/operations.generated.d.ts +111 -2
  22. package/dist/generated/operations.generated.js +39 -1
  23. package/dist/generated/operations.generated.js.map +1 -1
  24. package/dist/index.cjs +2 -0
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +3 -3
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +2 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/{materialisers.generated-BMkBQgWZ.d.ts → materialisers.generated-BfWJ-g7t.d.ts} +8 -3
  31. package/dist/{materialisers.generated-BWq5oePO.d.cts → materialisers.generated-DaJRwiRe.d.cts} +8 -3
  32. package/dist/responseSchemas.cjs +10 -1
  33. package/dist/responseSchemas.cjs.map +1 -1
  34. package/dist/responseSchemas.d.cts +15 -1
  35. package/dist/responseSchemas.d.ts +15 -1
  36. package/dist/responseSchemas.js +10 -1
  37. package/dist/responseSchemas.js.map +1 -1
  38. package/package.json +3 -4
  39. package/src/errors.ts +67 -1
  40. package/src/examples/staged/aaveBorrow.ts +128 -0
  41. package/src/examples/staged/aaveDebtRebalanceExactOut.ts +301 -0
  42. package/src/examples/staged/aaveHealthFactorExplode.ts +70 -0
  43. package/src/examples/staged/aaveToMorphoDebtMigration.ts +200 -0
  44. package/src/examples/staged/aaveToMorphoDebtMigrationWithSwap.ts +231 -0
  45. package/src/examples/staged/aaveToMorphoDebtMigrationWithSwapExactOut.ts +307 -0
  46. package/src/examples/staged/flashloanRepay.ts +142 -0
  47. package/src/examples/staged/manualRelayContinuation.ts +161 -0
  48. package/src/examples/staged/morphoBlueBorrow.ts +93 -0
  49. package/src/examples/staged/morphoBlueRepay.ts +132 -0
  50. package/src/examples/staged/registry.ts +89 -0
  51. package/src/generated/materialisers.generated.ts +12 -0
  52. package/src/generated/operations.generated.ts +214 -0
  53. package/src/index.ts +7 -2
  54. package/src/responseSchemas.ts +29 -0
@@ -0,0 +1,301 @@
1
+ import type { ComposeCompileRequest, Flow } from '@lifi/compose-spec';
2
+
3
+ import { createComposeSdk, materialisers, resources } from '../../index.js';
4
+ import type { Address } from '../../types.js';
5
+ import { API_KEY, BASE_URL } from '../config.js';
6
+
7
+ // Base mainnet token addresses.
8
+ const BASE_WETH = '0x4200000000000000000000000000000000000006';
9
+ const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
10
+ // Circle EURC on Base (6 decimals).
11
+ const BASE_EURC = '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42';
12
+
13
+ // Token decimals for the Paraswap BUY (raw-address requests require them).
14
+ const EURC_DECIMALS = 6;
15
+ const USDC_DECIMALS = 6;
16
+
17
+ // Aave V3 on Base: pool + WETH aToken + variable-debt tokens for the old (USDC)
18
+ // and new (EURC) debt assets. The variable-debt token only feeds aave.borrow
19
+ // (to read the post-borrow debt balance); aave.repay infers the asset from its
20
+ // bound input resource. Verified live against Pool.getReserveData on Base.
21
+ const AAVE_V3_POOL_BASE = '0xA238Dd80C259a72e81d7e4664a9801593F98d1c5';
22
+ const A_BAS_WETH = '0xD4a0e0b9149BCee3C920d2E00b5dE09138fd8bb7';
23
+ const VDEBT_BAS_USDC = '0x59dca05b6c26dbd64b5381374aAaC5CD05644C28';
24
+ const VDEBT_BAS_EURC = '0x03D01595769333174036832e18fA2f17C74f8161';
25
+
26
+ // Aave V3 flashloan premium (FLASHLOAN_PREMIUM_TOTAL) = 5 bps of principal.
27
+ // Mirrors the builtins package's `computeDefaultFee('aave-v3', amount)`,
28
+ // inlined so the example stays free of compose-internals imports (the SDK must
29
+ // not cross the manifest boundary into the builtins package). Override if the
30
+ // pool's premium has changed on-chain.
31
+ const AAVE_V3_FEE_BPS = 5n;
32
+ const BPS_DENOMINATOR = 10_000n;
33
+ const computeAaveV3Fee = (principal: bigint): bigint =>
34
+ (principal * AAVE_V3_FEE_BPS) / BPS_DENOMINATOR;
35
+
36
+ // Source-cap slippage on the EURC → USDC BUY, in basis points. This bounds how
37
+ // much extra EURC Augustus may pull above the quoted source before refunding.
38
+ // `newDebtBorrowAmount` must exceed the resulting `maxAmountIn`.
39
+ const DEFAULT_MAX_SLIPPAGE_BPS = 100; // 1%
40
+
41
+ export interface AaveDebtRebalanceExactOutInput {
42
+ readonly owner: Address;
43
+ /**
44
+ * WETH collateral used to seed the position (in smallest units, 18 decimals).
45
+ * In production the position already exists and this seed step is omitted —
46
+ * the collateral is never touched by the rebalance itself.
47
+ */
48
+ readonly collateralAmount: `${bigint}`;
49
+ /**
50
+ * Outstanding USDC debt to rebalance away from (6 decimals). The flashloan is
51
+ * sized to this; in production size it just above the live debt so the capped
52
+ * repay clears it after accrued interest.
53
+ */
54
+ readonly debtAmount: `${bigint}`;
55
+ /**
56
+ * EURC to borrow as the *new* debt (6 decimals). Sized as a *generous upper
57
+ * bound* — large enough that the exact-output BUY can always produce
58
+ * `debtAmount + aaveV3Fee` USDC even after `maxSlippageBps` of source slippage
59
+ * (i.e. `newDebtBorrowAmount > maxAmountIn`). The BUY pulls only what it needs;
60
+ * the unspent EURC is repaid straight back into the freshly-minted EURC debt,
61
+ * so the *net* new debt is the original USDC debt (in EURC terms) plus only
62
+ * the slippage/fee actually consumed — NOT the full upper bound.
63
+ * Note: EUR/USD is not 1:1 — size off a live BUY quote, e.g.
64
+ * newDebtBorrowAmount ≈ ceil((debtAmount + aaveV3Fee) * eurcPerUsdc * (1 + slippage))
65
+ */
66
+ readonly newDebtBorrowAmount: `${bigint}`;
67
+ /** Optional source-cap slippage on the BUY, in bps (default 100 = 1%). */
68
+ readonly maxSlippageBps?: number;
69
+ /** Optional integrator label for analytics / fee capture. */
70
+ readonly partner?: string;
71
+ /** Optional fee recipient; required to actually receive a partner fee. */
72
+ readonly partnerAddress?: Address;
73
+ /** Optional fixed partner fee in bps (e.g. '50' = 0.5%); needs partnerAddress. */
74
+ readonly partnerFeeBps?: string;
75
+ }
76
+
77
+ /**
78
+ * Atomically **rebalance** (debt-swap) an Aave V3 position on Base from USDC
79
+ * debt into EURC debt — same protocol, same WETH collateral, only the debt
80
+ * *token* changes — using a native **exact-output** (Paraswap/Velora BUY) swap.
81
+ *
82
+ * This is the single-protocol "debt switch" pattern productised by Aave's
83
+ * `ParaSwapDebtSwapAdapter` and DeFi Saver's "Debt Switch": flashloan/borrow the
84
+ * new debt slightly over a cap, exact-out-swap to produce exactly the old debt
85
+ * owed, repay the old debt, then repay the leftover new asset back into the
86
+ * freshly-created new debt so lasting debt = only what was consumed. Contrast
87
+ * with `aaveToMorphoDebtMigrationWithSwapExactOut.ts`, which *migrates* the whole
88
+ * position across protocols (Aave → Morpho) and therefore needs a second
89
+ * flashloan to move the collateral; here the collateral never moves, so a single
90
+ * flashloan of the old debt token suffices.
91
+ *
92
+ * Why rebalance USDC → EURC: at the time of writing EURC's Base Aave V3 variable
93
+ * borrow APR (~3.87%) sits below USDC's (~4.28%), and a EUR-based borrower may
94
+ * also want the liability denominated in EUR to match income/assets (removing
95
+ * USD/EUR FX risk on the debt). The reward is the APR delta over the holding
96
+ * period; the cost is the Aave flashloan premium plus the realised swap
97
+ * slippage on the consumed notional only.
98
+ *
99
+ * Phase 1 — provision the starting position on Aave V3 (illustrative; omit in
100
+ * production where the position already exists):
101
+ * - User direct-deposits WETH.
102
+ * - `lifi.zap` supplies the WETH to Aave (WETH → aBasWETH routing edge).
103
+ * - `aave.borrow` mints the USDC debt being rebalanced; the borrowed USDC is
104
+ * swept back to the signer as the user's existing loan proceeds.
105
+ *
106
+ * Phase 2 — rebalance USDC debt → EURC debt with one flashloan:
107
+ * - Flashloan (Aave V3, USDC) bridges the old-debt payoff before the new debt
108
+ * exists.
109
+ * - `aave.repay(mode: 'max')` clears the USDC debt with the flashloan; Aave's
110
+ * Pool clamps to the outstanding debt exactly, any cap residual is swept.
111
+ * - `aave.borrow` mints a *capped* (generously over-sized) `newDebtBorrowAmount`
112
+ * of EURC against the same, still-supplied WETH collateral.
113
+ * - `paraswap.buy` buys *exactly* `debtAmount + aaveV3Fee` USDC with the borrowed
114
+ * EURC, pulling only the EURC needed. `amountOut` is the exact figure that
115
+ * settles the USDC flashloan leg; `unspentIn` is the refunded, unspent EURC.
116
+ * - `lifi.flashloanRepay` settles the USDC leg from `buy.amountOut` (no
117
+ * feeBuffer: `amountOut == principal + fee` by construction).
118
+ * - `aave.repay(mode: 'max')` repays the unspent EURC (`buy.unspentIn`) straight
119
+ * back into the freshly-minted EURC debt, unwinding the borrow buffer. Any
120
+ * genuine over-repay surfaces through the repay op's `residual`, swept to the
121
+ * signer.
122
+ *
123
+ * After execution the signer holds the same WETH collateral on Aave V3 with EURC
124
+ * debt equal to the original USDC debt (in EUR terms) plus only the consumed
125
+ * slippage/fee; the USDC debt is closed.
126
+ */
127
+ export const buildAaveDebtRebalanceExactOut = ({
128
+ owner,
129
+ collateralAmount,
130
+ debtAmount,
131
+ newDebtBorrowAmount,
132
+ maxSlippageBps = DEFAULT_MAX_SLIPPAGE_BPS,
133
+ partner,
134
+ partnerAddress,
135
+ partnerFeeBps,
136
+ }: AaveDebtRebalanceExactOutInput): {
137
+ flow: Flow;
138
+ request: ComposeCompileRequest;
139
+ } => {
140
+ const sdk = createComposeSdk({ baseUrl: BASE_URL, apiKey: API_KEY });
141
+
142
+ // The USDC the BUY must produce: the flashloan principal plus the Aave V3
143
+ // flashloan premium. This is exactly what settles the debt flashloan leg.
144
+ const exactUsdcOut = (
145
+ BigInt(debtAmount) + computeAaveV3Fee(BigInt(debtAmount))
146
+ ).toString() as `${bigint}`;
147
+
148
+ const builder = sdk.flow(8453, {
149
+ name: 'aave-debt-rebalance-usdc-to-eurc-exact-out',
150
+ inputs: {
151
+ initialCollateral: resources.erc20(BASE_WETH, 8453),
152
+ // Single flashloan: the old (USDC) debt token. No collateral flashloan is
153
+ // needed because the WETH collateral never leaves Aave.
154
+ debtFlashloan: resources.erc20(BASE_USDC, 8453),
155
+ },
156
+ });
157
+
158
+ // --- Phase 1: provision the starting Aave V3 USDC borrow -----------------
159
+
160
+ // WETH → aBasWETH via the aave routing edge family (Aave V3 supply). The
161
+ // supplied collateral is never withdrawn — it backs the new EURC debt — so
162
+ // the aBasWETH output is intentionally left unconsumed AND unswept: it is the
163
+ // user's resulting collateral position and must stay on the (persistent,
164
+ // per-user) proxy. This is why the flow does NOT set a blanket `sweepTo`
165
+ // (which would try to transfer the aToken out and revert, since collateral
166
+ // backing an open debt cannot be moved); instead we explicitly transfer only
167
+ // the genuinely-loose tokens below.
168
+ builder.lifi.zap('supply-collateral', {
169
+ bind: { amountIn: builder.inputs.initialCollateral },
170
+ config: { resourceOut: resources.erc20(A_BAS_WETH, 8453) },
171
+ });
172
+
173
+ // Borrow the USDC debt being rebalanced. The proceeds are the user's loan;
174
+ // they remain as the proxy's residual USDC and are forwarded to the signer at
175
+ // the end of the flow (see `payout-borrow-proceeds`).
176
+ builder.aave.borrow('borrow-usdc-debt', {
177
+ bind: {},
178
+ config: {
179
+ pool: AAVE_V3_POOL_BASE,
180
+ asset: BASE_USDC,
181
+ variableDebtToken: VDEBT_BAS_USDC,
182
+ amount: debtAmount,
183
+ },
184
+ });
185
+
186
+ // --- Phase 2: rebalance USDC debt → EURC debt ----------------------------
187
+
188
+ // Settle the USDC debt with the flashloan. mode: 'max' makes Aave's Pool
189
+ // clamp paybackAmount to the outstanding debt exactly; unspent flashloan
190
+ // principal flows through the op's residual port (swept).
191
+ builder.aave.repay('repay-usdc-debt', {
192
+ bind: {
193
+ assetIn: builder.inputs.debtFlashloan,
194
+ onBehalfOf: builder.context.executionAddress,
195
+ },
196
+ config: { pool: AAVE_V3_POOL_BASE, mode: 'max' },
197
+ });
198
+
199
+ // Borrow a capped (generously over-sized) EURC amount against the same WETH
200
+ // collateral, now that the USDC debt is cleared. The over-borrow is
201
+ // intentional and is unwound below.
202
+ const borrowEurc = builder.aave.borrow('borrow-eurc-debt', {
203
+ bind: {},
204
+ config: {
205
+ pool: AAVE_V3_POOL_BASE,
206
+ asset: BASE_EURC,
207
+ variableDebtToken: VDEBT_BAS_EURC,
208
+ amount: newDebtBorrowAmount,
209
+ },
210
+ });
211
+
212
+ // Exact-output BUY: produce EXACTLY `exactUsdcOut` USDC from the borrowed
213
+ // EURC, pulling only the EURC needed and refunding the rest to the proxy
214
+ // (surfaced as `unspentIn`). `amountOut` is the exact figure that settles the
215
+ // USDC flashloan leg.
216
+ const buyUsdc = builder.paraswap.buy('buy-usdc-exact', {
217
+ bind: { amountIn: borrowEurc.borrowed },
218
+ config: {
219
+ resourceOut: resources.erc20(BASE_USDC, 8453),
220
+ exactAmountOut: exactUsdcOut,
221
+ srcDecimals: EURC_DECIMALS,
222
+ destDecimals: USDC_DECIMALS,
223
+ maxSlippageBps,
224
+ ...(partner !== undefined ? { partner } : {}),
225
+ ...(partnerAddress !== undefined ? { partnerAddress } : {}),
226
+ ...(partnerFeeBps !== undefined ? { partnerFeeBps } : {}),
227
+ },
228
+ });
229
+
230
+ // Settle the USDC flashloan leg with the exact BUY output. No feeBuffer:
231
+ // `amountOut == principal + fee` by construction.
232
+ builder.lifi.flashloanRepay('repay-debt-flashloan', {
233
+ bind: { funds: buyUsdc.amountOut },
234
+ config: { leg: 'debtFlashloan' },
235
+ });
236
+
237
+ // Unwind the over-borrow: repay the proxy's FULL residual EURC back into the
238
+ // freshly-minted EURC debt, so the new debt equals exactly the EURC the swap
239
+ // consumed. We read the live EURC balance rather than binding `buy.unspentIn`:
240
+ // unspentIn is only Augustus's refund (cap − used), but the proxy ALSO still
241
+ // holds the headroom we over-borrowed above the swap cap (borrow − cap), which
242
+ // Augustus never pulled. The live balance captures both, leaving zero idle.
243
+ // mode: 'exact' pulls precisely this balance (Aave clamps to min(balance,
244
+ // debt)); mode: 'max' would pass type(uint256).max and try to pull the whole
245
+ // outstanding debt, far exceeding the residual on the proxy, and revert.
246
+ const eurcResidual = builder.core.balanceOf('read-eurc-residual', {
247
+ bind: {},
248
+ config: { token: BASE_EURC },
249
+ });
250
+ builder.aave.repay('repay-eurc-remainder', {
251
+ bind: {
252
+ assetIn: eurcResidual.balance,
253
+ onBehalfOf: builder.context.executionAddress,
254
+ },
255
+ config: { pool: AAVE_V3_POOL_BASE, mode: 'exact' },
256
+ });
257
+
258
+ // Forward the genuinely-loose token — the residual USDC loan proceeds — to the
259
+ // signer. We read the proxy's LIVE USDC balance rather than the fixed borrowed
260
+ // amount: Aave's `mode: 'max'` USDC-debt repay overshoots the borrow by up to
261
+ // 1 wei (ray-math round-trip), so the proxy ends a wei short of `borrowed` —
262
+ // transferring a fixed amount would revert "transfer amount exceeds balance".
263
+ // The live balance always moves exactly what is there.
264
+ //
265
+ // We deliberately do NOT use a blanket `sweepTo`: the only other proxy-held
266
+ // balance is the aBasWETH collateral position, which cannot be transferred
267
+ // while the EURC debt is open (Aave's finalizeTransfer reverts). The position
268
+ // therefore stays on the persistent per-user proxy; we move out only the USDC.
269
+ const usdcResidual = builder.core.balanceOf('read-usdc-residual', {
270
+ bind: {},
271
+ config: { token: BASE_USDC },
272
+ });
273
+ builder.core.transfer('payout-borrow-proceeds', {
274
+ bind: {
275
+ amount: usdcResidual.balance,
276
+ recipient: builder.context.sender,
277
+ },
278
+ config: {},
279
+ });
280
+
281
+ const flow = builder.build();
282
+
283
+ const request = sdk.request(flow, {
284
+ signer: owner,
285
+ inputs: {
286
+ initialCollateral: materialisers.directDeposit({
287
+ amount: collateralAmount,
288
+ }),
289
+ debtFlashloan: materialisers.flashloan({
290
+ providerKind: 'aave-v3',
291
+ amount: debtAmount,
292
+ }),
293
+ },
294
+ // No blanket `sweepTo`: the resulting aBasWETH collateral position stays on
295
+ // the proxy (it backs the open EURC debt and cannot be moved). The loose
296
+ // USDC proceeds are forwarded via the explicit `payout-borrow-proceeds`
297
+ // transfer above.
298
+ });
299
+
300
+ return { flow, request };
301
+ };
@@ -0,0 +1,70 @@
1
+ import type { ComposeCompileRequest, Flow } from '@lifi/compose-spec';
2
+
3
+ import { createComposeSdk, guards } from '../../index.js';
4
+ import type { Address } from '../../types.js';
5
+ import { API_KEY, BASE_URL } from '../config.js';
6
+
7
+ // Base mainnet Aave v3 Pool.
8
+ const AAVE_V3_POOL = '0xA238Dd80C259a72e81d7e4664a9801593F98d1c5';
9
+
10
+ // 1.0 WAD (1e18) — minimum acceptable health factor.
11
+ const MIN_HEALTH_FACTOR_WAD = '1000000000000000000';
12
+
13
+ export interface AaveHealthFactorExplodeInput {
14
+ readonly signer: Address;
15
+ }
16
+
17
+ /**
18
+ * EXPLODE / DecomposeValue showcase.
19
+ *
20
+ * NOTE: currently disabled end-to-end. `aave.getHealthFactor` is in the
21
+ * default `DISABLED_COMPOSE_OPS` set on zap-backend because the EXPLODE
22
+ * opcode is not yet supported on-chain. The example still builds a valid
23
+ * Flow JSON (and its spec passes), but submitting the request to a backend
24
+ * with default config will fail at op resolution. Re-enable by unsetting
25
+ * `aave.getHealthFactor` in the backend's `DISABLED_COMPOSE_OPS` once
26
+ * contracts ship EXPLODE.
27
+ *
28
+ * Builds a minimal compose flow that:
29
+ * - StaticCalls `IPool.getUserAccountData(user)` on Aave v3 (Base)
30
+ * - Decomposes the returned 6-tuple via the EXPLODE opcode
31
+ * - Asserts `healthFactor >= 1.0 WAD` via `core.numericInvariant`
32
+ *
33
+ * The signer must hold an Aave v3 position on the target chain so HF > 0.
34
+ * Uses `allow-revert` so the compiled calldata is returned even if the
35
+ * assertion would fail — handy for tracing on a fork.
36
+ */
37
+ export const buildAaveHealthFactorExplode = ({
38
+ signer,
39
+ }: AaveHealthFactorExplodeInput): {
40
+ flow: Flow;
41
+ request: ComposeCompileRequest;
42
+ } => {
43
+ const sdk = createComposeSdk({ baseUrl: BASE_URL, apiKey: API_KEY });
44
+
45
+ const builder = sdk.flow(8453 /* Base */, {
46
+ name: 'aave-hf-explode-showcase',
47
+ inputs: {},
48
+ });
49
+
50
+ builder.aave.getHealthFactor('checkHf', {
51
+ bind: {},
52
+ config: { pool: AAVE_V3_POOL, user: signer },
53
+ guards: [
54
+ guards.coreNumericInvariant({
55
+ port: 'healthFactor',
56
+ op: 'gte',
57
+ threshold: MIN_HEALTH_FACTOR_WAD,
58
+ }),
59
+ ],
60
+ });
61
+
62
+ const flow = builder.build();
63
+ const request = sdk.request(flow, {
64
+ signer,
65
+ inputs: {},
66
+ simulationPolicy: 'allow-revert',
67
+ });
68
+
69
+ return { flow, request };
70
+ };
@@ -0,0 +1,200 @@
1
+ import type { ComposeCompileRequest, Flow } from '@lifi/compose-spec';
2
+
3
+ import { createComposeSdk, materialisers, resources } from '../../index.js';
4
+ import type { Address } from '../../types.js';
5
+ import {
6
+ padForAaveDebtRounding,
7
+ trimForAaveWithdrawalRounding,
8
+ } from '../aaveRounding.js';
9
+ import { API_KEY, BASE_URL } from '../config.js';
10
+
11
+ // Base mainnet token addresses.
12
+ const BASE_WETH = '0x4200000000000000000000000000000000000006';
13
+ const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
14
+
15
+ // Aave V3 on Base (pool + aWETH receipt + variable-debt USDC).
16
+ const AAVE_V3_POOL_BASE = '0xA238Dd80C259a72e81d7e4664a9801593F98d1c5';
17
+ const A_BAS_WETH = '0xD4a0e0b9149BCee3C920d2E00b5dE09138fd8bb7';
18
+ const VDEBT_BAS_USDC = '0x59dca05b6c26dbd64b5381374aAaC5CD05644C28';
19
+
20
+ // Morpho Blue WETH/USDC market on Base (same parameters as the
21
+ // `morphoBlueBorrow` / `morphoBlueRepay` examples).
22
+ const ADAPTIVE_CURVE_IRM_BASE = '0x46415998764C29aB2a25CbeA6254146D50D22687';
23
+ const WETH_USDC_ORACLE = '0xFEa2D58cEfCb9fcb597723c6bAE66fFE4193aFE4';
24
+ const WETH_USDC_LLTV = '860000000000000000';
25
+
26
+ const MORPHO_WETH_USDC_MARKET = {
27
+ loanToken: BASE_USDC,
28
+ collateralToken: BASE_WETH,
29
+ oracle: WETH_USDC_ORACLE,
30
+ irm: ADAPTIVE_CURVE_IRM_BASE,
31
+ lltv: WETH_USDC_LLTV,
32
+ };
33
+
34
+ export interface AaveToMorphoDebtMigrationInput {
35
+ readonly owner: Address;
36
+ /** WETH collateral the user posts (in smallest units). */
37
+ readonly collateralAmount: `${bigint}`;
38
+ /** USDC principal borrowed from Aave (in smallest units). */
39
+ readonly debtAmount: `${bigint}`;
40
+ /**
41
+ * Aave-V3 flashloan fee on `debtAmount` — equals
42
+ * `computeDefaultFee('aave-v3', debtAmount)` (5 bps of the principal).
43
+ */
44
+ readonly debtFlashloanFee: `${bigint}`;
45
+ }
46
+
47
+ /**
48
+ * Atomically provision an Aave V3 borrow position on Base and migrate it to
49
+ * a Morpho Blue WETH/USDC market — all in a single compose flow driven by
50
+ * two concurrent flashloans.
51
+ *
52
+ * Phase 1 — provision the source position on Aave V3:
53
+ * - User direct-deposits WETH.
54
+ * - `lifi.zap` supplies the WETH to Aave (WETH → aBasWETH routing edge).
55
+ * - `aave.borrow` mints USDC debt; the borrowed USDC stays on the proxy
56
+ * and is swept back to the signer as the user's loan proceeds.
57
+ *
58
+ * Phase 2 — migrate the position to Morpho using two concurrent flashloans:
59
+ * - Flashloan #1 (Aave V3, USDC) bridges the Aave debt payoff before the
60
+ * Morpho borrow exists.
61
+ * - Flashloan #2 (Balancer V2, WETH) bridges the Morpho collateral supply
62
+ * before the Aave collateral is freed.
63
+ * - `aave.repay` clears the Aave USDC debt with flashloan #1.
64
+ * - `lifi.zap` withdraws the freed WETH from Aave (aBasWETH → WETH).
65
+ * - `morphoBlue.supplyCollateral` deposits flashloan #2's WETH into Morpho.
66
+ * - `morphoBlue.borrow` mints exactly `debtAmount + debtFlashloanFee` USDC
67
+ * so the `borrowed` resource settles flashloan #1 with zero residual.
68
+ * - Two `lifi.flashloanRepay` ops settle each leg: the USDC leg from the
69
+ * Morpho borrow, the WETH leg from the Aave withdrawal (Balancer V2
70
+ * charges no fee, so the principal alone covers it).
71
+ *
72
+ * After execution the signer holds `debtAmount` USDC and an open Morpho
73
+ * Blue position (`collateralAmount` WETH collateral, `debtAmount +
74
+ * debtFlashloanFee` USDC debt). The Aave position is closed.
75
+ */
76
+ export const buildAaveToMorphoDebtMigration = ({
77
+ owner,
78
+ collateralAmount,
79
+ debtAmount,
80
+ debtFlashloanFee,
81
+ }: AaveToMorphoDebtMigrationInput): {
82
+ flow: Flow;
83
+ request: ComposeCompileRequest;
84
+ } => {
85
+ const sdk = createComposeSdk({ baseUrl: BASE_URL, apiKey: API_KEY });
86
+
87
+ // Both flashloan legs absorb Aave's 1-wei scaled-balance skew: the USDC
88
+ // leg funds a max-mode repay, the WETH leg is covered by a withdrawal.
89
+ const debtFlashloanAmount = padForAaveDebtRounding(debtAmount);
90
+ const collateralFlashloanAmount =
91
+ trimForAaveWithdrawalRounding(collateralAmount);
92
+
93
+ // Morpho borrow must equal principal + Aave-V3 flashloan fee so the
94
+ // `borrowed` resource exactly settles the USDC flashloan leg.
95
+ const morphoBorrowAmount = (
96
+ BigInt(debtFlashloanAmount) + BigInt(debtFlashloanFee)
97
+ ).toString() as `${bigint}`;
98
+
99
+ const builder = sdk.flow(8453, {
100
+ name: 'aave-to-morpho-debt-migration',
101
+ inputs: {
102
+ initialCollateral: resources.erc20(BASE_WETH, 8453),
103
+ debtFlashloan: resources.erc20(BASE_USDC, 8453),
104
+ collateralFlashloan: resources.erc20(BASE_WETH, 8453),
105
+ },
106
+ });
107
+
108
+ // --- Phase 1: provision the Aave V3 borrow position ----------------------
109
+
110
+ // WETH → aBasWETH via the aave routing edge family (Aave V3 supply).
111
+ const supplyToAave = builder.lifi.zap('supply-to-aave', {
112
+ bind: { amountIn: builder.inputs.initialCollateral },
113
+ config: { resourceOut: resources.erc20(A_BAS_WETH, 8453) },
114
+ });
115
+
116
+ // Borrow USDC against the freshly supplied collateral. The `borrowed`
117
+ // resource is left unbound; request-level `sweepTo` forwards it to the
118
+ // signer as the user's loan proceeds.
119
+ builder.aave.borrow('borrow-from-aave', {
120
+ bind: {},
121
+ config: {
122
+ pool: AAVE_V3_POOL_BASE,
123
+ asset: BASE_USDC,
124
+ variableDebtToken: VDEBT_BAS_USDC,
125
+ amount: debtAmount,
126
+ },
127
+ });
128
+
129
+ // --- Phase 2: migrate to Morpho with two concurrent flashloans -----------
130
+
131
+ // Settle the Aave USDC debt with flashloan #1. mode: 'max' makes Aave's
132
+ // Pool clamp paybackAmount to userVariableDebt exactly, so any unspent
133
+ // flashloan principal flows through the op's residual port (swept by the
134
+ // request-level sweepTo).
135
+ builder.aave.repay('repay-aave', {
136
+ bind: {
137
+ assetIn: builder.inputs.debtFlashloan,
138
+ onBehalfOf: builder.context.executionAddress,
139
+ },
140
+ config: { pool: AAVE_V3_POOL_BASE, mode: 'max' },
141
+ });
142
+
143
+ // Withdraw the freed WETH from Aave (aBasWETH → WETH) via routing.
144
+ const withdrawFromAave = builder.lifi.zap('withdraw-from-aave', {
145
+ bind: { amountIn: supplyToAave.amountOut },
146
+ config: { resourceOut: resources.erc20(BASE_WETH, 8453) },
147
+ });
148
+
149
+ // Open the Morpho Blue position with flashloan #2's WETH.
150
+ builder.morphoBlue.supplyCollateral('supply-to-morpho', {
151
+ bind: { assetIn: builder.inputs.collateralFlashloan },
152
+ config: { marketParams: MORPHO_WETH_USDC_MARKET, mode: 'exact' },
153
+ });
154
+
155
+ // Borrow exactly principal + fee from Morpho to settle the USDC leg.
156
+ const morphoBorrow = builder.morphoBlue.borrow('borrow-from-morpho', {
157
+ bind: {},
158
+ config: {
159
+ marketParams: MORPHO_WETH_USDC_MARKET,
160
+ amount: morphoBorrowAmount,
161
+ },
162
+ });
163
+
164
+ // Settle the USDC flashloan leg with the Morpho borrow.
165
+ builder.lifi.flashloanRepay('repay-debt-flashloan', {
166
+ bind: { funds: morphoBorrow.borrowed },
167
+ config: { leg: 'debtFlashloan' },
168
+ });
169
+
170
+ // Settle the WETH flashloan leg with the Aave withdrawal. Balancer V2
171
+ // charges no fee, so the withdrawn principal alone covers the leg.
172
+ builder.lifi.flashloanRepay('repay-collateral-flashloan', {
173
+ bind: { funds: withdrawFromAave.amountOut },
174
+ config: { leg: 'collateralFlashloan' },
175
+ });
176
+
177
+ const flow = builder.build();
178
+
179
+ const request = sdk.request(flow, {
180
+ signer: owner,
181
+ inputs: {
182
+ initialCollateral: materialisers.directDeposit({
183
+ amount: collateralAmount,
184
+ }),
185
+ debtFlashloan: materialisers.flashloan({
186
+ providerKind: 'aave-v3',
187
+ amount: debtFlashloanAmount,
188
+ }),
189
+ collateralFlashloan: materialisers.flashloan({
190
+ providerKind: 'balancer-v2',
191
+ amount: collateralFlashloanAmount,
192
+ }),
193
+ },
194
+ // Sweep the Aave borrow proceeds (and any aave.repay residual) to the
195
+ // signer.
196
+ sweepTo: builder.context.sender,
197
+ });
198
+
199
+ return { flow, request };
200
+ };