# Pay an invoice from any chain

> Pay a Request Network invoice in the exact currency it asks for, from another token or another chain.

- Status: live. Compiles on Composer today.
- Who it's for: Payment and invoicing apps
- Page: https://composer-experiences.li.quest/templates/invoice-payment
- Working example, run with your own key and wallet: https://composer-experiences.li.quest/templates/invoice-payment/live

## What you get

- The invoice is paid in the exact currency it asks for
- The payer pays once, from the chain they are on

## 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. Payer pays (Arbitrum): USDC
2. Exact amount delivered (Arbitrum to Base). Ops: `lifiIntents.order`
3. Held in escrow (Base): Refunds the payer if no solver fills it. Ops: `continuation.settle`
4. Invoice paid (Base): Request Network detects it. Ops: `core.call`

## What you control

| Parameter | Set by |
| --- | --- |
| Invoice | Passed by your app |
| Pay with | Passed by the payer |

## 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 `invoice-payment.ts`. It names the flow `tpl:invoice-payment@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: `invoice-payment.ts`

```ts
/**
 * Pay a Request Network invoice in USDC on Base from USDC on another chain,
 * with one signature. A LI.FI Intents order delivers exactly the invoice total
 * into an escrow on Base, and a solver pays it through Request's fee proxy;
 * unspent USDC returns to the payer, and an unfilled escrow refunds them.
 *
 *   const { flow, run } = buildFlow(sdk, inputs);
 *   const result = await flow.compile(run);
 */
import {
  type Address,
  type ComposeRunInput,
  type ComposeSdk,
  materialisers,
  raw,
  resources,
} from '@lifi/composer-sdk';

const BASE = 8453;
const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
// Request Network's ERC20FeeProxy on Base: its event marks the invoice paid.
const FEE_PROXY = '0x1892196E80C4c17ea5100Da765Ab48c1fE2Fb814';

export interface InvoicePaymentInputs {
  sourceChainId: number;
  sourceUsdc: Address;
  /** USDC the payer deposits; must cover what the solver asks for the total. */
  amountIn: bigint;
  payer: Address;
  /** The invoice terms, in USDC base units on Base. */
  invoice: {
    payee: Address;
    amount: bigint;
    fee: bigint;
    feeAddress: Address;
    paymentReference: `0x${string}`;
  };
}

export const buildFlow = (
  sdk: ComposeSdk,
  inputs: InvoicePaymentInputs,
  name = 'tpl:invoice-payment@1'
) => {
  const { invoice, payer, sourceChainId, sourceUsdc, amountIn } = inputs;
  const baseUsdc = resources.erc20(BASE_USDC, BASE);
  const total = `${invoice.amount + invoice.fee}`;

  // The leg a solver runs on Base: `exact` binds the escrow to this one call.
  const leg = sdk.flow(BASE, {
    name: `${name}:pay`,
    inputs: { funding: baseUsdc },
  });
  leg.core.call('pay', {
    resource: leg.inputs.funding,
    bind: {
      tokenAddress: raw.literal('address', BASE_USDC),
      to: raw.literal('address', invoice.payee),
      amount: raw.literal('uint256', `${invoice.amount}`),
      paymentReference: raw.literal('bytes', invoice.paymentReference),
      feeAmount: raw.literal('uint256', `${invoice.fee}`),
      feeAddress: raw.literal('address', invoice.feeAddress),
    },
    config: {
      target: FEE_PROXY,
      functionSignature:
        'function transferFromWithReferenceAndFee(address tokenAddress, address to, uint256 amount, bytes paymentReference, uint256 feeAmount, address feeAddress)',
      approvals: [{ spender: FEE_PROXY }],
    },
  });

  const flow = sdk.flow(sourceChainId, {
    name,
    inputs: { usdc: resources.erc20(sourceUsdc, sourceChainId) },
  });
  // No `destination`: the solver delivers exactly the total into the escrow.
  const order = flow.lifiIntents.order('order', {
    bind: { amountIn: flow.inputs.usdc },
    config: { resourceOut: baseUsdc, exactAmountOut: total },
  });
  flow.continuation.settle('settle', {
    bind: { input: order.amountOut },
    config: {
      provider: 'intent-factory',
      exact: true,
      outcomes: [],
      refund: payer,
      validity: { expiresAtMs: Date.now() + 60 * 60 * 1000 },
      continuationFlow: leg.build(),
    },
  });

  const run = {
    signer: payer,
    inputs: { usdc: materialisers.directDeposit({ amount: amountIn }) },
    // Unspent USDC returns to the payer. The payment leaves the flow, which
    // the price-impact gate would count as a loss.
    sweepTo: payer,
    maxPriceImpactBps: 0,
  } satisfies ComposeRunInput;
  return { flow, run };
};
```

### Call it

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

import { buildFlow } from './invoice-payment';

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:invoice-payment@1",
    "chainId": 42161,
    "inputs": [
      {
        "name": "usdc",
        "resource": {
          "kind": "erc20",
          "token": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
          "chainId": 42161
        }
      }
    ],
    "nodes": [
      {
        "id": "order",
        "op": "lifiIntents.order",
        "bind": {
          "amountIn": {
            "$ref": "input.usdc"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "chainId": 8453
          },
          "exactAmountOut": "100000000"
        }
      },
      {
        "id": "settle",
        "op": "continuation.settle",
        "bind": {
          "input": {
            "$ref": "order.amountOut"
          }
        },
        "config": {
          "provider": "intent-factory",
          "exact": true,
          "outcomes": [],
          "refund": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
          "validity": {
            "expiresAtMs": 1794933828252
          },
          "continuationFlow": {
            "version": 1,
            "id": "tpl:invoice-payment@1:pay",
            "chainId": 8453,
            "inputs": [
              {
                "name": "funding",
                "resource": {
                  "kind": "erc20",
                  "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
                  "chainId": 8453
                }
              }
            ],
            "nodes": [
              {
                "id": "pay",
                "op": "core.call",
                "bind": {
                  "input": {
                    "$ref": "input.funding"
                  }
                },
                "config": {
                  "target": "0x1892196E80C4c17ea5100Da765Ab48c1fE2Fb814",
                  "functionSignature": "function transferFromWithReferenceAndFee(address tokenAddress, address to, uint256 amount, bytes paymentReference, uint256 feeAmount, address feeAddress)",
                  "approvals": [
                    {
                      "spender": "0x1892196E80C4c17ea5100Da765Ab48c1fE2Fb814"
                    }
                  ],
                  "args": [
                    "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
                    "0xb5c9a1d7e3f4628d0e7a9b1c2d3e4f5a6b7c8d9e",
                    "99500000",
                    "0x8c6f1d3b4a5e7c21",
                    "500000",
                    "0x86DBd094BC7436BD106C53a6a137Ab0Ab810A6A9"
                  ]
                }
              }
            ]
          }
        }
      }
    ]
  },
  "run": {
    "inputs": {
      "usdc": {
        "kind": "directDeposit",
        "amount": "105000000"
      }
    },
    "signer": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    "maxPriceImpactBps": 0,
    "sweepTo": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
  }
}
```

### Prompt for a coding agent

```text
Goal: add "Pay an invoice from any chain" 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: Payer pays → Exact amount delivered (lifiIntents.order) → Held in escrow (continuation.settle) → Invoice paid (core.call).
   What can change: Invoice, Pay with.
4. Name the flow "tpl:invoice-payment@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.
