> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Run it from your machine

> Add the trade to your Issue an asset project, generate the DvP client, and price and settle a trade from your terminal on a local Surfpool network or devnet.

<div className="sol-stepper not-prose" data-path="settle-trade">
<div className="sol-stepper-nav" role="navigation" aria-label="Settle a trade · ~40 min">
<ol>
<li data-state="done"><a href="/developers/docs/defi/settle-trade/try-it"><span className="sol-stepper-n">Step 1<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Watch a trade settle</span></a></li>
<li data-state="done"><a href="/developers/docs/defi/settle-trade/browser"><span className="sol-stepper-n">Step 2<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Read the code</span></a></li>
<li data-state="current"><a href="/developers/docs/defi/settle-trade/local" aria-current="step"><span className="sol-stepper-n">Step 3<span className="sol-vh">: </span></span><span className="sol-stepper-t">Run it from your machine</span></a></li>
<li data-state="todo"><a href="/developers/docs/defi/settle-trade/go-live"><span className="sol-stepper-n">Step 4<span className="sol-vh">: </span></span><span className="sol-stepper-t">Go live</span></a></li>
</ol>
</div>
</div>

This step runs the trade from your terminal. The trade needs an asset to sell,
so you add the DvP client and three files to your Issue an asset project. The
output under each block is from a local Surfpool network copying mainnet.

## 1. Start from your Issue an asset project

If you haven't done it yet, follow
[Run it from your machine](/developers/docs/assets/issue-asset/local) in the Issue an
asset tutorial. You need its `config.ts`, `create-asset.ts`,
`approve-holder.ts`, and `blocked-transfer.ts`, and an issuer key file. Each run
creates a new LSF asset, and the issuer approves the investors and the trade's
escrow.

Then install the two extra packages the trade uses: the SPL Token client for
the USDC leg and the Memo program address that `SettleDvp` takes.

```bash Terminal
npm install @solana-program/token @solana-program/memo
```

The examples are tested with `@solana-program/token` 0.17 and
`@solana-program/memo` 0.15.

## 2. Add the DvP client

No package is published for the DvP client. Generate it from the program's IDL
at the commit the
[DvP program pages](/developers/docs/defi/dvp-program/create-a-trade#install) use, and copy
it into your project as `./dvp`. Run this in your project folder. It clones the
repository next to the project and needs `pnpm`:

```bash Terminal
git clone https://github.com/solana-foundation/dvp.git ../dvp-program
(cd ../dvp-program && git checkout df9919ed02c25a93620e7f6820107c9050ce3b92 \
  && pnpm install && pnpm generate-clients)
cp -r ../dvp-program/clients/typescript/src ./dvp && rm -rf ./dvp/__tests__
```

The client depends only on `@solana/kit`, which the project already has.

## 3. Start a local network

Run the trade on a local Surfpool network that copies accounts from mainnet:
the DvP program, the Pyth price feed account, and the USDC mint are mainnet's,
and the test USDC is free.

1. Install the [Surfpool CLI](/developers/docs/tools/surfpool/toolchain/getting-started)
   and start it from mainnet, airdropping SOL to your issuer (replace
   `<issuer address>` with the address of your key file):

   ```bash Terminal
   surfpool start --network mainnet --airdrop <issuer address>
   ```

   Without `--airdrop`, Surfpool only funds the Solana CLI default key file,
   `~/.config/solana/id.json`.

2. In the terminal where you run the code, point it at Surfpool and at mainnet
   USDC. Unset, the code uses devnet and devnet USDC:

   ```bash Terminal
   export RPC_URL=http://127.0.0.1:8899
   export RPC_SUBSCRIPTIONS_URL=ws://127.0.0.1:8900
   export USDC_MINT=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
   ```

3. Give the issuer test USDC with Surfpool's
   [`surfnet_setTokenAccount`](/developers/docs/tools/surfpool/rpc/cheatcodes)
   cheatcode. Each run sends 6 USDC to the buyer, so 60 USDC covers ten runs.
   Repeat it to top up:

   ```bash Terminal
   curl http://127.0.0.1:8899 -s -X POST -H "Content-Type: application/json" -d '
     {"jsonrpc": "2.0", "id": 1, "method": "surfnet_setTokenAccount",
      "params": ["<issuer address>", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                 {"amount": 60000000, "state": "initialized"},
                 "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]}'
   ```

<Note>
  **Devnet.** The same code runs against devnet with the three variables unset.
  The examples were tested on a Surfpool network copying devnet, whose DvP
  program is an older build than the client's commit (see
  [Program ID](/developers/docs/defi/dvp-program#program-id)). The issuer needs SOL from
  the [Solana Faucet](https://faucet.solana.com/) and 6 devnet USDC per run from
  [Circle's faucet](https://faucet.circle.com/). The devnet USDC/USD feed can
  update less often, so if the price check refuses the price as too old, set
  `export MAX_PRICE_AGE_SECONDS=600`.
</Note>

## 4. Add the price

Save this as `price.ts`. It's the code from the previous step.

```ts price.ts
import {
  address,
  fetchEncodedAccount,
  fixDecoderSize,
  getBytesDecoder,
  getI32Decoder,
  getI64Decoder,
  getStructDecoder,
  getU64Decoder,
  type Address,
} from "@solana/kit";
import { rpc } from "./config";

/** Pyth's receiver program, which owns every price feed account it writes. */
export const PYTH_RECEIVER_PROGRAM = address(
  "rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ",
);
/** Pyth's USDC/USD price feed account (same address on mainnet and devnet). */
export const USDC_USD_FEED = address(
  "Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX",
);
const USDC_USD_FEED_ID =
  "eaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a";
// First 8 bytes of every PriceUpdateV2 account (an Anchor discriminator).
const PRICE_UPDATE_V2 = "22f123639d7ef4cd";

const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString("hex");

// The price message inside a PriceUpdateV2 account.
const priceMessage = getStructDecoder([
  ["feedId", fixDecoderSize(getBytesDecoder(), 32)],
  ["price", getI64Decoder()],
  ["conf", getU64Decoder()],
  ["exponent", getI32Decoder()],
  ["publishTime", getI64Decoder()],
]);

/**
 * Read a Pyth price feed account and refuse a price you shouldn't trade on:
 * the wrong account, the wrong feed, partly verified, too old, or with a
 * confidence interval that is too wide.
 */
export async function readPrice(
  feed: Address = USDC_USD_FEED,
  {
    feedId = USDC_USD_FEED_ID,
    maxAgeSeconds = Number(process.env.MAX_PRICE_AGE_SECONDS ?? 120),
    maxConfidenceBps = 50n, // 0.5% of the price
  } = {},
) {
  const account = await fetchEncodedAccount(rpc, feed);
  if (!account.exists) throw new Error(`no price feed at ${feed}`);
  if (account.programAddress !== PYTH_RECEIVER_PROGRAM)
    throw new Error(`${feed} is not owned by the Pyth receiver program`);
  const data = account.data;
  if (hex(data.slice(0, 8)) !== PRICE_UPDATE_V2)
    throw new Error(`${feed} is not a PriceUpdateV2 account`);
  // Byte 40 is the verification level: 1 = Full (all guardian signatures).
  if (data[40] !== 1) throw new Error("price update is only partly verified");

  const m = priceMessage.decode(data, 41);
  if (hex(new Uint8Array(m.feedId)) !== feedId)
    throw new Error(`${feed} holds a different feed`);
  const ageSeconds = Math.floor(Date.now() / 1000) - Number(m.publishTime);
  if (ageSeconds > maxAgeSeconds)
    throw new Error(`price is ${ageSeconds} s old (max ${maxAgeSeconds} s)`);
  if (m.price <= 0n || m.conf * 10_000n > m.price * maxConfidenceBps)
    throw new Error("price confidence interval is too wide");

  return {
    price: m.price, // the price is price × 10^exponent
    conf: m.conf,
    exponent: m.exponent,
    publishTime: m.publishTime,
    ageSeconds,
  };
}

/** Show a raw value (value × 10^exponent) as a decimal string. */
export function decimal(value: bigint, exponent: number) {
  const s = value.toString().padStart(1 - exponent, "0");
  return `${s.slice(0, exponent)}.${s.slice(exponent)}`;
}
/** 6-decimal base units as a plain number, e.g. 4000000n -> "4". */
export const units = (n: bigint) => decimal(n, -6).replace(/\.?0+$/, "");
const usd = (n: bigint) => `$${decimal(n / 10_000n, -2)}`;

/**
 * Price the cash leg. The asset is quoted in US dollars per share; the buyer
 * pays in USDC, so convert the dollar amount at the oracle's USDC/USD price.
 * Amounts are in base units: LSF and USDC both have 6 decimals.
 */
export async function priceTrade(shares: bigint, navPerShareUsd: bigint) {
  const usdc = await readPrice();
  const notionalUsd = (shares * navPerShareUsd) / 1_000_000n;
  // USDC = USD / (price × 10^exponent), rounded up to the next base unit.
  const scale = 10n ** BigInt(-usdc.exponent);
  const cashAmount = (notionalUsd * scale + usdc.price - 1n) / usdc.price;
  console.log(
    "USDC/USD from Pyth:",
    decimal(usdc.price, usdc.exponent),
    "±",
    decimal(usdc.conf, usdc.exponent),
    `(published ${usdc.ageSeconds} s ago)`,
  );
  console.log(
    `Price: ${units(shares)} LSF × ${usd(navPerShareUsd)} = ${usd(notionalUsd)} = ${units(cashAmount)} USDC`,
  );
  return { usdc, notionalUsd, assetAmount: shares, cashAmount };
}
```

<div className="sol-term not-prose" data-term="paths/defi/settle-trade/price" data-tab="price.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of priceTrade(4\_000\_000n, 1\_250\_000n)</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of priceTrade(4_000_000n, 1_250_000n): Output">
<div className="sol-term-step" data-step="1" data-pending="call">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await priceTrade(4\_000\_000n, 1\_250\_000n)</div>
<div className="sol-term-row sol-term-ln">USDC/USD from Pyth\: 0.99985925 ± 0.00100406 (published 46 s ago)</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Price\:</span> 4 LSF × \$1.25 = \$5.00 = 5.000704 USDC</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="info">USDC/USD read from Pyth</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

Surfpool copies the feed account once, the first time it's read, so a later
run on the same network fails the age check with `price is … s old`. Reset the
account to copy it again, then rerun:

```bash Terminal
curl http://127.0.0.1:8899 -s -X POST -H "Content-Type: application/json" -d '
  {"jsonrpc": "2.0", "id": 1, "method": "surfnet_resetAccount",
   "params": ["Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX"]}'
```

## 5. Add the trade

Save this as `trade.ts`. It imports the client from `./dvp` and `failure` from
the Issue an asset tutorial's `blocked-transfer.ts`.

```ts trade.ts
import {
  address,
  getAddressEncoder,
  getProgramDerivedAddress,
  type Address,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import {
  getTransferCheckedInstruction as getUsdcTransferInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import {
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  getThawAccountInstruction,
  getTransferCheckedInstruction,
  TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { failure } from "./blocked-transfer";
import { rpc, send } from "./config";
import { units } from "./price";
import {
  DVP_SWAP_PROGRAM_PROGRAM_ADDRESS,
  getDvpSwapProgramErrorMessage,
  findSwapDvpEscrowAta,
  findSwapDvpPda,
  getCreateDvpInstruction,
  getSettleDvpInstruction,
  verifySwapDvp,
  type DvpSwapProgramError,
} from "./dvp";

// Devnet USDC by default. On mainnet: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v.
export const USDC_MINT = address(
  process.env.USDC_MINT ?? "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
);

export interface Terms {
  seller: Address; // delivers the asset (user_a)
  buyer: Address; // delivers the cash (user_b)
  agent: Address; // the settlement authority, e.g. the venue
  asset: Address; // the asset's mint (Token-2022)
  assetAmount: bigint;
  cashAmount: bigint; // USDC base units (SPL Token)
}
export type Trade = Terms & {
  record: Address;
  escrowA: Address;
  escrowB: Address;
};

const ataOf = async (owner: Address, mint: Address, tokenProgram: Address) =>
  (await findAssociatedTokenPda({ owner, mint, tokenProgram }))[0];

/**
 * Record the terms with CreateDvp. It creates the trade record and one escrow
 * account per leg, and moves no tokens. Anyone can create a record, so read
 * it back and check it against the agreed terms before anyone funds it.
 */
export async function createTrade(agent: TransactionSigner, terms: Terms) {
  // A random 64-bit nonce, so nobody can occupy this trade's address first.
  const nonce = new DataView(
    crypto.getRandomValues(new Uint8Array(8)).buffer,
  ).getBigUint64(0);
  const seeds = {
    settlementAuthority: terms.agent,
    userA: terms.seller,
    userB: terms.buyer,
    mintA: terms.asset,
    mintB: USDC_MINT,
    nonce,
  };
  const [record] = await findSwapDvpPda(seeds);
  const [escrowA] = await findSwapDvpEscrowAta({
    swapDvp: record,
    mint: terms.asset,
    tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
  });
  const [escrowB] = await findSwapDvpEscrowAta({
    swapDvp: record,
    mint: USDC_MINT,
    tokenProgram: TOKEN_PROGRAM_ADDRESS,
  });
  const [nonceTombstone] = await getProgramDerivedAddress({
    programAddress: DVP_SWAP_PROGRAM_PROGRAM_ADDRESS,
    seeds: ["nonce", getAddressEncoder().encode(record)],
  });

  const signature = await send(agent, [
    getCreateDvpInstruction({
      payer: agent,
      swapDvp: record,
      nonceTombstone,
      ...seeds,
      dvpAtaA: escrowA,
      dvpAtaB: escrowB,
      tokenProgramA: TOKEN_2022_PROGRAM_ADDRESS,
      tokenProgramB: TOKEN_PROGRAM_ADDRESS,
      amountA: terms.assetAmount,
      amountB: terms.cashAmount,
      expiryTimestamp: BigInt(Math.floor(Date.now() / 1000) + 24 * 60 * 60),
      refString: "LSF-TRADE-0001",
      userASettlementDestination: null, // proceeds go to the seller
      userBSettlementDestination: null, // the asset goes to the buyer
      earliestSettlementTimestamp: null,
    }),
  ]);
  const trade: Trade = { ...terms, record, escrowA, escrowB };
  console.log("Trade record:", record);
  console.log("  asset leg:", units(terms.assetAmount), "LSF, escrow", escrowA);
  console.log("  cash leg:", units(terms.cashAmount), "USDC, escrow", escrowB);
  await verifyTrade(trade);
  console.log("Record checked: owner, size, address and terms match");
  console.log("Signature:", signature);
  return { trade, signature };
}

/** Check the record is the DvP program's and holds exactly the agreed terms. */
export async function verifyTrade(trade: Trade) {
  // Owner, size and address checks; throws on a forged record.
  const { data } = await verifySwapDvp(rpc, trade.record);
  const expected = {
    userA: trade.seller,
    userB: trade.buyer,
    settlementAuthority: trade.agent,
    mintA: trade.asset,
    mintB: USDC_MINT,
    amountA: trade.assetAmount,
    amountB: trade.cashAmount,
    userASettlementDestination: trade.seller,
    userBSettlementDestination: trade.buyer,
  };
  for (const [field, value] of Object.entries(expected))
    if (data[field as keyof typeof expected] !== value)
      throw new Error(`trade record ${field} does not match the agreed terms`);
  return data;
}

/**
 * The asset's accounts start frozen (Issue an asset), and so does the trade's
 * new escrow. The issuer approves the escrow the same way it approves a holder.
 */
export async function approveEscrow(issuer: TransactionSigner, trade: Trade) {
  const signature = await send(issuer, [
    getThawAccountInstruction({
      account: trade.escrowA,
      mint: trade.asset,
      owner: issuer,
    }),
  ]);
  console.log(
    "Issuer approved the LSF escrow for the trade. Signature:",
    signature,
  );
  return signature;
}

/** Each party funds its leg with an ordinary transfer into the escrow. */
export async function fundAssetLeg(seller: TransactionSigner, trade: Trade) {
  const signature = await send(seller, [
    getTransferCheckedInstruction({
      source: await ataOf(
        seller.address,
        trade.asset,
        TOKEN_2022_PROGRAM_ADDRESS,
      ),
      mint: trade.asset,
      destination: trade.escrowA,
      authority: seller,
      amount: trade.assetAmount,
      decimals: 6,
    }),
  ]);
  console.log("Seller funded the asset leg. Signature:", signature);
  return signature;
}
export async function fundCashLeg(buyer: TransactionSigner, trade: Trade) {
  const signature = await send(buyer, [
    getUsdcTransferInstruction({
      source: await ataOf(buyer.address, USDC_MINT, TOKEN_PROGRAM_ADDRESS),
      mint: USDC_MINT,
      destination: trade.escrowB,
      authority: buyer,
      amount: trade.cashAmount,
      decimals: 6,
    }),
  ]);
  console.log("Buyer funded the cash leg. Signature:", signature);
  return signature;
}

/**
 * SettleDvp moves both legs in one transaction: the asset to the buyer, the
 * USDC to the seller. If either escrow holds less than its agreed amount it
 * fails with LegNotFunded (custom error 4) and nothing moves.
 */
export async function settle(
  agent: TransactionSigner,
  trade: Trade,
  options: { skipPreflight?: boolean } = {},
): Promise<Signature> {
  await verifyTrade(trade);
  const T22 = TOKEN_2022_PROGRAM_ADDRESS;
  const T = TOKEN_PROGRAM_ADDRESS;
  // The four accounts SettleDvp writes to: each side's proceeds, and each
  // side's own account for any surplus in its escrow.
  const accounts = {
    userADestinationAtaB: [trade.seller, USDC_MINT, T],
    userBDestinationAtaA: [trade.buyer, trade.asset, T22],
    userAAtaA: [trade.seller, trade.asset, T22],
    userBAtaB: [trade.buyer, USDC_MINT, T],
  } as const;
  const ata = {} as Record<keyof typeof accounts, Address>;
  const createAccounts = [];
  for (const [name, [owner, mint, tokenProgram]] of Object.entries(accounts)) {
    ata[name as keyof typeof accounts] = await ataOf(owner, mint, tokenProgram);
    createAccounts.push(
      getCreateAssociatedTokenIdempotentInstruction({
        payer: agent,
        ata: ata[name as keyof typeof accounts],
        owner,
        mint,
        tokenProgram,
      }),
    );
  }

  const signature = await send(
    agent,
    [
      ...createAccounts,
      getSettleDvpInstruction({
        settlementAuthority: agent,
        swapDvp: trade.record,
        mintA: trade.asset,
        mintB: USDC_MINT,
        dvpAtaA: trade.escrowA,
        dvpAtaB: trade.escrowB,
        ...ata,
        tokenProgramA: T22,
        tokenProgramB: T,
        memoProgram: MEMO_PROGRAM_ADDRESS,
        legAExtrasCount: 0, // no transfer hooks on either mint
      }),
    ],
    options,
  );
  console.log("Settled both legs in one transaction. Signature:", signature);
  const [buyerLsf, buyerUsdc, sellerLsf, sellerUsdc] = await Promise.all([
    holding(trade.buyer, trade.asset),
    holding(trade.buyer, USDC_MINT),
    holding(trade.seller, trade.asset),
    holding(trade.seller, USDC_MINT),
  ]);
  console.log(
    `Balances: buyer ${units(buyerLsf)} LSF, ${units(buyerUsdc)} USDC |`,
    `seller ${units(sellerLsf)} LSF, ${units(sellerUsdc)} USDC`,
  );
  const closed = !(await rpc.getAccountInfo(trade.record).send()).value;
  console.log("Trade record and escrows closed:", closed);
  return signature;
}

/** Token balance of an account, or 0 when it doesn't exist (yet, or any more). */
export async function balance(account: Address) {
  const info = await rpc.getAccountInfo(account, { encoding: "base64" }).send();
  if (!info.value) return 0n;
  const { value } = await rpc.getTokenAccountBalance(account).send();
  return BigInt(value.amount);
}
export async function holding(owner: Address, mint: Address) {
  const tokenProgram =
    mint === USDC_MINT ? TOKEN_PROGRAM_ADDRESS : TOKEN_2022_PROGRAM_ADDRESS;
  return balance(await ataOf(owner, mint, tokenProgram));
}

/**
 * Settle while a leg is still unfunded, with skipPreflight so the failed
 * transaction lands onchain and you can read its error, log and fee.
 */
export async function settleUnfunded(agent: TransactionSigner, trade: Trade) {
  try {
    await settle(agent, trade, { skipPreflight: true });
    throw new Error("expected settle to fail");
  } catch (error) {
    const signature = (error as { signature?: Signature }).signature;
    if (!signature) throw error;
    const { err, fee } = await failure(signature);
    // err is {"InstructionError":[<instruction index>,{"Custom":<code>}]}
    const [instruction, { Custom }] = (
      err as { InstructionError: [number, { Custom: number }] }
    ).InstructionError;
    const code = Number(Custom) as DvpSwapProgramError;
    const message = getDvpSwapProgramErrorMessage(code);
    console.log(
      "Settle with the cash leg unfunded (skipPreflight): failed onchain",
    );
    console.log("Failed signature:", signature);
    console.log(
      "  err:",
      JSON.stringify(err, (_k, v) => (typeof v === "bigint" ? Number(v) : v)),
    );
    console.log(`  DvP error ${code}:`, message);
    console.log("  fee paid anyway:", String(fee), "lamports");
    const [escrowA, escrowB, buyerLsf, sellerUsdc] = await Promise.all([
      balance(trade.escrowA),
      balance(trade.escrowB),
      holding(trade.buyer, trade.asset),
      holding(trade.seller, USDC_MINT),
    ]);
    console.log(
      `Nothing moved: asset escrow ${units(escrowA)} LSF | cash escrow`,
      `${units(escrowB)} USDC | buyer ${units(buyerLsf)} LSF | seller`,
      `${units(sellerUsdc)} USDC`,
    );
    return {
      signature,
      err,
      fee,
      instruction,
      code,
      message,
      after: { escrowA, escrowB, buyerLsf, sellerUsdc },
    };
  }
}
```

<div className="sol-term not-prose" data-term="paths/defi/settle-trade/trade" data-tab="trade.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Settle with the cash leg unfunded, then with both legs funded</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Settle with the cash leg unfunded, then with both legs funded: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await approveEscrow(issuer, trade)</div>
<div className="sol-term-row sol-term-ln">Issuer approved the LSF escrow for the trade. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2mZuEQfUJxkS8uy4zrZLRPgkutCncf4RCDKevk5r5J9LCHtaMNFBWwxtvaMbQRrjwfx7QFcXqQPEgsNv7wkLKazN"><span className="sol-h-f">2mZuEQfUJxkS8uy4zrZLRPgkutCncf4RCDKevk5r5J9LCHtaMNFBWwxtvaMbQRrjwfx7QFcXqQPEgsNv7wkLKazN</span><span className="sol-h-s" aria-hidden="true">2mZu…KazN</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await fundAssetLeg(seller, trade)</div>
<div className="sol-term-row sol-term-ln">Seller funded the asset leg. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="24cpZdS3DyNWaFGkWeepUEogfgshrDxXJcmUJr9aiHwxLNFpWAyoHZ19MUSFcx3eywCepP6AwpB9t2heEhKJvu8A"><span className="sol-h-f">24cpZdS3DyNWaFGkWeepUEogfgshrDxXJcmUJr9aiHwxLNFpWAyoHZ19MUSFcx3eywCepP6AwpB9t2heEhKJvu8A</span><span className="sol-h-s" aria-hidden="true">24cp…vu8A</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await settleUnfunded(agent, trade)</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Settle with the cash leg unfunded (skipPreflight)\: failed onchain</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Failed <span className="sol-term-k">signature\:</span> <span className="sol-h" title="2FfFCTfYghi7RJX1YKDhTCpxcLQfCc5ZMs5CVCuosPfmTmoSyGVE6aPHwsyv8BWkaePqSjpjYWqXbF825G7cUj6"><span className="sol-h-f">2FfFCTfYghi7RJX1YKDhTCpxcLQfCc5ZMs5CVCuosPfmTmoSyGVE6aPHwsyv8BWkaePqSjpjYWqXbF825G7cUj6</span><span className="sol-h-s" aria-hidden="true">2FfF…cUj6</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">err\:</span> `{"InstructionError":[4,{"Custom":4}]}`</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2">DvP error 4\: DvP leg is not funded with the expected amount</div>
<div className="sol-term-row sol-term-ln" data-indent="2">fee paid anyway\: 5000 lamports</div>
<div className="sol-term-row sol-term-ln">Nothing moved\: asset escrow 4 LSF \| cash escrow 0 USDC \| buyer 0 LSF \| seller 0 USDC</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await fundCashLeg(buyer, trade)</div>
<div className="sol-term-row sol-term-ln">Buyer funded the cash leg. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="3FYLcpq3YKym1EbKMmDP7ZPvEcXxH62qU7VtnryzbxUm8uP8xTpvkoo3kNWv5y1jcyxrpegfD16T1fxmmdwD8eYo"><span className="sol-h-f">3FYLcpq3YKym1EbKMmDP7ZPvEcXxH62qU7VtnryzbxUm8uP8xTpvkoo3kNWv5y1jcyxrpegfD16T1fxmmdwD8eYo</span><span className="sol-h-s" aria-hidden="true">3FYL…8eYo</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await settle(agent, trade)</div>
<div className="sol-term-row sol-term-ln">Settled both legs in one transaction. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="WSZ95HL5Urh75SqheweTvM9ZdKzK5QDmh1nepwUBd31BzMruREbduWU4F1MYFX15JduNTBaRgWLo9ruSZ64iDTy"><span className="sol-h-f">WSZ95HL5Urh75SqheweTvM9ZdKzK5QDmh1nepwUBd31BzMruREbduWU4F1MYFX15JduNTBaRgWLo9ruSZ64iDTy</span><span className="sol-h-s" aria-hidden="true">WSZ9…iDTy</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Balances\:</span> buyer 4 LSF, 4.999296 USDC \| seller 996 LSF, 5.000704 USDC</div>
<div className="sol-term-row sol-term-ln">Trade record and escrows closed\: true</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="error">Failed\: leg not funded (Custom\: 4)</span><span className="sol-term-badge" data-tone="ok">Settled · both legs in one transaction</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Rent (storage deposit)</span> <span className="sol-concept-def">Every account holds a small refundable deposit for the space it takes up.</span>](/developers/docs/core/rent)
</div>

The agent pays the deposits for the trade record, its two escrow accounts, and
a small marker account that stops the same trade address being used twice.
When the agent settles, the record and the escrows are closed and their
deposits go back to the agent. The marker account is never closed.

## 6. Run it

Save this as `trade-run.ts` (`run.ts` is the Issue an asset script). It creates
a new LSF asset, gives the seller, the buyer, and the agent a little SOL for
fees and the buyer 6 USDC, approves the two investors (the seller gets
1000 LSF), then prices the trade, records it, funds the asset leg, tries to
settle, funds the cash leg, and settles. The output starts with the new asset
and the two approvals.

```ts trade-run.ts
// trade-run.ts: price an LSF trade from Pyth, then settle it with DvP.
//   npx tsx trade-run.ts
// The issuer key is read from ISSUER_KEYPAIR, or from the Solana CLI default
// ~/.config/solana/id.json. It needs SOL for fees and 6 USDC for each run,
// which it sends to the buyer.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  createKeyPairSignerFromBytes,
  generateKeyPairSigner,
  lamports,
  type TransactionSigner,
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import {
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  getTransferCheckedInstruction,
  TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import { approveHolder, openAccount } from "./approve-holder";
import { send } from "./config";
import { createAsset } from "./create-asset";
import { priceTrade } from "./price";
import {
  approveEscrow,
  createTrade,
  fundAssetLeg,
  fundCashLeg,
  settle,
  settleUnfunded,
  USDC_MINT,
} from "./trade";

export async function run(issuer: TransactionSigner) {
  const { mint: asset } = await createAsset(issuer);

  const seller = await generateKeyPairSigner();
  const buyer = await generateKeyPairSigner();
  const agent = await generateKeyPairSigner(); // the settlement authority
  const usdcAta = async (owner: TransactionSigner) =>
    (
      await findAssociatedTokenPda({
        owner: owner.address,
        mint: USDC_MINT,
        tokenProgram: TOKEN_PROGRAM_ADDRESS,
      })
    )[0];
  // SOL for each party's fees (the agent also pays the trade's rent, which
  // it gets back at settlement), and 6 USDC for the buyer to pay with.
  await send(issuer, [
    ...[seller, buyer, agent].map((to) =>
      getTransferSolInstruction({
        source: issuer,
        destination: to.address,
        amount: lamports(50_000_000n), // 0.05 SOL
      }),
    ),
    getCreateAssociatedTokenIdempotentInstruction({
      payer: issuer,
      ata: await usdcAta(buyer),
      owner: buyer.address,
      mint: USDC_MINT,
    }),
    getTransferCheckedInstruction({
      source: await usdcAta(issuer),
      mint: USDC_MINT,
      destination: await usdcAta(buyer),
      authority: issuer,
      amount: 6_000_000n,
      decimals: 6,
    }),
  ]);

  // Approve both investors; the seller holds 1000 LSF.
  for (const [owner, amount] of [
    [seller.address, 1_000_000_000n],
    [buyer.address, 0n],
  ] as const) {
    await openAccount(issuer, asset, owner);
    await approveHolder(issuer, asset, owner, amount);
  }

  // 4 LSF at $1.25 a share, paid in USDC at the live USDC/USD price.
  const quote = await priceTrade(4_000_000n, 1_250_000n);
  const { trade } = await createTrade(agent, {
    seller: seller.address,
    buyer: buyer.address,
    agent: agent.address,
    asset,
    assetAmount: quote.assetAmount,
    cashAmount: quote.cashAmount,
  });

  await approveEscrow(issuer, trade);
  await fundAssetLeg(seller, trade);
  const failed = await settleUnfunded(agent, trade);
  await fundCashLeg(buyer, trade);
  const settled = await settle(agent, trade);

  return { trade, failed, settled };
}

// Run when started directly (not when imported by the tests).
if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const keyPath =
    process.env.ISSUER_KEYPAIR ??
    join(homedir(), ".config", "solana", "id.json");
  const bytes = new Uint8Array(JSON.parse(await readFile(keyPath, "utf8")));
  await run(await createKeyPairSignerFromBytes(bytes));
}
```

<div className="sol-term not-prose" data-term="paths/defi/settle-trade/run" data-tab="trade-run.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of npx tsx trade-run.ts</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of npx tsx trade-run.ts: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\$</span> npx tsx trade-run.ts</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Mint\:</span> <span className="sol-h" title="PsxKt9wuT8VuCQDMkNCXrigRMeVgaopeNqBXCdeXJ5p"><span className="sol-h-f">PsxKt9wuT8VuCQDMkNCXrigRMeVgaopeNqBXCdeXJ5p</span><span className="sol-h-s" aria-hidden="true">PsxK…XJ5p</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Extensions\:</span> MetadataPointer, PausableConfig, PermanentDelegate, DefaultAccountState, TokenMetadata</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="27HUffYm1hJekCNgSjBW3AS4r1D2nBBEpqcvgrrBUV2EGZeqWhw9Txt3PUo3azPKN7yd9LA44i7cDxfJMPSznyo7"><span className="sol-h-f">27HUffYm1hJekCNgSjBW3AS4r1D2nBBEpqcvgrrBUV2EGZeqWhw9Txt3PUo3azPKN7yd9LA44i7cDxfJMPSznyo7</span><span className="sol-h-s" aria-hidden="true">27HU…nyo7</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Fee\:</span> 10000 lamports</div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="2itvBPXadQbV3ktWMEWsySC7gosnis8dFXxTeusj3weB"><span className="sol-h-f">2itvBPXadQbV3ktWMEWsySC7gosnis8dFXxTeusj3weB</span><span className="sol-h-s" aria-hidden="true">2itv…3weB</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="2itvBPXadQbV3ktWMEWsySC7gosnis8dFXxTeusj3weB"><span className="sol-h-f">2itvBPXadQbV3ktWMEWsySC7gosnis8dFXxTeusj3weB</span><span className="sol-h-s" aria-hidden="true">2itv…3weB</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 1000 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="ebrnZWeehNAvJh8bGSs6aasntCS253LSekR52yivCspE8fzmpXpBFabPcb3ukXiYkZ8uSxPtYZ6Rsp3nGGGz4hS"><span className="sol-h-f">ebrnZWeehNAvJh8bGSs6aasntCS253LSekR52yivCspE8fzmpXpBFabPcb3ukXiYkZ8uSxPtYZ6Rsp3nGGGz4hS</span><span className="sol-h-s" aria-hidden="true">ebrn…z4hS</span></span></div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="7r6cYT2HEtnEEFdQYBiiNjMDFZG9tqEmVJDSyM9Fdhao"><span className="sol-h-f">7r6cYT2HEtnEEFdQYBiiNjMDFZG9tqEmVJDSyM9Fdhao</span><span className="sol-h-s" aria-hidden="true">7r6c…dhao</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="7r6cYT2HEtnEEFdQYBiiNjMDFZG9tqEmVJDSyM9Fdhao"><span className="sol-h-f">7r6cYT2HEtnEEFdQYBiiNjMDFZG9tqEmVJDSyM9Fdhao</span><span className="sol-h-s" aria-hidden="true">7r6c…dhao</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 0 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="4r8aaALCczy2tkg872LkibuyaZ48PSMSzF5iGEMRNbfhbFpMquum47MXfnV1bVZ5jddQsmB2qYe88eQ2ni23orVW"><span className="sol-h-f">4r8aaALCczy2tkg872LkibuyaZ48PSMSzF5iGEMRNbfhbFpMquum47MXfnV1bVZ5jddQsmB2qYe88eQ2ni23orVW</span><span className="sol-h-s" aria-hidden="true">4r8a…orVW</span></span></div>
<div className="sol-term-row sol-term-ln">USDC/USD from Pyth\: 0.99985944 ± 0.00100387 (published 4 s ago)</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Price\:</span> 4 LSF × \$1.25 = \$5.00 = 5.000703 USDC</div>
<div className="sol-term-row sol-term-ln">Trade record\: <span className="sol-h" title="88XeBphVdRDrQRhirLyVNLGGLQmAoDmx5WtADNPM311C"><span className="sol-h-f">88XeBphVdRDrQRhirLyVNLGGLQmAoDmx5WtADNPM311C</span><span className="sol-h-s" aria-hidden="true">88Xe…311C</span></span></div>
<div className="sol-term-row sol-term-ln" data-indent="2">asset leg\: 4 LSF, escrow <span className="sol-h" title="9fQeTCqRsNfeUDdJ8QqvdBmYC14vh7JwiFUwAmpuvf97"><span className="sol-h-f">9fQeTCqRsNfeUDdJ8QqvdBmYC14vh7JwiFUwAmpuvf97</span><span className="sol-h-s" aria-hidden="true">9fQe…vf97</span></span></div>
<div className="sol-term-row sol-term-ln" data-indent="2">cash leg\: 5.000703 USDC, escrow <span className="sol-h" title="HK92sq9rms2c1Nobn3w81mSGKeuQyhyAG6yQ1yYSjfFD"><span className="sol-h-f">HK92sq9rms2c1Nobn3w81mSGKeuQyhyAG6yQ1yYSjfFD</span><span className="sol-h-s" aria-hidden="true">HK92…jfFD</span></span></div>
<div className="sol-term-row sol-term-ln">Record checked\: owner, size, address and terms match</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2dStdFAm2x64nLj4bVyzZGbge2y6WHK1HcvpPt64aaVxRRrvQ44uT3XKH97bNQWAVHSwkcvjBZpdCDYSnUpMzNQG"><span className="sol-h-f">2dStdFAm2x64nLj4bVyzZGbge2y6WHK1HcvpPt64aaVxRRrvQ44uT3XKH97bNQWAVHSwkcvjBZpdCDYSnUpMzNQG</span><span className="sol-h-s" aria-hidden="true">2dSt…zNQG</span></span></div>
<div className="sol-term-row sol-term-ln">Issuer approved the LSF escrow for the trade. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2nkyJ2GnC9nw3y1Z2XAsrGYf5ZiDbVbGiSHUnVXc8Nk9cAcRyyNwMLQ6QLaFVc7FasWheDHP2s1F2R4zsfHwfzPu"><span className="sol-h-f">2nkyJ2GnC9nw3y1Z2XAsrGYf5ZiDbVbGiSHUnVXc8Nk9cAcRyyNwMLQ6QLaFVc7FasWheDHP2s1F2R4zsfHwfzPu</span><span className="sol-h-s" aria-hidden="true">2nky…fzPu</span></span></div>
<div className="sol-term-row sol-term-ln">Seller funded the asset leg. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="5V8hmsGn1xzUDUgkhkN7Y77nmuG3iPqH71aFXsmyU14cy2j5kwAZ8edSXiAFwd96RLqjTK8bPey4kg4AsnPsfkDz"><span className="sol-h-f">5V8hmsGn1xzUDUgkhkN7Y77nmuG3iPqH71aFXsmyU14cy2j5kwAZ8edSXiAFwd96RLqjTK8bPey4kg4AsnPsfkDz</span><span className="sol-h-s" aria-hidden="true">5V8h…fkDz</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error">Settle with the cash leg unfunded (skipPreflight)\: failed onchain</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Failed <span className="sol-term-k">signature\:</span> <span className="sol-h" title="2BLhaueJbDmv4UEqW9Zpgi2HzopT93keyqGkYwu3SkgdDsJ1JFCUQu2kLCHaGZwReypmGbvmQK4uvFxUShGkNFUU"><span className="sol-h-f">2BLhaueJbDmv4UEqW9Zpgi2HzopT93keyqGkYwu3SkgdDsJ1JFCUQu2kLCHaGZwReypmGbvmQK4uvFxUShGkNFUU</span><span className="sol-h-s" aria-hidden="true">2BLh…NFUU</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">err\:</span> `{"InstructionError":[4,{"Custom":4}]}`</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2">DvP error 4\: DvP leg is not funded with the expected amount</div>
<div className="sol-term-row sol-term-ln" data-indent="2">fee paid anyway\: 5000 lamports</div>
<div className="sol-term-row sol-term-ln">Nothing moved\: asset escrow 4 LSF \| cash escrow 0 USDC \| buyer 0 LSF \| seller 0 USDC</div>
<div className="sol-term-row sol-term-ln">Buyer funded the cash leg. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="Cci8NmtgrYLv8YAPbn6Vx8TzFkwbX9EgFjeSCy8Ltg9CMARPXe54eEtXBtv2koY7vDjotzynthDEAUnjiUHkkmn"><span className="sol-h-f">Cci8NmtgrYLv8YAPbn6Vx8TzFkwbX9EgFjeSCy8Ltg9CMARPXe54eEtXBtv2koY7vDjotzynthDEAUnjiUHkkmn</span><span className="sol-h-s" aria-hidden="true">Cci8…kkmn</span></span></div>
<div className="sol-term-row sol-term-ln">Settled both legs in one transaction. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="67VeoGZmkBBNuFnrpVVrPP77JXovfQVSPSVQ6cLWz3Hfe428WYyMATQXeMNWxEzncWjoS4FZhweUEWJY5VdtNvf6"><span className="sol-h-f">67VeoGZmkBBNuFnrpVVrPP77JXovfQVSPSVQ6cLWz3Hfe428WYyMATQXeMNWxEzncWjoS4FZhweUEWJY5VdtNvf6</span><span className="sol-h-s" aria-hidden="true">67Ve…Nvf6</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Balances\:</span> buyer 4 LSF, 0.999297 USDC \| seller 996 LSF, 5.000703 USDC</div>
<div className="sol-term-row sol-term-ln">Trade record and escrows closed\: true</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="error">First settle failed\: leg not funded</span><span className="sol-term-badge" data-tone="ok">Settled</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

Then run it:

```bash Terminal
npx tsx trade-run.ts
```

Expect the states and errors shown under the script, with your own addresses
and signatures, and a USDC amount that follows the current price.

## Run the tests instead

The code on these pages and its tests live in the docs repository under
`packages/docs-examples/paths/defi/settle-trade`. The test starts its own
Surfpool network copying mainnet, so you need no Surfpool CLI, keys, SOL, or
USDC:

```bash Terminal
git clone https://github.com/solana-foundation/solana-com.git
cd solana-com
corepack enable
pnpm install
pnpm --filter @workspace/docs-examples exec vitest run paths/defi/settle-trade
```

The tests pass when the first settle fails with `{"Custom":4}` and moves
nothing, and the second moves 4 LSF to the buyer and the USDC to the seller and
closes the trade.

<Note>
  The full example is in
  [`packages/docs-examples/paths/defi/settle-trade`](https://github.com/solana-foundation/solana-com/tree/main/packages/docs-examples/paths/defi/settle-trade).
</Note>
