# Sweep small balances into one token

> All the leftovers in a wallet become one useful balance in a single transaction.

- Status: live. Compiles on Composer today, and Jumper runs it in production.
- Who it's for: Wallets with a portfolio or settings screen
- Page: https://composer-experiences.li.quest/templates/dust-sweep
- Working example, run with your own key and wallet: https://composer-experiences.li.quest/templates/dust-sweep/live

## What you get

- Tokens worth too little to trade one by one become one balance
- One transaction, simulated first
- Runs on Jumper today

## 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. Small balances (Base): Several tokens
2. Swap each one (Base). Ops: `lifi.swap ×n`
3. One token to the user (Base): USDC

## What you control

| Parameter | Set by |
| --- | --- |
| Tokens to sweep | Picked by your user |
| Threshold | Below a value you set |
| Target token | USDC or ETH |
| Slippage | Up to 5% |

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

```ts
/**
 * Sweep several small balances into one token in one transaction: every token
 * is swapped to `tokenOut` and the total goes to the user. Call it with
 * `const { flow, run } = buildFlow(sdk, inputs); const result = await flow.compile(run);`.
 */
import {
  type Address,
  type ComposeSdk,
  materialisers,
  resources,
} from '@lifi/composer-sdk';

export interface DustSweepInputs {
  chainId: number;
  /** The balances to sweep; each amount is in that token's smallest unit. */
  tokens: { address: Address; amount: bigint }[];
  /** The one token the user ends up with, e.g. USDC. */
  tokenOut: Address;
  user: Address;
}

export const buildFlow = (
  sdk: ComposeSdk,
  inputs: DustSweepInputs,
  name = 'tpl:dust-sweep@1'
) => {
  const { chainId, tokens } = inputs;
  // One flow input per balance: `token0`, `token1`, …
  const flow = sdk.flow(chainId, {
    name,
    inputs: Object.fromEntries(
      tokens.map(({ address }, i) => [
        `token${i}`,
        resources.erc20(address, chainId),
      ])
    ),
  });

  // Swap every balance into the target token.
  tokens.forEach((_, i) => {
    flow.lifi.swap(`swap${i}`, {
      bind: { amountIn: flow.inputs[`token${i}`]! },
      config: {
        resourceOut: resources.erc20(inputs.tokenOut, chainId),
        slippage: 0.05,
      },
    });
  });

  // Each balance is deposited as is; the swapped total is swept to the user.
  const run = {
    signer: inputs.user,
    inputs: Object.fromEntries(
      tokens.map(({ amount }, i) => [
        `token${i}`,
        materialisers.directDeposit({ amount }),
      ])
    ),
    sweepTo: inputs.user,
  };
  return { flow, run };
};
```

### Call it

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

import { buildFlow } from './dust-sweep';

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:dust-sweep@1",
    "chainId": 8453,
    "inputs": [
      {
        "name": "token0",
        "resource": {
          "kind": "erc20",
          "token": "0x940181a94A35A4569E4529A3CDfB74e38FD98631",
          "chainId": 8453
        }
      },
      {
        "name": "token1",
        "resource": {
          "kind": "erc20",
          "token": "0x4ed4E862860beD51a9570b96d89aF5E1B0Efefed",
          "chainId": 8453
        }
      },
      {
        "name": "token2",
        "resource": {
          "kind": "erc20",
          "token": "0x4200000000000000000000000000000000000006",
          "chainId": 8453
        }
      }
    ],
    "nodes": [
      {
        "id": "swap0",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "input.token0"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "chainId": 8453
          },
          "slippage": 0.05
        }
      },
      {
        "id": "swap1",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "input.token1"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "chainId": 8453
          },
          "slippage": 0.05
        }
      },
      {
        "id": "swap2",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "input.token2"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "chainId": 8453
          },
          "slippage": 0.05
        }
      }
    ]
  },
  "run": {
    "inputs": {
      "token0": {
        "kind": "directDeposit",
        "amount": "5500000000000000000"
      },
      "token1": {
        "kind": "directDeposit",
        "amount": "2000000000000000000000"
      },
      "token2": {
        "kind": "directDeposit",
        "amount": "2000000000000000"
      }
    },
    "signer": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    "sweepTo": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
  }
}
```

### Prompt for a coding agent

```text
Goal: add "Sweep small balances into one token" 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: Small balances → Swap each one (lifi.swap ×n) → One token to the user.
   What can change: Tokens to sweep, Threshold, Target token, Slippage.
4. Name the flow "tpl:dust-sweep@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.
