# Loop a position for leverage

> Buy a Pendle PT, post it on Morpho Blue, borrow and buy again up to a target leverage, simulated as one transaction.

- Status: live. Compiles on Composer today.
- Who it's for: Yield and trading apps that offer leverage
- Page: https://composer-experiences.li.quest/templates/leverage-loop
- Working example, run with your own key and wallet: https://composer-experiences.li.quest/templates/leverage-loop/live

## What you get

- A target leverage in one transaction
- The simulation measures the leverage you actually get
- No flash loan needed

## What runs, in order

A step without ops is work outside the flow, such as the user paying in. `×n` marks an op the flow repeats.

1. User pays (Ethereum): reUSDe
2. Buy the PT (Ethereum): Royco deposit, wrap to SY, Pendle swap. Ops: `core.call ×n`, `core.staticCall ×n`, `core.invoke ×n`, `core.asResource ×n`, `core.balanceOf ×n`
3. Supply as collateral (Ethereum): Morpho Blue. Ops: `morphoBlue.supplyCollateral ×n`
4. Borrow USDC (Ethereum): Repeated to the target. Ops: `morphoBlue.borrow ×n`
5. Swap USDC to reUSDe (Ethereum): Feeds the next leg. Ops: `lifi.swap ×n`

## What you control

| Parameter | Set by |
| --- | --- |
| Market | Fixed by you |
| Target leverage | Passed by your user |
| Loop legs | Planned for you |

## Build it

1. Get an API key at https://portal.li.fi. Keep it on your server.
2. Install these exact versions; npm's `latest` tag lags production:

```sh
npm install @lifi/composer-sdk@0.16.0 @lifi/compose-spec@0.16.0
```

3. Add the module below as `leverage-loop.ts`. It names the flow `tpl:leverage-loop@1`, so LI.FI can see which template it came from.
4. Compile with `simulationPolicy: 'allow-revert'`. Before the user signs, show `outputs[<key>].amount.minimum.value`: the least they receive. It is optional; when it is absent, the flow has no floor.

### The module: `leverage-loop.ts`

```ts
/**
 * Loop a Pendle PT position on Morpho Blue for leverage, in one transaction on
 * Ethereum. Each leg deposits reUSDe into Royco's senior tranche, wraps it into
 * Pendle SY, buys PT and supplies the PT as Morpho collateral; each later leg
 * first borrows USDC against the collateral so far and swaps it to reUSDe. The
 * position belongs to the user's Composer proxy. Call it with
 * `const { flow, run } = buildFlow(sdk, inputs); const result = await flow.compile(run);`.
 */
import type { Ref } from '@lifi/compose-spec';
import {
  type Address,
  type ComposeSdk,
  guards,
  materialisers,
  raw,
  resources,
} from '@lifi/composer-sdk';

const REUSDE = resources.erc20('0xdDC0f880ff6e4e22E4B74632fBb43Ce4DF6cCC5a', 1);
const PENDLE_ROUTER = '0x888888888889758F76e7103c6CbF23ABbF58F946';
// Pendle's default PT search (whole range, 256 steps) and an empty limit order.
const GUESS_PT = [0, `0x${'f'.repeat(64)}`, 0, 256, 1e14];
const NO_LIMIT = [`0x${'0'.repeat(40)}`, 0, [], [], '0x'];
const FILL = `((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)`;
const SIG = {
  request:
    'requestDeposit(address tranche, uint256 assets, address receiver, uint64 executorBonusWAD)',
  nonce: 'getLastRequestNonce() view returns (uint256)',
  execute:
    'executeDeposit(address user, uint256 requestNonce, uint256 assetsToDeposit) returns (uint256)',
  wrap: 'deposit(address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut) returns (uint256)',
  buyPt: `swapExactSyForPt(address receiver, address market, uint256 exactSyIn, uint256 minPtOut, (uint256,uint256,uint256,uint256,uint256) guessPtOut, (address,uint256,${FILL}[],${FILL}[],bytes) limit)`,
};

export interface LeverageLoopInputs {
  user: Address;
  /** reUSDe the user deposits, 18 decimals. */
  deposit: bigint;
  /** One USDC borrow per extra leg, sized off-chain to the leverage target. */
  borrows: bigint[];
  royco: { entryPoint: Address; seniorTranche: Address };
  pendle: { sy: Address; market: Address; pt: Address };
  /** The Morpho Blue market lending USDC against the PT; `lltv` in WAD. */
  morpho: { loanToken: Address; oracle: Address; irm: Address; lltv: bigint };
  slippageBps: number;
}

export const buildFlow = (
  sdk: ComposeSdk,
  inputs: LeverageLoopInputs,
  name = 'tpl:leverage-loop@1'
) => {
  const { royco, pendle, morpho, slippageBps: bps } = inputs;
  const { entryPoint: entry, seniorTranche: tranche } = royco;
  const lltv = `${morpho.lltv}`;
  const marketParams = { ...morpho, collateralToken: pendle.pt, lltv };
  const flow = sdk.flow(1, { name, inputs: { reUsde: REUSDE } });
  const me: Ref = { $ref: 'context.executionAddress' };
  const ref = (path: string): Ref => ({ $ref: path });
  // A contract call; one that spends `input` approves `to` for it first.
  const call = (
    id: string,
    to: Address,
    sig: string,
    args: unknown[],
    input?: Ref
  ) =>
    flow.untypedOp(id, input ? 'core.call' : 'core.invoke', {
      bind: input ? { input } : {},
      config: {
        target: to,
        functionSignature: `function ${sig}`,
        args,
        ...(input && { approvals: [{ spender: to }] }),
      },
    });
  // Track a call's uint256 result as an amount of `token` the next call can spend.
  const asToken = (id: string, from: string, token: Address): Ref => {
    const handle = raw.ref<'uint256'>(`${from}.result`);
    flow.core.asResource(id, {
      bind: { handle },
      config: { resource: resources.erc20(token, 1) },
    });
    return ref(`${id}.resource`);
  };

  // reUSDe ─► Royco senior tranche ─► Pendle SY ─► PT ─► Morpho collateral.
  const leg = (n: number, reUsde: Ref) => {
    const id = (node: string) => `${node}-${n}`;
    call(id('request'), entry, SIG.request, [tranche, reUsde, me, 0], reUsde);
    flow.core.staticCall(id('nonce'), {
      bind: {},
      config: { target: entry, functionSignature: `function ${SIG.nonce}` },
    });
    const nonce = ref(`${id('nonce')}.result`);
    call(id('execute'), entry, SIG.execute, [me, nonce, reUsde]);
    const sr = asToken(id('sr'), id('execute'), tranche);
    call(id('wrap'), pendle.sy, SIG.wrap, [me, tranche, sr, 0], sr);
    const sy = asToken(id('sy'), id('wrap'), pendle.sy);
    const buy = [me, pendle.market, sy, 0, GUESS_PT, NO_LIMIT];
    call(id('buy-pt'), PENDLE_ROUTER, SIG.buyPt, buy, sy);
    // The PT bought, floored against its simulated amount, becomes collateral.
    const pt = flow.core.balanceOf(id('pt'), {
      bind: {},
      config: { token: pendle.pt },
      guards: [guards.slippage({ port: 'balance', bps })],
    });
    flow.morphoBlue.supplyCollateral(id('supply'), {
      bind: { assetIn: pt.balance },
      config: { marketParams, mode: 'exact' },
    });
  };

  leg(0, { $ref: 'input.reUsde' });
  inputs.borrows.forEach((amount, i) => {
    const { borrowed } = flow.morphoBlue.borrow(`borrow-${i + 1}`, {
      bind: {},
      config: { marketParams, amount: `${amount}` },
    });
    flow.lifi.swap(`swap-${i + 1}`, {
      bind: { amountIn: borrowed },
      config: { resourceOut: REUSDE, slippage: bps / 10_000 },
    });
    leg(i + 1, ref(`swap-${i + 1}.amountOut`));
  });

  const run = {
    signer: inputs.user,
    inputs: { reUsde: materialisers.directDeposit({ amount: inputs.deposit }) },
    sweepTo: inputs.user,
    // Collateral is unpriced, so the price-impact check would read it as lost.
    maxPriceImpactBps: 0,
  };
  return { flow, run };
};
```

### Call it

```ts
import { createComposeSdk } from '@lifi/composer-sdk';

import { buildFlow } from './leverage-loop';

const sdk = createComposeSdk({
  baseUrl: 'https://composer.li.quest',
  apiKey: process.env.LIFI_API_KEY!,
});

// inputs: the values your user picks; see the module's inputs interface.
const { flow, run } = buildFlow(sdk, inputs);
const result = await flow.compile({ ...run, simulationPolicy: 'allow-revert' });
// Show the outputs' amount.minimum to the user, then have them sign
// result.transaction.
```

### The same call over REST

Compile and simulate in one call, for sample values:

```http
POST https://composer.li.quest/compose
content-type: application/json
x-lifi-api-key: <your key>

{
  "flow": {
    "version": 1,
    "id": "tpl:leverage-loop@1",
    "chainId": 1,
    "inputs": [
      {
        "name": "reUsde",
        "resource": {
          "kind": "erc20",
          "token": "0xdDC0f880ff6e4e22E4B74632fBb43Ce4DF6cCC5a",
          "chainId": 1
        }
      }
    ],
    "nodes": [
      {
        "id": "request-0",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "input.reUsde"
          }
        },
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function requestDeposit(address tranche, uint256 assets, address receiver, uint64 executorBonusWAD)",
          "args": [
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "input.reUsde"
            },
            {
              "$ref": "context.executionAddress"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xaF55a0c251690d9322b5F94b7e50EE895750262c"
            }
          ]
        }
      },
      {
        "id": "nonce-0",
        "op": "core.staticCall",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function getLastRequestNonce() view returns (uint256)",
          "args": []
        }
      },
      {
        "id": "execute-0",
        "op": "core.invoke",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function executeDeposit(address user, uint256 requestNonce, uint256 assetsToDeposit) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            {
              "$ref": "nonce-0.result"
            },
            {
              "$ref": "input.reUsde"
            }
          ]
        }
      },
      {
        "id": "sr-0",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "execute-0.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            "chainId": 1
          }
        }
      },
      {
        "id": "wrap-0",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sr-0.resource"
          }
        },
        "config": {
          "target": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
          "functionSignature": "function deposit(address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "sr-0.resource"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807"
            }
          ]
        }
      },
      {
        "id": "sy-0",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "wrap-0.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
            "chainId": 1
          }
        }
      },
      {
        "id": "buy-pt-0",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sy-0.resource"
          }
        },
        "config": {
          "target": "0x888888888889758F76e7103c6CbF23ABbF58F946",
          "functionSignature": "function swapExactSyForPt(address receiver, address market, uint256 exactSyIn, uint256 minPtOut, (uint256,uint256,uint256,uint256,uint256) guessPtOut, (address,uint256,((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],bytes) limit)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x3876192EFdcD96850eaA1207bB33d3782C9132EA",
            {
              "$ref": "sy-0.resource"
            },
            0,
            [
              0,
              "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
              0,
              256,
              100000000000000
            ],
            [
              "0x0000000000000000000000000000000000000000",
              0,
              [],
              [],
              "0x"
            ]
          ],
          "approvals": [
            {
              "spender": "0x888888888889758F76e7103c6CbF23ABbF58F946"
            }
          ]
        }
      },
      {
        "id": "pt-0",
        "op": "core.balanceOf",
        "bind": {},
        "config": {
          "token": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
        },
        "guards": [
          {
            "kind": "slippage",
            "port": "balance",
            "bps": 100
          }
        ]
      },
      {
        "id": "supply-0",
        "op": "morphoBlue.supplyCollateral",
        "bind": {
          "assetIn": {
            "$ref": "pt-0.balance"
          }
        },
        "config": {
          "marketParams": {
            "loanToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "oracle": "0x4E5dB0BE0590Ce0B642964A3F79C240e4F08B50e",
            "irm": "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
            "lltv": "915000000000000000",
            "collateralToken": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
          },
          "mode": "exact"
        }
      },
      {
        "id": "borrow-1",
        "op": "morphoBlue.borrow",
        "bind": {},
        "config": {
          "marketParams": {
            "loanToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "oracle": "0x4E5dB0BE0590Ce0B642964A3F79C240e4F08B50e",
            "irm": "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
            "lltv": "915000000000000000",
            "collateralToken": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
          },
          "amount": "50000"
        }
      },
      {
        "id": "swap-1",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "borrow-1.borrowed"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0xdDC0f880ff6e4e22E4B74632fBb43Ce4DF6cCC5a",
            "chainId": 1
          },
          "slippage": 0.01
        }
      },
      {
        "id": "request-1",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "swap-1.amountOut"
          }
        },
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function requestDeposit(address tranche, uint256 assets, address receiver, uint64 executorBonusWAD)",
          "args": [
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "swap-1.amountOut"
            },
            {
              "$ref": "context.executionAddress"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xaF55a0c251690d9322b5F94b7e50EE895750262c"
            }
          ]
        }
      },
      {
        "id": "nonce-1",
        "op": "core.staticCall",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function getLastRequestNonce() view returns (uint256)",
          "args": []
        }
      },
      {
        "id": "execute-1",
        "op": "core.invoke",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function executeDeposit(address user, uint256 requestNonce, uint256 assetsToDeposit) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            {
              "$ref": "nonce-1.result"
            },
            {
              "$ref": "swap-1.amountOut"
            }
          ]
        }
      },
      {
        "id": "sr-1",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "execute-1.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            "chainId": 1
          }
        }
      },
      {
        "id": "wrap-1",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sr-1.resource"
          }
        },
        "config": {
          "target": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
          "functionSignature": "function deposit(address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "sr-1.resource"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807"
            }
          ]
        }
      },
      {
        "id": "sy-1",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "wrap-1.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
            "chainId": 1
          }
        }
      },
      {
        "id": "buy-pt-1",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sy-1.resource"
          }
        },
        "config": {
          "target": "0x888888888889758F76e7103c6CbF23ABbF58F946",
          "functionSignature": "function swapExactSyForPt(address receiver, address market, uint256 exactSyIn, uint256 minPtOut, (uint256,uint256,uint256,uint256,uint256) guessPtOut, (address,uint256,((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],bytes) limit)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x3876192EFdcD96850eaA1207bB33d3782C9132EA",
            {
              "$ref": "sy-1.resource"
            },
            0,
            [
              0,
              "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
              0,
              256,
              100000000000000
            ],
            [
              "0x0000000000000000000000000000000000000000",
              0,
              [],
              [],
              "0x"
            ]
          ],
          "approvals": [
            {
              "spender": "0x888888888889758F76e7103c6CbF23ABbF58F946"
            }
          ]
        }
      },
      {
        "id": "pt-1",
        "op": "core.balanceOf",
        "bind": {},
        "config": {
          "token": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
        },
        "guards": [
          {
            "kind": "slippage",
            "port": "balance",
            "bps": 100
          }
        ]
      },
      {
        "id": "supply-1",
        "op": "morphoBlue.supplyCollateral",
        "bind": {
          "assetIn": {
            "$ref": "pt-1.balance"
          }
        },
        "config": {
          "marketParams": {
            "loanToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "oracle": "0x4E5dB0BE0590Ce0B642964A3F79C240e4F08B50e",
            "irm": "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
            "lltv": "915000000000000000",
            "collateralToken": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
          },
          "mode": "exact"
        }
      },
      {
        "id": "borrow-2",
        "op": "morphoBlue.borrow",
        "bind": {},
        "config": {
          "marketParams": {
            "loanToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "oracle": "0x4E5dB0BE0590Ce0B642964A3F79C240e4F08B50e",
            "irm": "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
            "lltv": "915000000000000000",
            "collateralToken": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
          },
          "amount": "30000"
        }
      },
      {
        "id": "swap-2",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "borrow-2.borrowed"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0xdDC0f880ff6e4e22E4B74632fBb43Ce4DF6cCC5a",
            "chainId": 1
          },
          "slippage": 0.01
        }
      },
      {
        "id": "request-2",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "swap-2.amountOut"
          }
        },
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function requestDeposit(address tranche, uint256 assets, address receiver, uint64 executorBonusWAD)",
          "args": [
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "swap-2.amountOut"
            },
            {
              "$ref": "context.executionAddress"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xaF55a0c251690d9322b5F94b7e50EE895750262c"
            }
          ]
        }
      },
      {
        "id": "nonce-2",
        "op": "core.staticCall",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function getLastRequestNonce() view returns (uint256)",
          "args": []
        }
      },
      {
        "id": "execute-2",
        "op": "core.invoke",
        "bind": {},
        "config": {
          "target": "0xaF55a0c251690d9322b5F94b7e50EE895750262c",
          "functionSignature": "function executeDeposit(address user, uint256 requestNonce, uint256 assetsToDeposit) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            {
              "$ref": "nonce-2.result"
            },
            {
              "$ref": "swap-2.amountOut"
            }
          ]
        }
      },
      {
        "id": "sr-2",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "execute-2.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            "chainId": 1
          }
        }
      },
      {
        "id": "wrap-2",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sr-2.resource"
          }
        },
        "config": {
          "target": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
          "functionSignature": "function deposit(address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut) returns (uint256)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x87A9CC8ee891a501868F323480F93dC4259647F8",
            {
              "$ref": "sr-2.resource"
            },
            0
          ],
          "approvals": [
            {
              "spender": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807"
            }
          ]
        }
      },
      {
        "id": "sy-2",
        "op": "core.asResource",
        "bind": {
          "handle": {
            "$ref": "wrap-2.result"
          }
        },
        "config": {
          "resource": {
            "kind": "erc20",
            "token": "0xa26b9621Fb842D7e19c1c46dB79706B85f174807",
            "chainId": 1
          }
        }
      },
      {
        "id": "buy-pt-2",
        "op": "core.call",
        "bind": {
          "input": {
            "$ref": "sy-2.resource"
          }
        },
        "config": {
          "target": "0x888888888889758F76e7103c6CbF23ABbF58F946",
          "functionSignature": "function swapExactSyForPt(address receiver, address market, uint256 exactSyIn, uint256 minPtOut, (uint256,uint256,uint256,uint256,uint256) guessPtOut, (address,uint256,((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],((uint256,uint256,uint256,uint8,address,address,address,address,uint256,uint256,uint256,bytes),bytes,uint256)[],bytes) limit)",
          "args": [
            {
              "$ref": "context.executionAddress"
            },
            "0x3876192EFdcD96850eaA1207bB33d3782C9132EA",
            {
              "$ref": "sy-2.resource"
            },
            0,
            [
              0,
              "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
              0,
              256,
              100000000000000
            ],
            [
              "0x0000000000000000000000000000000000000000",
              0,
              [],
              [],
              "0x"
            ]
          ],
          "approvals": [
            {
              "spender": "0x888888888889758F76e7103c6CbF23ABbF58F946"
            }
          ]
        }
      },
      {
        "id": "pt-2",
        "op": "core.balanceOf",
        "bind": {},
        "config": {
          "token": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
        },
        "guards": [
          {
            "kind": "slippage",
            "port": "balance",
            "bps": 100
          }
        ]
      },
      {
        "id": "supply-2",
        "op": "morphoBlue.supplyCollateral",
        "bind": {
          "assetIn": {
            "$ref": "pt-2.balance"
          }
        },
        "config": {
          "marketParams": {
            "loanToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
            "oracle": "0x4E5dB0BE0590Ce0B642964A3F79C240e4F08B50e",
            "irm": "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
            "lltv": "915000000000000000",
            "collateralToken": "0x3E0B7eD61d41f2cBeC58b98A960d0E8388C7Bd85"
          },
          "mode": "exact"
        }
      }
    ]
  },
  "run": {
    "inputs": {
      "reUsde": {
        "kind": "directDeposit",
        "amount": "100000000000000000"
      }
    },
    "signer": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    "maxPriceImpactBps": 0,
    "sweepTo": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
  }
}
```

### Prompt for a coding agent

```text
Goal: add "Loop a position for leverage" to my app with LI.FI Composer.
1. Install exactly: npm install @lifi/composer-sdk@0.16.0 @lifi/compose-spec@0.16.0
2. Read https://composer.li.quest/llms.txt. The manifest at https://composer.li.quest/compose/manifest is the source of truth for operations.
3. The flow: User pays → Buy the PT (core.call ×n, core.staticCall ×n, core.invoke ×n, core.asResource ×n, core.balanceOf ×n) → Supply as collateral (morphoBlue.supplyCollateral ×n) → Borrow USDC (morphoBlue.borrow ×n) → Swap USDC to reUSDe (lifi.swap ×n).
   What can change: Market, Target leverage, Loop legs.
4. Name the flow "tpl:leverage-loop@1" so LI.FI can see which template it came from.
5. Compile with POST /compose and simulationPolicy: 'allow-revert'.
   Before the user signs, show outputs[<key>].amount.minimum.value: the least they receive.
   It is optional; when it is absent, the flow has no floor.
6. The API key comes from https://portal.li.fi. Keep it on the server.
7. If you get stuck, POST https://composer.li.quest/feedback with what you tried.
```

## Composer references

- [Composer API llms.txt](https://composer.li.quest/llms.txt)
- [Operation manifest](https://composer.li.quest/compose/manifest): the source of truth for operations
- [Docs](https://docs.li.fi/composer/overview.md)
- Stuck? `POST https://composer.li.quest/feedback` with what you tried; it needs no key.
