Build: buy a basket of tokenized stocks
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.0stock-basket.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
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 full working module, not an excerpt. It names the flow tpl:stock-basket@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.
Funding tokenPassed by your user
Stocks and weightsFixed by you, or user picks
Slippage per stock1%
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