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

# Superstate Swap

> Superstate swap offers: allowlisting a wallet, live on-chain quotes, and passage.superstate.execute.

Superstate supplies **tokenized equities**. A Superstate offer arrives with `type: "superstate::swap"` and settles **directly onchain**: the user pays with a stablecoin and receives the tokenized equity, an ERC-20, in the same flow.

> [!NOTE]
>
> **Recommended:** render [`CheckoutContainer`](https://docs.passage.coinlist.co/sdk/checkout). It detects `superstate::swap` and renders this entire flow - wallet step, amount, review, confirmation - for you. This page covers what is specific to Superstate, and the rungs below the component.

> [!NOTE]
>
> `passage.superstate` was the `swap` namespace before v0.11.0, and `executeSwap` is now `execute`. It is named after the provider now, because Ondo ships its own swap and `swap` could only ever mean one of them. See the [changelog](https://docs.passage.coinlist.co/changelogs/react.md) for the migration table.

## What Superstate needs from you

**Nothing.** The SDK looks up the swap contract for the chain you pass, and the funding assets and issuer are the provider's own constants. Every `CheckoutConfig` key is optional, and so is `config` itself. The `"superstate::swap"` entry takes one optional listener, `onOrderConfirmed`, which fires once the swap has mined. The confirmation dialog shows either way:

```tsx theme={null}
import { type CheckoutConfig, CheckoutContainer } from "@passage-cl/react";
import type { OfferOptionId } from "@passage-cl/react/universal";

const config: CheckoutConfig = {
  "superstate::swap": {
    onOrderConfirmed: (order) => console.log("Swap mined", order.swapTxHash),
  },
};

// `optionId` is the offer option your page showed. Superstate ignores it,
// but `CheckoutContainer` requires it for every offer type.
export function SwapCheckout({ optionId }: { optionId: OfferOptionId }) {
  return (
    <CheckoutContainer
      offer={offer}
      chain="ethereum_sepolia"
      optionId={optionId}
      wallets={wallets}
      config={config}
    />
  );
}
```

The SDK ships the Superstate swap contract for **Ethereum Sepolia only** today. On a chain with no contract, the checkout renders its flow-level error instead of quoting, and logs `checkout blocked` with the reason `unsupported-chain` once, at `error`, through your `Config.logger`.

The Superstate checkout ignores `CheckoutContainer`'s `optionId` prop, because a swap sends no option id. The prop is still required, as it is for every offer type, so pass the option your page showed: the SDK never picks one. `useSuperstateSwapCheckoutViewModel` takes no `optionId` at all.

Three things distinguish Superstate from the other providers:

* **The wallet must be allowlisted.** Superstate only settles to addresses the issuer has approved. The user signs an ownership challenge and the SDK allowlists the address on the swap contract, once per wallet per offer. The same allowlists are what make permissioned DeFi pools and RWA lending markets reachable. That is also why the Superstate checkout never skips its wallet step: a `wallets.preselected` wallet opens the step with its row already selected, rather than skipping it (see [Wallets](https://docs.passage.coinlist.co/sdk/wallets.md#skipping-the-wallet-step)).
* **The fee comes out of the amount quoted.** You quote the gross amount the user wants to spend, and the quote splits it into `inputTokenAmount` (what buys shares) and `fee`. The wallet is debited `inputTokenAmount + fee`, which never exceeds the amount quoted, so always show that sum as the total cost.
* **Quotes are read quotes, polled every 15 seconds.** Nothing is committed until the swap itself, and slippage protection guards the on-chain minimum output. There is no expiring committed quote to race, as there is with Ondo.

If your app stops supplying the wallet the user confirmed on the wallet step (it disconnected, or switched to another account), the checkout returns to the wallet step with "Your wallet disconnected - reconnect or choose another." It waits while a swap is in flight, and stays on the review step while a sent swap has not confirmed. Choosing a wallet again runs the authorization again, which returns at once for a wallet that is already allowlisted.

Allowlisting a wallet needs a CoinList user, and this checkout does not check the session. On a wallet session (a user signed in with their wallet instead of a CoinList login), a wallet that is not allowlisted yet fails on the wallet step with "Failed to request authorization challenge. Please try again." Retrying does not help.

## Prerequisites

* Completed [OAuth](https://docs.passage.coinlist.co/sdk/oauth-authentication.md) with a working `PassageProvider`
* A **swap-enabled offer**. CoinList provides the offer ID during onboarding - keep it in a constant (`SWAP_OFFER_ID`).
  > [!NOTE]
  >
  > Offers expose a `type` field, so you can detect Superstate swap offers from [fetch offers](https://docs.passage.coinlist.co/sdk/fetch-offers.md) data via `offer.type === "superstate::swap"` instead of hard-coding IDs. Ondo swap offers are `'ondo::swap'` and take a different flow.
* A wallet integration. The partner demo uses [wagmi](https://wagmi.sh/) + [Reown AppKit](https://reown.com/appkit); any stack that can sign messages and send transactions works. See [Wallets](https://docs.passage.coinlist.co/sdk/wallets.md).

```bash theme={null}
npm install @passage-cl/react wagmi @wagmi/core viem @reown/appkit @reown/appkit-adapter-wagmi @tanstack/react-query
```

> [accordion] Build your own UI with hooks (L2)
>
> `useSuperstateSwapCheckoutViewModel` wraps the whole flow and returns `{ state, onEvent }`. Call it behind your own markup when you want the SDK's logic, state and error handling but not its UI.
>
> ```tsx theme={null}
> import { useSuperstateSwapCheckoutViewModel } from "@passage-cl/react";
>
> export function MySwapCheckout() {
>   const { state, onEvent } = useSuperstateSwapCheckoutViewModel({
>     offer,
>     chain: "ethereum_sepolia",
>     wallets,
>     // Optional: `enabled` (default true) and `onOrderConfirmed`.
>   });
>
>   if (state.type === "error") {
>     return <p role="alert">Swaps are unavailable ({state.reason}).</p>;
>   }
>   // Render state.wallet, state.amount, state.review, state.sidebar and
>   // state.orderConfirmed with your own markup, and send the user's actions
>   // to onEvent.
>   return <MySwapSteps state={state} onEvent={onEvent} />;
> }
> ```
>
> `state` is either `{ type: "error", reason }`, when the swap could not be loaded at all (`"unsupported-chain"`: no contract on the chain, or `"load-failed"`: the output token read failed, which `{ type: "ON_RETRY_LOAD" }` retries), or `{ type: "content" }` with one slice per region: `wallet`, `amount`, `review`, `sidebar`, and `orderConfirmed`. Each slice is a discriminated union of its own. `switch` on each exhaustively and assign the `default` to `const exhaustive: never`, so a new arm is a compile error rather than a blank screen.
>
> The data hooks it is built from are exported too, so you can assemble your own viewmodel instead:
>
> | Hook | What it does |
> | - | - |
> | `useSwapOutputToken` | Reads the tokenized equity's decimals and symbol from the contract, once. Returns `{ state, refetch }`; call `refetch()` to retry after an `ERROR`. |
> | `useSwapQuote` | Polls a live quote every 15s. Returns `{ state }`. |
> | `useErc20TokenBalances` | Per-asset wallet balances, for a Max button. Returns `{ state }`. |
>
> Each returns its result as a `state` union with `DISABLED`, `LOADING`, `ERROR` (with a `reason` of `"not-authenticated"` or `"generic-error"`), and `CONTENT` arms, and each takes a required `enabled` flag. Switched off with no answer in hand, a hook reports `DISABLED`. `useSwapQuote` keeps a quote it already has; `useErc20TokenBalances` drops its balances and reports `DISABLED` whenever it is switched off or has no `address`. Like all React hooks they must be called unconditionally. See [SDK structure](https://docs.passage.coinlist.co/sdk/structure.md#hooks) for the conventions they share.
>
> The step viewmodels (`useSuperstateAmountViewModel`, `useSuperstateWalletViewModel`, `useSuperstateReviewViewModel`, `useSuperstateSidebarViewModel`) and the `SlippagePicker` component are no longer exported since v0.13.0. Use the god viewmodel above, or build the steps yourself from the data hooks and the L1 namespace below.

> [accordion] Drive it yourself with the client (L1)
>
> `passage.superstate` is a plain namespace with no React. The walkthrough below builds the flow from scratch, trimmed to the minimum that still compiles and runs.
>
> ### Flow at a glance
>
> ```mermaid theme={null}
> flowchart LR
>   connect[connect_wallet]
>   authorize[authorizing]
>   quote[quoting]
>   swapping[swapping]
>   success[success]
>   error[error]
>
>   connect -->|wallet connected| authorize
>   authorize -->|sign challenge + allow-list tx| quote
>   authorize -->|rejected / not authorized| error
>   quote -->|user confirms amount| swapping
>   swapping -->|approve + swap mined| success
>   swapping -->|rejected / reverted| error
>   error -->|retry| connect
> ```
>
> 1. **connect\_wallet** - your wallet UI; the SDK only needs the connected account.
>
> 2. **authorizing** - `passage.superstate.authorizeWallet` proves the user owns the wallet (a message signature) and allow-lists it for the offer, broadcasting an allow-list transaction if the contract requires one. One-time per wallet per offer.
>
> 3. **quoting** - `useSwapOutputToken` + `useSwapQuote` show a live quote (input, fee, output), refreshed every 15s.
>
> 4. **swapping** - `passage.superstate.execute` runs the ERC-20 approval and then the swap, reporting progress phases.
>
> 5. **success / error** - show the confirmed output amount and an explorer link, or a readable error.
>
> > [!NOTE]
> >
> > The flow involves **two identities**: the **CoinList session** (from OAuth) identifies *who* is buying, and the **external wallet** is *where* the shares are delivered. `authorizeWallet` is what links them - which is why the user signs a message before ever swapping.
>
> ### Step 1: Pin the swap parameters
>
> Keep the offer, chain, contract, and input token in one place. `superstateSwapContractAddress(chain)` returns the swap contract the SDK knows for a chain, or `null` where none is deployed. `TOKEN_REGISTRY` knows the ERC-20 metadata and per-chain address for USDC, USDT, and USDZ. Superstate pays in USDC on every chain, Sepolia included. USDZ, CoinList's test dollar on Ethereum Sepolia, pays Centrifuge vaults there, and token sales that list it.
>
> ```ts constants.ts theme={null}
> import {
>   type EthereumChain,
>   type EvmContractAddress,
>   OfferId,
>   superstateSwapContractAddress,
>   TOKEN_REGISTRY,
>   USDC_SYMBOL,
> } from "@passage-cl/react/universal";
>
> // Provided by CoinList during onboarding.
> export const SWAP_OFFER_ID = OfferId("YOUR_SWAP_OFFER_ID");
>
> export const SWAP_CHAIN: EthereumChain = "ethereum_sepolia";
> export const SWAP_CONTRACT_ADDRESS = requireSwapContract(SWAP_CHAIN);
>
> function requireSwapContract(chain: EthereumChain): EvmContractAddress {
>   const address = superstateSwapContractAddress(chain);
>   if (address === null) {
>     throw new Error(`No Superstate swap contract on ${chain}`);
>   }
>   return address;
> }
>
> // The stablecoin the user pays with (USDC, 6 decimals).
> export const INPUT_TOKEN = TOKEN_REGISTRY.erc20(USDC_SYMBOL);
> export const INPUT_TOKEN_ADDRESS = TOKEN_REGISTRY.usdcAddress(SWAP_CHAIN);
>
> // BCP-47 locale used for amount formatting.
> export const LOCALE = "en-US";
> ```
>
> > [!NOTE]
> >
> > This page runs on **Sepolia** throughout. The SDK knows the Sepolia swap contract only, so `superstateSwapContractAddress("ethereum_mainnet")` returns `null` today. CoinList provides the production mainnet address when swaps go live. To move to mainnet, set `SWAP_CHAIN` to `"ethereum_mainnet"` and point `SWAP_CONTRACT_ADDRESS` at that address - `TOKEN_REGISTRY` already knows the mainnet USDC/USDT addresses.
>
> ### Step 2: Bring your wallet
>
> The swap flows never import wagmi. They drive **any** wallet through the `EvmWallet` interface, which you implement once for every flow in the SDK.
>
> > [card] [Wallets: the EvmWallet seam](https://docs.passage.coinlist.co/sdk/wallets.md)
> >
> > The five members, the wagmi + AppKit adapter, and how wallet errors are classified.
>
> ```ts theme={null}
> import { buildEvmWallet } from "./wagmiEvmWallet";
> ```
>
> ### Step 3: Allowlist the wallet
>
> Superstate only settles to wallets the issuer has allowlisted. `passage.superstate.authorizeWallet` does both halves in one call: it proves the user controls the wallet by having them sign a challenge, then registers the address against the offer, broadcasting an allowlist transaction if the contract requires one.
>
> ```tsx theme={null}
> const wallet = buildEvmWallet({
>   address: EvmWalletAddress(address),
>   walletClient,
>   config,
> });
>
> const result = await passage.superstate.authorizeWallet({
>   wallet,
>   offerId: SWAP_OFFER_ID,
>   contractAddress: SWAP_CONTRACT_ADDRESS,
>   chain: SWAP_CHAIN,
>   onProgress: (phase) => setBusy({ kind: "authorize", phase }),
> });
>
> if (result.type === "success") {
>   setAuthorized(true);
> } else {
>   setError(result.error.step);
> }
> ```
>
> It is **idempotent**: if the wallet is already authorized it returns `success` immediately without prompting, so it is safe to call at the start of every session. Failures come back as `{ type: "error" }` rather than throwing.
>
> #### Parameters
>
> | Parameter | Type | Description |
> | - | - | - |
> | `wallet` | `EvmWallet` | An already-connected wallet that can sign messages and send transactions. |
> | `offerId` | `OfferId` | The offer to allowlist the wallet against. |
> | `contractAddress` | `EvmContractAddress` | The swap contract for the offer. |
> | `chain` | `EthereumChain` | The EVM chain to authorize on, for example `ethereum_mainnet`. |
> | `onProgress` | `(phase: WalletAuthorizationPhase) => void` | Optional. Called as the flow advances, for rendering loading states. |
>
> #### Progress phases
>
> Emitted in order. Two of them open a wallet popup. A wallet that is already authorized stops after `checking-authorization`:
>
> `checking-authorization` → `requesting-challenge` → **`signing-message`** *(wallet popup)* → `submitting-signature` → *(**`broadcasting-transaction`** (wallet popup) → `awaiting-confirmation`, only when the contract needs an allowlist transaction)* → `verifying-authorization`
>
> #### Error steps
>
> `WalletAuthorizationError` is tagged by the step that failed, so you can tell a user rejection apart from an infrastructure problem.
>
> | `step` | What happened |
> | - | - |
> | `authorization-check` | Reading the wallet's authorization failed: either the initial check, or the final on-chain re-check after the user signed (and possibly after the allowlist transaction was broadcast). |
> | `challenge-request` | Requesting the ownership challenge failed. It always fails on a wallet session, because the request needs a CoinList user. |
> | `signing` | The user did not sign the challenge. Carries a `cause` of type `WalletError`. |
> | `allow-wallet` | Submitting the signature to allowlist the wallet failed. |
> | `broadcast` | The wallet never sent the allowlist transaction. Carries a `cause` of type `WalletError`, which is `contract_reverted` when the wallet refused a transaction that would revert. Authorizing again is safe. |
> | `broadcast-unconfirmed` | The allowlist transaction was sent, but waiting for its receipt failed. It may still mine, so authorizing again would send a second one. Carries the `txHash` to look up first, and a `cause` of type `WalletError`. |
> | `not-authorized` | The flow completed but the on-chain re-check still reports the wallet as unauthorized. |
>
> An allowlist transaction that reverts is not an error of its own: the flow goes on to the on-chain re-check, and reports `not-authorized` only if the contract still says no.
>
> A `cause` of `{ type: "disconnected" }` means the wallet is no longer connected, or no longer on the account its `address` names, so nothing was sent. Retrying through the same wallet fails the same way, so ask the user to reconnect or choose another wallet. Your `EvmWallet` reports this by throwing `WalletDisconnectedError` from `@passage-cl/react/universal`. An EIP-1193 `4100` error and wagmi's `ConnectorNotConnectedError` count the same, so a viem or wagmi adapter can let those propagate. See [Wallets](https://docs.passage.coinlist.co/sdk/wallets.md).
>
> Allowlisting needs a CoinList user: `passage.wallets.createOwnershipChallenge` and `passage.superstate.allowWallet` both throw `NotAuthenticatedError` on a wallet session, and `authorizeWallet` turns that into its `challenge-request` step. A wallet that is already authorized succeeds before reaching either call.
>
> `authorizeWallet` reads `authorized(address)` on the swap contract over JSON-RPC (through CoinList's authenticated RPC proxy unless you set `Config.rpc`), and calls two Frontline endpoints. The first is also `passage.wallets.createOwnershipChallenge`, which the [requirements checklist](https://docs.passage.coinlist.co/sdk/requirements.md) uses to bind a wallet to an offer option. For non-SDK integrations, Frontline also serves the authorization read as `GET /v1/wallet/authorized`.
>
> | Endpoint | Purpose |
> | - | - |
> | `POST /v1/wallet-ownership` | Requests a `plain` challenge for the user to sign. |
> | `POST /v1/offers/{offer_id}/allow-wallet` | Submits the signature and allowlists the address. |
>
> ### Step 4: Show a live quote
>
> Read the output token to learn its decimals, parse the user's input, then poll a quote. `useSwapQuote` waits while `outputTokenDecimals` is `null`; gate it on a valid amount yourself, through `enabled`.
>
> ```tsx theme={null}
> const { state: outputTokenState } = useSwapOutputToken({
>   contractAddress: SWAP_CONTRACT_ADDRESS,
>   chain: SWAP_CHAIN,
>   enabled: true,
> });
> const outputToken =
>   outputTokenState.type === "CONTENT" ? outputTokenState.outputToken : null;
>
> const parsed = parseBlockchainAmount(amountInput, INPUT_TOKEN.decimals);
> const hasAmount = parsed.valid && parsed.amount.raw > 0n;
> const inputAmount =
>   parsed.valid && parsed.amount.raw > 0n
>     ? parsed.amount
>     : BlockchainAmount({ raw: 0n, decimals: INPUT_TOKEN.decimals });
>
> const { state: quoteState } = useSwapQuote({
>   contractAddress: SWAP_CONTRACT_ADDRESS,
>   chain: SWAP_CHAIN,
>   inputAmount,
>   inputTokenAddress: INPUT_TOKEN_ADDRESS,
>   outputTokenDecimals: outputToken?.decimals ?? null,
>   enabled: authorized && hasAmount,
> });
>
> // A quote outlives a change of amount and being switched off. Input plus fee
> // is what the swap pulls. While a refresh is in flight, a quote that does not
> // price the amount on screen is the previous amount's. A settled quote may ask
> // for less (a partial fill: the rest stays in the wallet), never for more.
> const quote =
>   hasAmount && quoteState.type === "CONTENT" && quoteFits(quoteState)
>     ? quoteState.quote
>     : null;
>
> function quoteFits(state: { quote: SwapQuote; isRefreshing: boolean }): boolean {
>   const total = BlockchainAmount.add(state.quote.inputTokenAmount, state.quote.fee).raw;
>   return state.isRefreshing ? total === inputAmount.raw : total <= inputAmount.raw;
> }
> ```
>
> `quoteState` is `DISABLED` while switched off with no quote in hand, `LOADING` until the first quote lands (or while the output token's decimals are unknown), `ERROR` with a `reason` when no quote could be read at all, and `CONTENT` with `quote` and `isRefreshing` otherwise.
>
> A `SwapQuote` has `inputTokenAmount`, `fee`, and `outputTokenAmount`, all `BlockchainAmount`s. Render them with `formatAmount(amount, LOCALE)`, and derive the total and the slippage-protected minimum:
>
> ```tsx theme={null}
> const total = BlockchainAmount.add(quote.inputTokenAmount, quote.fee);
> const minReceived = computeSlip(quote.outputTokenAmount, DEFAULT_SLIPPAGE_BPS);
> ```
>
> > [!NOTE]
> >
> > The **fee comes out of the amount you quote**: `inputTokenAmount` is what buys shares, and `fee` is charged on top of it. The wallet is debited `inputTokenAmount + fee`, so always show that sum as the total cost.
>
> The quote refreshes every 15s; pass `pollIntervalMs` to change that. `isRefreshing` flags a newer quote on the way. A failed poll behind a quote in hand keeps the last quote, stays `CONTENT`, and retries on the next tick, so `ERROR` means the hook never got a quote. A quote also stays in `CONTENT` after you switch the hook off, and after the amount changes until the new quote lands, which is why the sample checks it against the amount before using it, the way the SDK's own review step does.
>
> ### Step 5: Execute the swap
>
> `passage.superstate.execute` runs the whole on-chain sequence and returns a discriminated result. It never throws.
>
> ```tsx theme={null}
> const result = await passage.superstate.execute({
>   wallet,
>   contractAddress: SWAP_CONTRACT_ADDRESS,
>   chain: SWAP_CHAIN,
>   inputTokenAddress: INPUT_TOKEN_ADDRESS,
>   quote,
>   slippageBps: DEFAULT_SLIPPAGE_BPS,
>   onProgress: (phase) => setBusy({ kind: "swap", phase }),
> });
>
> if (result.type === "success") {
>   // result: swapTxHash, inputAmount, fee, outputAmount, outputAmountConfirmed,
>   //   pricePerShare, recipientAddress
>   const amount = `${formatAmount(result.outputAmount, LOCALE)} ${outputToken.symbol}`;
>   const received = result.outputAmountConfirmed ? amount : `${amount} (estimated)`;
>   const explorerUrl = txExplorerUrl(SWAP_CHAIN, result.swapTxHash);
> } else {
>   // result.error.step: "status-check" | "swap-paused" | "swap-stopped" | "allowance-check"
>   //   | "approval" | "approval-reverted" | "swap" | "swap-unconfirmed" | "swap-reverted"
>   setError("The swap did not go through.");
> }
> ```
>
> Two of those steps need care before you offer a retry:
>
> * **`swap-unconfirmed`**: the wallet sent the swap, but waiting for its receipt failed. It may still mine, so swapping again can fill the order twice. It carries the `txHash` to look up first, and a `cause` of type `WalletError`. The SDK's own review step disables its button until the user leaves the step, with "Your swap was sent but has not confirmed yet. Check your wallet before placing another."
> * **`swap`** means the wallet never sent the swap (`cause` says why), so swapping again is safe, unless `cause.type` is `"disconnected"`: then the user has to reconnect first.
>
> `swap-paused` means the contract has suspended swaps and may resume, so "try again shortly" fits. `swap-stopped` is permanent.
>
> > [!WARNING]
> >
> > **Read `outputAmountConfirmed` before you show `outputAmount` to a user.** It is `true` when the amount is decoded from the on-chain `Swapped` event, and `false` when that event would not decode and the quote's estimate stands in. The swap mined either way, so the order is settled - but an estimate labeled as a confirmed fill is the one way this flow can misreport what happened. `pricePerShare` derives from the same number and carries the same caveat.
>
> Phases (wallet popups marked):
>
> `checking-status` → `checking-allowance` → *(`resetting-allowance` → `confirming-allowance-reset`, only for a non-zero allowance that does not cover `input + fee`)* → **`approving`** *(wallet popup)* → `confirming-approval` → **`swapping`** *(wallet popup)* → `confirming-swap`
>
> When the standing allowance already covers `input + fee`, the approval phases are skipped.
>
> > [!NOTE]
> >
> > The user signs up to **two transactions** - an ERC-20 `approve` for `input + fee` when the allowance does not already cover it, then the swap itself. When the wallet holds a non-zero allowance that does not cover the amount, the SDK first resets it to zero in one extra transaction, whatever the coin, because USDT-style tokens reject a non-zero to non-zero `approve`. All read-only checks run *before* the first popup, so the user never signs a transaction that those checks could have stopped.
>
> `slippageBps` sets the on-chain minimum-output guard. `DEFAULT_SLIPPAGE_BPS` is 0.5% and is fine for a minimal integration; see [Going further](#going-further) for a picker.
>
> ### Putting it together
>
> A complete, minimal swap component. It compiles against the current SDK release and reuses `constants.ts` (Step 1) and `buildEvmWallet` (Step 2).
>
> ```tsx MinimalSwap.tsx theme={null}
> "use client";
>
> import {
>   type SwapExecutionPhase,
>   usePassage,
>   useSwapOutputToken,
>   useSwapQuote,
>   type WalletAuthorizationPhase,
> } from "@passage-cl/react";
> import {
>   BlockchainAmount,
>   computeSlip,
>   DEFAULT_SLIPPAGE_BPS,
>   EvmWalletAddress,
>   formatAmount,
>   parseBlockchainAmount,
>   type SwapQuote,
>   txExplorerUrl,
> } from "@passage-cl/react/universal";
> import { useAppKit, useAppKitAccount } from "@reown/appkit/react";
> import { useEffect, useState } from "react";
> import { useConfig, useWalletClient } from "wagmi";
> import {
>   INPUT_TOKEN,
>   INPUT_TOKEN_ADDRESS,
>   LOCALE,
>   SWAP_CHAIN,
>   SWAP_CONTRACT_ADDRESS,
>   SWAP_OFFER_ID,
> } from "./constants";
> import { buildEvmWallet } from "./wagmiEvmWallet";
>
> type Busy =
>   | { kind: "authorize"; phase: WalletAuthorizationPhase }
>   | { kind: "swap"; phase: SwapExecutionPhase };
>
> const GENERIC_ERROR = "Something went wrong. Please try again.";
>
> export function MinimalSwap() {
>   const { passage, isReady } = usePassage();
>   const { open } = useAppKit();
>   const { address, isConnected } = useAppKitAccount();
>   const { data: walletClient } = useWalletClient();
>   const config = useConfig();
>
>   const [authorized, setAuthorized] = useState(false);
>   const [amountInput, setAmountInput] = useState("");
>   const [busy, setBusy] = useState<Busy | null>(null);
>   const [error, setError] = useState<string | null>(null);
>   const [confirmed, setConfirmed] = useState<{
>     received: string;
>     explorerUrl: string;
>   } | null>(null);
>
>   // The output token (the tokenized equity) tells us the decimals needed to quote.
>   const { state: outputTokenState, refetch: refetchOutputToken } =
>     useSwapOutputToken({
>       contractAddress: SWAP_CONTRACT_ADDRESS,
>       chain: SWAP_CHAIN,
>       enabled: true,
>     });
>   const outputToken =
>     outputTokenState.type === "CONTENT" ? outputTokenState.outputToken : null;
>
>   // Quoting stays disabled until the wallet is authorized, the output token is
>   // known, and the amount is a valid non-zero value.
>   const parsed = parseBlockchainAmount(amountInput, INPUT_TOKEN.decimals);
>   const hasAmount = parsed.valid && parsed.amount.raw > 0n;
>   const inputAmount =
>     parsed.valid && parsed.amount.raw > 0n
>       ? parsed.amount
>       : BlockchainAmount({ raw: 0n, decimals: INPUT_TOKEN.decimals });
>
>   const { state: quoteState } = useSwapQuote({
>     contractAddress: SWAP_CONTRACT_ADDRESS,
>     chain: SWAP_CHAIN,
>     inputAmount,
>     inputTokenAddress: INPUT_TOKEN_ADDRESS,
>     outputTokenDecimals: outputToken?.decimals ?? null,
>     enabled: authorized && hasAmount,
>   });
>   // A quote outlives a change of amount and being switched off. Input plus fee
>   // is what the swap pulls. While a refresh is in flight, a quote that does not
>   // price the amount on screen is the previous amount's. A settled quote may
>   // ask for less (a partial fill: the rest stays in the wallet), never for more.
>   const quoteFits = (fit: { quote: SwapQuote; isRefreshing: boolean }) => {
>     const total = BlockchainAmount.add(fit.quote.inputTokenAmount, fit.quote.fee).raw;
>     return fit.isRefreshing ? total === inputAmount.raw : total <= inputAmount.raw;
>   };
>   const quote =
>     hasAmount && quoteState.type === "CONTENT" && quoteFits(quoteState)
>       ? quoteState.quote
>       : null;
>   const isRefreshing = quoteState.type === "CONTENT" && quoteState.isRefreshing;
>
>   // If the connected account changes, the prior authorization no longer applies.
>   useEffect(() => {
>     setAuthorized(false);
>   }, [address]);
>
>   const buildWallet = () => {
>     if (!walletClient || !address) return null;
>     return buildEvmWallet({
>       address: EvmWalletAddress(address),
>       walletClient,
>       config,
>     });
>   };
>
>   const handleAuthorize = async () => {
>     const wallet = buildWallet();
>     if (!isReady || !wallet) return;
>     setError(null);
>     setBusy({ kind: "authorize", phase: "checking-authorization" });
>     try {
>       const result = await passage.superstate.authorizeWallet({
>         wallet,
>         offerId: SWAP_OFFER_ID,
>         contractAddress: SWAP_CONTRACT_ADDRESS,
>         chain: SWAP_CHAIN,
>         onProgress: (phase) => setBusy({ kind: "authorize", phase }),
>       });
>       if (result.type === "success") setAuthorized(true);
>       else setError(GENERIC_ERROR);
>     } catch {
>       setError(GENERIC_ERROR);
>     } finally {
>       setBusy(null);
>     }
>   };
>
>   const handleSwap = async () => {
>     const wallet = buildWallet();
>     if (!isReady || !wallet || !quote) return;
>     setError(null);
>     setBusy({ kind: "swap", phase: "checking-status" });
>     try {
>       const result = await passage.superstate.execute({
>         wallet,
>         contractAddress: SWAP_CONTRACT_ADDRESS,
>         chain: SWAP_CHAIN,
>         inputTokenAddress: INPUT_TOKEN_ADDRESS,
>         quote,
>         slippageBps: DEFAULT_SLIPPAGE_BPS,
>         onProgress: (phase) => setBusy({ kind: "swap", phase }),
>       });
>       if (result.type === "success" && outputToken) {
>         const amount = `${formatAmount(result.outputAmount, LOCALE)} ${outputToken.symbol}`;
>         setConfirmed({
>           received: result.outputAmountConfirmed ? amount : `${amount} (estimated)`,
>           explorerUrl: txExplorerUrl(SWAP_CHAIN, result.swapTxHash),
>         });
>       } else {
>         setError(GENERIC_ERROR);
>       }
>     } catch {
>       setError(GENERIC_ERROR);
>     } finally {
>       setBusy(null);
>     }
>   };
>
>   if (outputTokenState.type === "ERROR") {
>     return (
>       <div>
>         <p>Swaps are unavailable right now.</p>
>         <button onClick={refetchOutputToken}>Try again</button>
>       </div>
>     );
>   }
>
>   if (confirmed) {
>     return (
>       <div>
>         <h3>Swap complete</h3>
>         <p>You received {confirmed.received}.</p>
>         <a href={confirmed.explorerUrl} target="_blank" rel="noreferrer">
>           View transaction
>         </a>
>       </div>
>     );
>   }
>
>   if (!isConnected || !address) {
>     return <button onClick={() => open()}>Connect wallet</button>;
>   }
>
>   if (!authorized) {
>     return (
>       <div>
>         <button onClick={handleAuthorize} disabled={busy !== null || !walletClient}>
>           Authorize wallet
>         </button>
>         {busy?.kind === "authorize" && <p>{authorizePhaseLabel(busy.phase)}</p>}
>         {error && <p role="alert">{error}</p>}
>       </div>
>     );
>   }
>
>   const total = quote
>     ? BlockchainAmount.add(quote.inputTokenAmount, quote.fee)
>     : null;
>
>   return (
>     <div>
>       <input
>         inputMode="decimal"
>         placeholder={`Amount in ${INPUT_TOKEN.symbol}`}
>         value={amountInput}
>         onChange={(e) => {
>           if (e.target.value === "" || /^\d*\.?\d*$/.test(e.target.value)) {
>             setAmountInput(e.target.value);
>           }
>         }}
>       />
>
>       {quote && total && outputToken ? (
>         <dl>
>           <dt>You pay</dt>
>           <dd>
>             {formatAmount(quote.inputTokenAmount, LOCALE)} {INPUT_TOKEN.symbol}
>           </dd>
>           <dt>CoinList fee</dt>
>           <dd>
>             {formatAmount(quote.fee, LOCALE)} {INPUT_TOKEN.symbol}
>           </dd>
>           <dt>Total (charged to your wallet)</dt>
>           <dd>
>             {formatAmount(total, LOCALE)} {INPUT_TOKEN.symbol}
>           </dd>
>           <dt>You receive</dt>
>           <dd>
>             {formatAmount(quote.outputTokenAmount, LOCALE)} {outputToken.symbol}
>           </dd>
>           <dt>Minimum received</dt>
>           <dd>
>             {formatAmount(
>               computeSlip(quote.outputTokenAmount, DEFAULT_SLIPPAGE_BPS),
>               LOCALE,
>             )}{" "}
>             {outputToken.symbol}
>           </dd>
>         </dl>
>       ) : quoteState.type === "ERROR" ? (
>         <p role="alert">Could not fetch a quote. Retrying…</p>
>       ) : hasAmount ? (
>         <p>Fetching quote…</p>
>       ) : null}
>
>       <button
>         onClick={handleSwap}
>         disabled={!isReady || !quote || !walletClient || busy !== null}
>       >
>         Swap
>       </button>
>
>       {isRefreshing && <span> Refreshing quote…</span>}
>       {busy?.kind === "swap" && <p>{swapPhaseLabel(busy.phase)}</p>}
>       {error && <p role="alert">{error}</p>}
>     </div>
>   );
> }
>
> function authorizePhaseLabel(phase: WalletAuthorizationPhase): string {
>   switch (phase) {
>     case "signing-message":
>       return "Sign the message in your wallet…";
>     case "broadcasting-transaction":
>       return "Confirm the transaction in your wallet…";
>     default:
>       return "Authorizing…";
>   }
> }
>
> function swapPhaseLabel(phase: SwapExecutionPhase): string {
>   switch (phase) {
>     case "approving":
>       return `Approve ${INPUT_TOKEN.symbol} in your wallet…`;
>     case "swapping":
>       return "Confirm the swap in your wallet…";
>     default:
>       return "Working…";
>   }
> }
> ```
>
> The production-grade version - with balances, a slippage picker, per-step error copy, and a review screen - is `CheckoutContainer`, which the partner demo renders in [`OfferCheckoutView.tsx`](https://github.com/coinlist/partner-demo/blob/main/src/features/checkout/OfferCheckoutView.tsx).
>
> ### Going further
>
> * **Balances and a Max button** - `useErc20TokenBalances({ address, chain, assets: [USDC_SYMBOL], enabled })` returns `{ state }`. Its `CONTENT` arm carries `balances`, a `Map` of raw per-asset balances (`null` for a read that failed), so you can show the user's USDC and prefill the max amount. Balances refresh every 15s. It was `useSwapTokenBalances` before v0.11.0.
> * **A slippage picker** - `SLIPPAGE_OPTIONS_BPS` (0.25%-5%) with `formatBpsAsPercent(bps, LOCALE)` for labels; pass the selected `Bps` to `passage.superstate.execute`.
> * **A quote without React** - `passage.superstate.getQuote({ contractAddress, chain, inputToken, amount, outputTokenDecimals })` returns the same `SwapQuote` the hook polls, and `passage.superstate.getOutputToken({ contractAddress, chain })` the output token.
> * **More formatting helpers** in `@passage-cl/react/universal`: `shortenAddress`, `formattedPricePerShare`.

## Common questions

> [accordion] Why does the user sign a message before swapping?
>
> The flow has two identities: the OAuth **CoinList session** is *who* is buying, and the **external wallet** is *where* shares are delivered. `authorizeWallet` links them - the user signs an ownership challenge, and the SDK allow-lists that address on the swap contract. It's one-time per wallet per offer, and returns success immediately on later calls if the wallet is already authorized.

> [accordion] Why does my wallet ask for two transactions?
>
> A swap needs an ERC-20 `approve` (for `input + fee`) before the swap itself, so the contract can pull the stablecoin. A wallet that already holds a non-zero allowance too small for the swap needs one extra reset-to-zero transaction first, because USDT-style tokens reject a non-zero to non-zero `approve`. Every read-only check (status, allowance) runs before the first popup, so the user never signs a transaction that those checks could have stopped.

> [accordion] How fresh is the quote, and what if the price moves?
>
> `useSwapQuote` polls every 15s. On execution, `passage.superstate.execute` passes a slippage-derived minimum output to the contract, so if the price moves beyond your `slippageBps` the swap reverts rather than over-charging. The result's `outputAmount` is decoded from the on-chain `Swapped` event when the receipt yields one, and falls back to the quote's estimate when it does not - `outputAmountConfirmed` tells you which one you got.

> [accordion] Do I need wagmi / Reown AppKit specifically?
>
> No. Anything implementing the five-member `EvmWallet` interface works - viem directly, Privy, ethers with a thin adapter. The SDK only calls `signMessage`, `writeContract`, `broadcastRawTx`, and `awaitTx`; it never sees your wallet library.

> [accordion] How do I go to mainnet?
>
> This page uses Sepolia everywhere, and the SDK knows the Sepolia swap contract only. CoinList provides the production swap contract address and swap offer ID during onboarding. Set `SWAP_CHAIN` to `"ethereum_mainnet"`, point `SWAP_CONTRACT_ADDRESS` at the mainnet contract, and the wallet adapter's `CHAINS` map handles the network switch. `CheckoutContainer` runs on mainnet once the SDK ships that contract.

## Next step

> [card] [See the checkout in the partner demo](https://github.com/coinlist/partner-demo/tree/main/src/features/checkout)
>
> The partner demo's checkout feature renders `CheckoutContainer` with its own wallets.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.