Build: loop a position for leverage

Three steps from here to your app. Run it from your backend, your frontend or your agent.

1

Get your API key

Create a key on the LI.FI portal. It ties usage and your fees to your app.

Get API key ↗
2

Add the flow

Install
npm install @lifi/composer-sdk@0.16.0 @lifi/compose-spec@0.16.0
leverage-loop.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
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 full working module, not an excerpt. It names the flow tpl:leverage-loop@1 so LI.FI can see which template it came from.

3

Choose what you control

Fix these once, or pass them in from your user on every call.

MarketFixed by you
Target leveragePassed by your user
Loop legsPlanned for you

Before you go live

Need it changed?

A protocol we don't cover yet, custom logic, or a launch with a partner. We build these with you.

Talk to the team