# Buy a basket of tokenized stocks

> One payment splits into a weighted basket of stock tokens. Sell it back the same way.

- Status: live. Compiles on Composer today.
- Who it's for: Wallets and neobanks with a stocks tab
- Page: https://composer-experiences.li.quest/templates/stock-basket
- Working example, run with your own key and wallet: https://composer-experiences.li.quest/templates/stock-basket/live

## What you get

- A whole theme in one transaction instead of one trade per stock
- Weights are fixed by you or picked by the user
- A stock that cannot be bought right now is named before signing

## 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): USDC
2. Split by weight (Ethereum): Up to 13 legs. Ops: `core.partition`
3. Buy each stock token (Ethereum): MSTRx, CRCLon. Ops: `lifi.swap ×n`

## What you control

| Parameter | Set by |
| --- | --- |
| Funding token | Passed by your user |
| Stocks and weights | Fixed by you, or user picks |
| Slippage per stock | 1% |

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

```ts
/**
 * Buy a basket of tokenized stocks in one transaction: one payment is split
 * by weight, each part is swapped into its stock token, and the stock tokens
 * go 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 StockBasketInputs {
  chainId: number;
  /** The token the user pays with, e.g. USDC. */
  payToken: Address;
  /** In `payToken`'s smallest unit. */
  amount: bigint;
  /** Two to thirteen stock tokens; weights in basis points sum to 10000. */
  stocks: { token: Address; weightBps: number }[];
  /** Per stock, in basis points. */
  slippageBps: number;
  user: Address;
}

export const buildFlow = (
  sdk: ComposeSdk,
  inputs: StockBasketInputs,
  name = 'tpl:stock-basket@1'
) => {
  const { chainId, stocks } = inputs;
  const flow = sdk.flow(chainId, {
    name,
    inputs: { payment: resources.erc20(inputs.payToken, chainId) },
  });

  // Split the payment into one part per stock, by weight.
  const { parts } = flow.core.partition('split', {
    bind: { source: flow.inputs.payment },
    config: { bps: stocks.map(({ weightBps }) => weightBps) },
  });

  // Swap each part into its stock token.
  stocks.forEach(({ token }, i) => {
    flow.lifi.swap(`buy${i}`, {
      bind: { amountIn: parts[i]! },
      config: {
        resourceOut: resources.erc20(token, chainId),
        slippage: inputs.slippageBps / 10_000,
      },
    });
  });

  const run = {
    signer: inputs.user,
    inputs: { payment: materialisers.directDeposit({ amount: inputs.amount }) },
    sweepTo: inputs.user,
  };
  return { flow, run };
};
```

### Call it

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

import { buildFlow } from './stock-basket';

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:stock-basket@1",
    "chainId": 1,
    "inputs": [
      {
        "name": "payment",
        "resource": {
          "kind": "erc20",
          "token": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
          "chainId": 1
        }
      }
    ],
    "nodes": [
      {
        "id": "split",
        "op": "core.partition",
        "bind": {
          "source": {
            "$ref": "input.payment"
          }
        },
        "config": {
          "bps": [
            5000,
            5000
          ]
        }
      },
      {
        "id": "buy0",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "split.parts.0"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0xAE2f842EF90C0d5213259Ab82639D5BBF649b08E",
            "chainId": 1
          },
          "slippage": 0.01
        }
      },
      {
        "id": "buy1",
        "op": "lifi.swap",
        "bind": {
          "amountIn": {
            "$ref": "split.parts.1"
          }
        },
        "config": {
          "resourceOut": {
            "kind": "erc20",
            "token": "0x3632DEa96A953C11dac2f00b4A05a32CD1063fAE",
            "chainId": 1
          },
          "slippage": 0.01
        }
      }
    ]
  },
  "run": {
    "inputs": {
      "payment": {
        "kind": "directDeposit",
        "amount": "500000000"
      }
    },
    "signer": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    "sweepTo": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
  }
}
```

### Prompt for a coding agent

```text
Goal: add "Buy a basket of tokenized stocks" 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 → Split by weight (core.partition) → Buy each stock token (lifi.swap ×n).
   What can change: Funding token, Stocks and weights, Slippage per stock.
4. Name the flow "tpl:stock-basket@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.
