> ## 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.

# Read the trade code

> Read the code that prices a trade from a Pyth feed, records it with the DvP program, and settles both legs in one transaction, then step through its output.

<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="current"><a href="/developers/docs/defi/settle-trade/browser" aria-current="step"><span className="sol-stepper-n">Step 2<span className="sol-vh">: </span></span><span className="sol-stepper-t">Read the code</span></a></li>
<li data-state="todo"><a href="/developers/docs/defi/settle-trade/local"><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 is the code behind the trade in the previous step, in two files:
`price.ts` reads the price and converts the shares into USDC, and `trade.ts`
records, funds, and settles the trade. Press **Run** under each block to step
through its output on a local test network (Surfpool). Nothing is sent from
your browser, and there's nothing to install.

## 1. Price the trade

```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>

A Pyth price feed account holds Pyth's latest price for one feed, and anyone
can read it with an ordinary account lookup. The code reads the USDC/USD feed
account
<span className="sol-address" data-address="Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX"><Tooltip headline="Pyth USDC/USD price feed account" tip="Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX" cta="View on Solana Explorer" href="https://explorer.solana.com/address/Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX">`Dpw1…eFbX`</Tooltip><span className="nojs-only"> ([Pyth USDC/USD price feed account](https://explorer.solana.com/address/Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX))</span></span>
and checks it before using the price:

1. **The owner.** The account must belong to Pyth's receiver program
   (`rec5EKMG…LtFJ`). Anyone can create an account with bytes that look like a
   price, but only that program can write to accounts it owns.
2. **The layout and feed.** The first 8 bytes identify a `PriceUpdateV2`
   account, and the feed ID inside it must be USDC/USD.
3. **Verification.** The update must be fully verified (byte 40 is `1`).
4. **Age.** `publishTime` must be at most `MAX_PRICE_AGE_SECONDS` old, 120 by
   default. Pyth updates this feed on mainnet every 55 seconds, or sooner when
   the price moves by 0.5% ([sponsored feeds](https://docs.pyth.network/price-feeds/core/push-feeds/solana)).
5. **Confidence.** Pyth publishes a confidence interval with each price. The
   code refuses a price whose interval is wider than 0.5% of the price.

`priceTrade` then converts the dollar amount into USDC at that price, rounding
up to the next base unit. Pyth's values are integers with an exponent: a
`price` of `99987452` with an exponent of `-8` is 0.99987452.

The feed address and the receiver program address are the same on mainnet and
devnet (see Pyth's [contract addresses](https://docs.pyth.network/price-feeds/core/contract-addresses/solana)).

## 2. Record, fund, and settle

```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>

`trade.ts` uses the client generated from the DvP program's IDL (`./dvp`).

- **`createTrade`** derives the trade record's address from the agent, the two
  parties, the two mints, and a random nonce, and sends `CreateDvp` with both
  amounts and an expiry one day ahead. The agent pays the deposits for the
  record and both escrows, and gets them back when it settles. Then
  `verifyTrade` reads the record back.
- **`verifyTrade`** checks that the record is owned by the DvP program, is
  exactly 458 bytes, sits at the address its terms derive, and holds the agreed
  parties, mints, amounts, and payout addresses. Creating a record is open to
  anyone, so every party checks it before acting on it (see
  [verify the terms](/developers/docs/defi/dvp-program/fund-the-legs#verify-the-terms)).
  `settle` runs the same check before the agent signs.
- **`approveEscrow`** thaws the LSF escrow with the issuer's freeze authority.
  Without it, the seller's transfer into a frozen account fails.
- **`fundAssetLeg`** and **`fundCashLeg`** are plain `TransferChecked`
  transfers into the escrows. LSF is a Token-2022 token and USDC an SPL Token
  token; one trade can mix the two.
- **`settle`** creates the four token accounts that settlement pays into, if
  they don't exist, and sends `SettleDvp`, signed by the agent. The program
  checks both escrows, moves 4 LSF to the buyer, and the USDC to the seller,
  returns any surplus, and closes the record and both escrows.
- **`settleUnfunded`** sends the same settle with `skipPreflight`, so the
  failed attempt lands onchain and the code can read its error.

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Programs</span> <span className="sol-concept-def">Programs are code deployed to the network that owns and updates accounts.</span>](/developers/docs/core/programs)
</div>

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Cross-program calls</span> <span className="sol-concept-def">A cross-program call (CPI) is one program calling another inside the same transaction, the way your program would call the Token program to move tokens.</span>](/developers/docs/core/cpi)
</div>

The DvP program moves the tokens by calling the Token-2022 program for the LSF
leg and the Token program for the USDC leg, inside the one settle transaction.

To run this code yourself and change the trade, continue to the next step.
