{ + try { + return await engine.quote(params); + } catch (err) { + if ( + err instanceof RouteUnavailableError && + err.reason === "recipient_not_deployed" + ) { + if (!(await payerConfirms(params.recipient.address))) return null; + return engine.quote({ ...params, allowUndeployedRecipient: true }); + } + throw err; + } +} +``` + +`` does this itself: it shows a warning with an "It's my wallet, continue" button, then quotes again with the flag for that address only. + +`engine.maxSendable` skips these checks, since it only works out fees, and so does the fresh quote `send` builds when fees rise, since the payer already confirmed that recipient. + +Before the burn on a bridge into Starknet, Whisk also checks that the destination Starknet wallet is on the destination's chain id, else the failure is a `WrongChainError`. + +## The resolved recipient + + + The destination address. For Solana it is the wallet; Whisk derives the USDC + account. + ++ The destination chain the address was resolved for. + ++ Optional label, such as the ENS name or handle the payer typed. + + +`ResolvedRecipient` also has `needsClaimLink` and `claimToken`, reserved for resolvers that create a wallet for an off-platform recipient. Nothing in 0.3 sets or reads them. + +## Related + ++ diff --git a/concepts/recovery.mdx b/concepts/recovery.mdx new file mode 100644 index 0000000..a57cc00 --- /dev/null +++ b/concepts/recovery.mdx @@ -0,0 +1,227 @@ +--- +title: Recovery +description: How a bridge that stopped between the burn and the mint gets finished, after a closed tab, a slow attestation or a failed mint. +--- + +Once a bridge's burn is signed, the USDC has left the payer's wallet and only a mint on the destination delivers it. Whisk keeps a record of every bridge from the moment it is signed, so a transfer that stops part way can be finished later without burning again. + +```ts +import { + createStorageInflightStore, + createWhisk, + type WhiskAdapter, +} from "@usewhisk/core"; + +declare const destinationAdapter: WhiskAdapter | undefined; + +const engine = createWhisk({ + chains: ["Base_Sepolia", "Arc_Testnet", "Solana_Devnet"], + inflightStore: createStorageInflightStore(window.localStorage), +}); + +for (const record of await engine.inflight()) { + if (record.step === "minted") { + await engine.dismiss(record.id); + continue; + } + const result = await engine.resume( + record, + destinationAdapter ? { destinationAdapter } : {}, + ); + if (result.kind === "success") await engine.dismiss(record.id); + else console.warn(record.id, result.error.message); +} +``` + +## In-flight records + +`send` writes an `InflightRecord` to the engine's `inflightStore` for every bridge. Same-chain sends have no record; they settle in one transaction. + +| `step` | When it is written | +| ---------- | --------------------------------------------------------------------------------- | +| `signing` | Before the wallet is asked for anything. | +| `burned` | The moment the wallet returns the burn hash, before any wait for a receipt. | +| `attested` | When Circle's attestation arrives. | +| `minted` | When the recipient has the USDC. `mintTxHash` is set when the mint hash is known. | + +A record also holds the network, the source and destination chains, who mints (`"forwarder"` or `"adapter"`), the speed, the amount burned (a 6-decimal subunit string) and the recipient. Its `id` is the id of the quote it was sent from. + +If `send` ends before a burn hash was recorded (the payer rejected the wallet prompt, or a check failed), the record is removed. A record with a burn hash is never removed by Whisk on its own. It stays until you call `engine.dismiss(id)`, even after it reaches `minted`, so the payer can see the transfer finish. + +`engine.inflight()` lists the records, oldest first. + +## Stores + +`InflightStore` is a three-method interface: `put`, `list` and `remove`. Whisk ships three: + +- **`createMemoryInflightStore()`**, the `createWhisk` default. Records last as long as the engine, so a reload loses them. +- **`createStorageInflightStore(storage)`** keeps each record as JSON under `whisk:inflight:+ Every check that runs before the burn. + ++ Supported chains per ecosystem. + +` in any Web Storage object, such as `localStorage`. It ignores entries under that prefix that are not valid version 2 records. +- **`createBrowserInflightStore()`**, from `@usewhisk/react`, uses `localStorage` when the page can write to it and falls back to memory when it cannot (Safari private browsing, server rendering). ` ` uses it unless you pass `inflightStore` in the config. + +Write your own store to keep records on a server, for example keyed by the payer's account, so a transfer can be finished from another device. + + + With the memory store, a closed tab loses the record. The USDC is still safe + on the attested message, but the payer needs the burn hash from their wallet + history to finish the transfer with `resumeFromTx`. Pass a persistent store + wherever you can. + + +## Resume and dismiss + +`engine.resume(record, options?, listeners?)` finishes a transfer from its record: + +1. On an EVM source it reads the burn's status. A reverted burn moved no USDC, so the record is removed and `resume` returns a failure saying so. +2. It polls Iris until the burn is attested, then checks the attested message against the record: the destination domain and the burned amount must match, or it returns a failure instead of minting. +3. If Circle forwards the mint, it waits for the forwarder. If the forwarder reports `FAILED`, it falls back to a wallet mint. +4. Before a wallet mint it checks whether the destination already received the message (on EVM, whether the message nonce is used). If so, it marks the record `minted` without signing anything. +5. It mints with `options.destinationAdapter`. An attestation that expired is re-attested by Circle once, and the mint tried again. + +`resume` returns a `SendResult` like `send`. A failure with `retryable: true` (Circle has not attested yet, or the forwarder has not minted yet) means "try again later", not "something is wrong". + +A wallet mint on an EVM destination without an EVM `destinationAdapter` throws `RouteUnavailableError` with `reason: "destination_adapter_required"`. Connect a wallet on the destination chain and resume again; any EVM wallet can submit the mint, and the USDC still goes to the recorded recipient. + +`engine.dismiss(id)` removes a record. Call it once the payer has seen the transfer finish, or chooses to drop it. Dismissing does not touch any funds; a burned transfer can still be finished later with `resumeFromTx`. + +## ResumeList + +`` renders every record in the engine's store with Resume and Dismiss buttons. It picks the destination wallet for the record's chain from the connected wallets. ` ` renders one above the form, so a payer who reloads mid-transfer sees it on return. Render it on its own anywhere inside ` `: + +```tsx +import { ResumeList } from "@usewhisk/react"; + +export function PendingTransfers() { + return ; +} +``` + +It reads the store once, when it mounts, and renders nothing when there are no records. A transfer that fails after the burn in the same session appears in the list after the component remounts. + + + In 0.3, ` + +See [ResumeList](/widget/resume-list) for details. + +## When the tab closes mid-transfer + +| Closed while... | What happened to the USDC | How to finish | +| ----------------------------------------------- | ------------------------------------------- | --------------------------------------------------------- | +| the wallet prompt was open, before signing | Nothing moved. | Nothing to finish. The `signing` record can be dismissed. | +| the wallet was submitting the burn | It may have burned; the record has no hash. | Find the burn hash in the wallet and call `resumeFromTx`. | +| waiting for the burn receipt or the attestation | Burned. | `resume` the `burned` record. | +| waiting for the forwarder or the wallet mint | Burned and attested. | `resume` the record. | + +A `signing` record passed to `resume` returns a failure that says no burn was recorded and points at `resumeFromTx`. No merchant fee was taken for it: the fee is only sent with the burn or after it. + +A record for a transfer with a `feePolicy` fee keeps the fee's amount, status and hashes as `customFee`. `resume` reports it on the result's `customFee` and never asks the payer for the fee again, even when it was not paid. + +## resumeFromTx + +`engine.resumeFromTx({ sourceChain, txHash, destinationAdapter? })` finishes a transfer from the burn hash alone, such as a hash from a receipt link or the payer's wallet history. If the store already has a record for that hash it uses it; otherwise it builds one from what Iris decoded from the burn (destination, amount, recipient, speed, whether it was forwarded), saves it, and resumes. + +```ts +import { createWhisk, type EvmAdapter } from "@usewhisk/core"; + +declare const arcWallet: EvmAdapter; + +const engine = createWhisk({ chains: ["Stellar", "Arc"] }); + +const result = await engine.resumeFromTx({ + sourceChain: "Stellar", + txHash: "9f2c...burn-hash-from-the-wallet", + destinationAdapter: arcWallet, +}); +``` + +Until Iris has seen the burn, `resumeFromTx` throws a retryable `BridgeStepError`. Call it again after a few seconds. + +## When the forwarder fails + +Circle's forwarder spends its fee on destination gas. If gas rises past that fee, or the relayer fails for another reason, Iris reports the forward as `FAILED` or leaves it pending. The attested message is still valid, and anyone can submit it, because Whisk leaves `destinationCaller` empty on every burn into an EVM chain. + +- `send` falls back to a wallet mint when Iris reports `FAILED`. With no `destinationAdapter` on an EVM to EVM route, the source wallet switches chain and signs it. +- If the forwarder is still pending when `send` stops polling, `send` returns a failure on the `mint` step with category `polling_timeout`. The record stays `attested`; `resume` waits for the forwarder again, and mints with the wallet if it has failed by then. + +## Manual mint without the engine + +For a support tool, or a page that only has a burn hash, `@usewhisk/core` exports the pieces on their own: + +- `fetchAttestationOnce(sourceChain, burnTxHash, options?)` returns the Iris status (`"not_found"`, `"pending_confirmations"` or `"complete"`), with `message` and `attestation` once complete; +- `pollAttestation(sourceChain, burnTxHash, options?)` polls every 3 seconds for up to 10 minutes by default; +- `buildReceiveMessageCall(destinationChain, message, attestation)` returns a `receiveMessage` call for an EVM destination, or `null` for any other ecosystem. + +```ts +import { buildReceiveMessageCall, fetchAttestationOnce } from "@usewhisk/core"; +import type { Account, Chain, Hex, WalletClient } from "viem"; + +declare const walletClient: WalletClient; +declare const account: Account; +declare const arc: Chain; +declare const burnTxHash: string; + +const attested = await fetchAttestationOnce("Base", burnTxHash, { + baseUrl: "https://iris-proxy.example.com", +}); + +if ( + attested.status === "complete" && + attested.message && + attested.attestation +) { + const call = buildReceiveMessageCall( + "Arc", + attested.message, + attested.attestation, + ); + if (call) { + const [message, attestation] = call.args; + await walletClient.writeContract({ + account, + chain: arc, + address: call.address as Hex, + abi: call.abi, + functionName: call.functionName, + args: [message as Hex, attestation as Hex], + }); + } +} +``` + +`ReceiveMessageCall` types `address` and `args` as plain strings, so viem needs the casts to `Hex` shown above. These helpers do not re-attest an expired attestation or check whether the message was already received; `engine.resume` and `resumeFromTx` do both. + +## Pointing recovery at another Iris host + +`fetchAttestationOnce` and `pollAttestation` take `baseUrl`, which replaces the Iris host chosen from the source chain's network. Use it to route recovery through your own proxy. `IRIS_MAINNET_URL` and `IRIS_SANDBOX_URL` are exported, and `getIrisBaseUrl(chain)` returns the default for a chain. + +The engine has no `baseUrl` option. To send its Iris requests (including those made by `resume` and `resumeFromTx`) through a proxy, pass a `fetch` to `createWhisk` that rewrites the URL: + +```ts +import { createWhisk } from "@usewhisk/core"; + +const engine = createWhisk({ + chains: ["Base", "Arc"], + fetch: (input, init) => { + const url = new URL( + input instanceof Request ? input.url : input.toString(), + ); + if (url.hostname === "iris-api.circle.com") { + url.hostname = "iris-proxy.example.com"; + } + return fetch(url, init); + }, +}); +``` + +`WhiskClientConfig` in `@usewhisk/react` has no `fetch` option in 0.3, so this needs the core engine. + +## Related + +` shows the amount of a transfer from Stellar at one tenth of its value: it formats the 6-decimal record with Stellar's 7 decimals. The record, the resume and the mint use the correct amount. + + diff --git a/docs.json b/docs.json new file mode 100644 index 0000000..7f965ea --- /dev/null +++ b/docs.json @@ -0,0 +1,181 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "willow", + "name": "Whisk", + "description": "Stablecoin payments SDK. Send and bridge USDC over Circle CCTP V2 across EVM chains, Solana, Stellar and Starknet.", + "colors": { + "primary": "#2b3cff", + "light": "#2b3cff", + "dark": "#2b3cff" + }, + "background": { + "color": { + "light": "#fbfaf7", + "dark": "#fbfaf7" + } + }, + "appearance": { + "default": "light", + "strict": true + }, + "fonts": { + "family": "Geist" + }, + "logo": { + "light": "/logo/whisk.png", + "dark": "/logo/whisk.png", + "href": "https://usewhisk.xyz" + }, + "favicon": "/favicon.png", + "navbar": { + "links": [ + { + "label": "npm", + "href": "https://www.npmjs.com/org/usewhisk" + } + ], + "primary": { + "type": "github", + "href": "https://github.com/usewhisk/whisk" + } + }, + "footer": { + "socials": { + "github": "https://github.com/usewhisk" + } + }, + "contextual": { + "options": ["copy", "view", "chatgpt", "claude"] + }, + "navigation": { + "tabs": [ + { + "tab": "Docs", + "groups": [ + { + "group": "Get started", + "pages": [ + "index", + "quickstart", + "installation", + "wallets", + "chains", + "rpc" + ] + }, + { + "group": "Concepts", + "pages": [ + "concepts/how-it-works", + "concepts/amounts-and-units", + "concepts/quotes-and-fees", + "concepts/recovery", + "concepts/recipients", + "concepts/errors", + "concepts/fund-safety" + ] + }, + { + "group": "Widget", + "pages": [ + "widget/whisk-provider", + "widget/whisk-send", + "widget/whisk-receipt", + "widget/resume-list", + "widget/connect-modal", + "widget/primitives" + ] + }, + { + "group": "Theming", + "pages": [ + "theming/overview", + "theming/tokens", + "theming/tailwind", + "theming/fonts" + ] + }, + { + "group": "Hooks", + "pages": [ + "hooks/use-whisk", + "hooks/use-receipt", + "hooks/use-refund", + "hooks/wallet-adapters", + "hooks/use-whisk-engine" + ] + }, + { + "group": "Headless", + "pages": [ + "headless/core-engine", + "headless/react-headless", + "headless/server", + "headless/vue" + ] + }, + { + "group": "Payment flows", + "pages": [ + "flows/checkout", + "flows/receipts", + "flows/refunds", + "flows/metadata" + ] + }, + { + "group": "Recipes", + "pages": [ + "recipes/donate-button", + "recipes/ecommerce-checkout", + "recipes/invoice-link", + "recipes/payroll-batch", + "recipes/themed-saas" + ] + } + ] + }, + { + "tab": "Reference", + "groups": [ + { + "group": "@usewhisk/react", + "pages": [ + "reference/react/config", + "reference/react/components", + "reference/react/hooks" + ] + }, + { + "group": "@usewhisk/core", + "pages": [ + "reference/core/create-whisk", + "reference/core/engine", + "reference/core/types", + "reference/core/errors" + ] + }, + { + "group": "@usewhisk/cctp", + "pages": [ + "reference/cctp/overview", + "reference/cctp/chains", + "reference/cctp/builders", + "reference/cctp/iris", + "reference/cctp/fees" + ] + } + ] + }, + { + "tab": "Migration", + "groups": [ + { + "group": "Upgrade guides", + "pages": ["migration/0-2-to-0-3", "migration/0-1-to-0-2"] + } + ] + } + ] + } +} diff --git a/favicon.png b/favicon.png new file mode 100644 index 0000000..61a1801 Binary files /dev/null and b/favicon.png differ diff --git a/flows/checkout.mdx b/flows/checkout.mdx new file mode 100644 index 0000000..e9d6387 --- /dev/null +++ b/flows/checkout.mdx @@ -0,0 +1,372 @@ +--- +title: Checkout +description: Take a fixed-price USDC payment for an order and confirm it on your server before you fulfil. +--- + +A checkout locks three things the payer must not change: who gets paid, how +much, and on which chain. Lock them on `+ What Whisk guarantees about the payer's money, and where the gaps are. + ++ Showing a transfer's status from its burn hash. + +` and report the result to +your server: + +```tsx PayForOrder.tsx +import { useState } from "react"; +import { WhiskSend, type SendSuccess } from "@usewhisk/react"; + +const MERCHANT_ADDRESS = "0x5B8ecaB7096F8aBED873D246629ef9f05f467605"; + +export function PayForOrder({ + orderId, + total, +}: { + orderId: string; + total: string; +}) { + const [error, setError] = useState (null); + + function onSuccess(result: SendSuccess) { + const burn = result.steps.find((step) => step.name === "burn"); + fetch(`/api/orders/${orderId}/paid`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + finalTxHash: result.finalTxHash, + burnTxHash: burn?.txHash, + }), + }).catch(() => setError("Paid, but we could not reach the store.")); + } + + return ( + <> + + {error && {error}
} + > + ); +} +``` + +The component must sit inside a [``](/widget/whisk-provider). +`total` is a decimal USDC string such as `"42.50"`, the same string the payer +sees in the amount field. + +## Lock the order + +`amount`, `recipient`, `sourceChain` and `destinationChain` are controlled +props: when you pass one, the field shows that value and ignores edits. The +`default*` versions only seed a field the payer can still change, so never use +them for a price or a merchant address. + +Pick one of two shapes: + +| Shape | Props | What happens | +| ----------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Cross-chain | `tabs={["bridge"]}`, `destinationChain` | The payer picks any source chain on the same network; you receive on one. | +| Same chain | `tabs={["send"]}`, `sourceChain` and `destinationChain` set to the same chain | A plain USDC transfer on one chain, no CCTP, no bridge fees. | + + + On the Send tab the destination is whatever source chain the payer picked. If + you leave both tabs visible and only lock `destinationChain`, a payer on the + Send tab pays your address on their own chain. That is only safe when your + address can receive on every chain in the config (a contract wallet deployed + on one chain cannot). + + +The network (mainnet or testnet) follows the source chain. A bridge never +crosses networks: quoting a mainnet source against a testnet destination +throws `NetworkMismatchError` before anything is signed. + +## What the merchant receives + +Who pays the bridge fees is set once, on the config, with `feeBearer`. There is +no per-widget override. + +```ts +import { createWhiskConfig, evm } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Arc_Testnet", "Base_Sepolia", "Ethereum_Sepolia"], + feeBearer: "sender", +}); +``` + +| `feeBearer` | Payer is debited | Merchant receives | +| -------------------- | ----------------------------------------- | -------------------------------------------- | +| `"sender"` (default) | `amount` plus the CCTP and Forwarder fees | at least `amount` | +| `"receiver"` | `amount` | `amount` less the fees, at least `amountOut` | + +For a checkout keep the default. The burn is sized up so the merchant nets the +full price, and the quote shows the payer the total as "You pay" +(`quote.amountIn`). With `"receiver"`, a 42.50 order arrives short by the +bridge fees, and a total too small to cover them fails to quote. + +A same-chain transfer has no CCTP fees, so `feeBearer` does not apply: the +merchant receives exactly `amount`. A `feePolicy` merchant fee is always paid by +the payer on top, whatever `feeBearer` says. See +[quotes and fees](/concepts/quotes-and-fees) for the fee lines. + +## Confirm the payment + +`onSuccess` receives a `SendSuccess`: + ++ The transaction that put the USDC in the merchant's wallet. For a same-chain + send it is the transfer on that chain. For a bridge it is the mint on the + destination chain. It can be missing when Circle's Forwarder minted and Iris + did not return the mint hash. + + ++ Every step with its state and tx hash. The `burn` step's `txHash` is the + source-chain burn, which is what [receipts](/flows/receipts) and + `resumeFromTx` take. + + ++ The metadata passed to `send`, merged with config defaults. ` + +` has + no `metadata` prop, so through the widget this is always undefined. + + Set when a `feePolicy` charged the payer, on EVM sources. `status: "paid"` + means the fee landed; `"unpaid"` means the payment went through but the payer + rejected the fee request, or it reverted. A wallet without atomic batches asks + for the fee after the payment, so the payer can decline it. If your fee is + part of the price, check this before you fulfil. See [when the fee is + paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + + +`onFailure` receives a `SendFailure` with `error` and `steps`. If the `burn` +step succeeded, the payer's USDC has left their wallet and is in flight. Do +not tell them the payment failed: show a [``](/widget/whisk-receipt) +or the [` `](/widget/resume-list) so they can finish the mint. See +[recovery](/concepts/recovery). + +## Attach order metadata + +To tag the payment with your order id, build the flow with +[`useWhisk`](/hooks/use-whisk) and pass `metadata` to `send`. The hook signs +with the connected EVM wallet. + +```tsx Checkout.tsx +import { useState } from "react"; +import { + QuoteChangedError, + QuoteExpiredError, + toWhiskError, + useWhisk, + type Quote, +} from "@usewhisk/react"; +import { reportBurn, reportPaid } from "./api"; + +const MERCHANT_ADDRESS = "0x5B8ecaB7096F8aBED873D246629ef9f05f467605"; + +export function Checkout({ + orderId, + total, +}: { + orderId: string; + total: string; +}) { + const { quote, send, isConnected, isSending } = useWhisk(); + const [pending, setPending] = useState (null); + const [error, setError] = useState(null); + + async function review() { + setError(null); + try { + setPending( + await quote({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient: { address: MERCHANT_ADDRESS, chain: "Base_Sepolia" }, + amount: total, + }), + ); + } catch (err) { + setError(toWhiskError(err, "Could not price this order.").message); + } + } + + async function pay(confirmed: Quote) { + setError(null); + try { + const result = await send( + { quote: confirmed, metadata: { orderId, source: "checkout" } }, + { + onBurnSubmitted: (txHash) => { + reportBurn(orderId, txHash).catch(console.error); + }, + }, + ); + if (result.kind === "success") await reportPaid(orderId, result); + else setError(result.error.message); + } catch (err) { + if (err instanceof QuoteChangedError) setPending(err.quote); + if (err instanceof QuoteExpiredError) setPending(null); + setError(toWhiskError(err, "The payment did not go through.").message); + } + } + + if (!isConnected) return Connect a wallet to pay.
; + + return ( ++ {pending ? ( + + ) : ( + + )} + {error &&+ ); +} +``` + +A few things this does that the widget does for you: + +- The payer sees `quote.amountIn` before signing. `send` signs exactly that + quote. +- A quote expires after about a minute. `send` throws `QuoteExpiredError` for + a stale one and `QuoteChangedError` when Circle's fees rose past it; + `err.quote` is the fresh quote to show. +- `onBurnSubmitted` fires with the burn hash before any receipt wait. Saving it + against the order there means a closed tab mid-bridge still leaves you a hash + to look up. + +{error}
} ++ Metadata stays in the browser. It is not written on chain, not sent to Circle, + not kept in the in-flight record, and Whisk has no server that receives it. It + comes back on the `SendResult` so your own code can tell which order a result + belongs to. See [metadata](/flows/metadata). + + +## Verify on your server + +Everything the browser posts is a claim. A payer can call your endpoint with +any hash, replay one from an earlier order, or pay on testnet and claim +mainnet. Whisk 0.3 does not notify your server, so your server checks the +chain itself before it fulfils. + +Take the chain, merchant address and amount from your order record, never from +the request, then read the transaction: + +```ts verify-payment.ts +import { + createPublicClient, + erc20Abi, + http, + isAddressEqual, + parseEventLogs, + type Address, + type Hash, +} from "viem"; +import { getChain, parseUsdcAmount, type Chain } from "@usewhisk/core"; + +export type ExpectedPayment = { + chain: Chain; + merchant: Address; + amount: string; +}; + +export async function verifyPayment( + expected: ExpectedPayment, + txHash: Hash, +): Promise{ + const chain = getChain(expected.chain); + if (chain.ecosystem !== "evm") { + throw new Error(`${chain.label} is not an EVM chain`); + } + const client = createPublicClient({ + transport: http(chain.defaultRpcUrls[0]), + }); + const receipt = await client.waitForTransactionReceipt({ + hash: txHash, + confirmations: 2, + }); + if (receipt.status !== "success") return false; + + const received = parseEventLogs({ + abi: erc20Abi, + eventName: "Transfer", + logs: receipt.logs, + }) + .filter( + (log) => + isAddressEqual(log.address, chain.usdc) && + isAddressEqual(log.args.to, expected.merchant), + ) + .reduce((sum, log) => sum + log.args.value, 0n); + + return received >= parseUsdcAmount(expected.amount); +} +``` + +This works for both shapes. A same-chain payment is a USDC `Transfer` from the +payer to the merchant; a bridge mint is a `Transfer` from the zero address to +the merchant. In both, the amount is compared in 6-decimal `bigint` subunits. +Use your own RPC in production rather than the chain's public default. + +The route handler then refuses anything it cannot prove and flips the order +once: + +```ts route.ts +import type { Hash } from "viem"; +import { verifyPayment, type ExpectedPayment } from "./verify-payment"; + +type Order = ExpectedPayment & { id: string; status: "pending" | "paid" }; + +declare const db: { + findOrder(id: string): Promise ; + isTxUsed(txHash: string): Promise ; + markPaid(id: string, txHash: string): Promise ; +}; + +export async function POST(req: Request, orderId: string) { + const { finalTxHash } = (await req.json()) as { finalTxHash?: Hash }; + const order = await db.findOrder(orderId); + if (!order || order.status !== "pending" || !finalTxHash) { + return Response.json({ ok: false }, { status: 400 }); + } + if (await db.isTxUsed(finalTxHash)) { + return Response.json({ ok: false }, { status: 409 }); + } + if (!(await verifyPayment(order, finalTxHash))) { + return Response.json({ ok: false }, { status: 402 }); + } + const first = await db.markPaid(order.id, finalTxHash); + return Response.json({ ok: true, fulfilled: first }); +} +``` + +- `isTxUsed` stops one payment from settling two orders. Store the hash with a + unique index. +- `markPaid` should be a conditional update (`where status = 'pending'`) so two + concurrent requests cannot both fulfil. +- When `finalTxHash` is missing (a forwarded mint whose hash Iris did not + return), keep the order pending with its burn hash and match it later + against USDC `Transfer` logs to the merchant on the destination chain. + +## Related + + + diff --git a/flows/metadata.mdx b/flows/metadata.mdx new file mode 100644 index 0000000..3ab9083 --- /dev/null +++ b/flows/metadata.mdx @@ -0,0 +1,141 @@ +--- +title: Metadata +description: Tag a send with your own correlation keys, and know exactly where those keys go. +--- + +Metadata is a flat object of your own keys, such as an order id or a campaign +code, that you pass to `send` and get back on the result: + +```ts +import { createWhisk, type EvmAdapter, type Quote } from "@usewhisk/core"; + +declare const adapter: EvmAdapter; +declare const quote: Quote; + +const engine = createWhisk({ + chains: ["Arc_Testnet", "Base_Sepolia"], + defaultMetadata: { source: "web", env: "staging" }, +}); + +const result = await engine.send({ + quote, + adapter, + metadata: { orderId: "ord_123", env: "prod" }, +}); + +console.log(result.metadata); +``` + +That logs `{ source: "web", env: "prod", orderId: "ord_123" }`. Per-call keys +win over `defaultMetadata` when both set the same key. + +## Where metadata goes + +Metadata never leaves the engine that was given it. In 0.3: + +| Place | Has metadata? | +| ------------------------------------------- | --------------------------------------------------------------------------------- | +| `SendResult.metadata` (success and failure) | Yes | +| `RefundResult.metadata` | Yes, plus the refund keys | +| The burn or transfer transaction | No | +| CCTP `hookData` | No. Whisk only writes Circle's Forwarder marker and, into Stellar, the recipient. | +| Circle's Iris API | No | +| The in-flight record (`InflightRecord`) | No | +| The result of `resume` or `resumeFromTx` | No | +| Any Whisk server | No. Whisk 0.3 runs no server and calls none of yours. | + +So metadata answers one question: which of your orders does this result +belong to? It does not let anyone else, including your server, tie a +transaction on chain back to an order. Your code has to send the order id and +the tx hashes to your server itself, ideally from `onBurnSubmitted` as well as +on success. See [checkout](/flows/checkout). + +Two consequences worth planning for: + +- If the payer reloads mid-bridge and finishes from the + [`+ Show settlement status from a burn hash. + ++ Send a payment back to the payer. + ++ A full shop, cart and checkout example. + ++ What Whisk checks before it burns. + +`](/widget/resume-list), the resumed result has no metadata. + Keep your own map from order id to burn hash. +- If `send` throws instead of returning a failure (an expired quote, a fee + rise, too little balance), there is no result and so no metadata on it. + + + Metadata passes through the payer's browser and anyone with dev tools can read + or change it. Do not put emails, names, addresses or anything sensitive in it, + and do not trust it on the way back. It is a label, not a proof. + + +## Rules + +`validateMetadata` enforces them, and `send` runs it before it checks the quote +or asks for a signature. `createWhisk` runs it on `defaultMetadata` when the +engine is created. Any break throws `ConfigError`. + +- A plain object. Not `null`, not an array. +- Keys are non-empty strings and do not start with `__` + (`METADATA_RESERVED_PREFIX`). That prefix is kept for Whisk's own keys, such + as the refund links. +- Values are `string`, `number` or `boolean`. No nested objects or arrays. +- Numbers are finite: no `NaN` or `Infinity`. +- The JSON-serialized object is at most 1024 bytes (`METADATA_MAX_BYTES`), + counted as UTF-8, so a 4-byte emoji costs 4. + +An empty object passes. + +```ts check-metadata.ts +import { + ConfigError, + validateMetadata, + type WhiskMetadata, +} from "@usewhisk/react"; + +export function checkMetadata( + input: unknown, +): { ok: true; metadata: WhiskMetadata } | { ok: false; reason: string } { + try { + validateMetadata(input); + return { ok: true, metadata: input }; + } catch (err) { + if (err instanceof ConfigError) return { ok: false, reason: err.message }; + throw err; + } +} +``` + +`validateMetadata` is a TypeScript assertion function: after it returns, +`input` is typed `WhiskMetadata`. + +## Defaults and merging + +`WhiskConfig.defaultMetadata` is merged into every `send` and `refund` of a +core engine. The merge is `mergeMetadata(defaults, perCall)`: a shallow spread +where per-call keys win, returning `undefined` when both are empty. When +neither is set, `result.metadata` is absent rather than `{}`. + ++ The React config from `createWhiskConfig` has no `defaultMetadata` option in + 0.3, so ` + +```ts order-metadata.ts +import { mergeMetadata, type WhiskMetadata } from "@usewhisk/react"; + +const APP_METADATA: WhiskMetadata = { app: "atelier", release: "2026.10" }; + +export function orderMetadata(orderId: string) { + return mergeMetadata(APP_METADATA, { orderId }); +} +``` + +## Where you can pass it + +| API | Metadata | +| ------------------------------------------- | ----------------------------------------- | +| `engine.send({ quote, adapter, metadata })` | Yes | +| `useWhisk().send({ quote, metadata })` | Yes | +| `engine.refund` and `useRefund` | Yes, as `metadata` on the refund input | +| `` cannot set one + ([usewhisk/whisk#156](https://github.com/usewhisk/whisk/issues/156)). Merge + your defaults yourself before each call. + ` | No prop. Use `useWhisk` to tag a payment. | +| `engine.resume`, `engine.resumeFromTx` | No | + +The type is `WhiskMetadata = Record `. diff --git a/flows/receipts.mdx b/flows/receipts.mdx new file mode 100644 index 0000000..25ddf22 --- /dev/null +++ b/flows/receipts.mdx @@ -0,0 +1,249 @@ +--- +title: Receipts +description: Show where a transfer stands from its source-chain tx hash, in the widget, in your own UI, or on a server. +--- + +A receipt needs three things: the source chain, the source-chain tx hash, and +the destination chain. `deriveReceiptView` turns those, plus Circle's latest +attestation status, into a stage and a list of steps: + +```ts +import { deriveReceiptView, RECEIPT_STAGE_LABELS } from "@usewhisk/core"; + +const view = deriveReceiptView({ + sourceChain: "Base_Sepolia", + sourceTxHash: + "0x8a3f5c0e2b7d4a91c6e0f3b2d5a8c7e1f0b9a6d3c2e5f8a1b4d7c0e3f6a9b2c5", + destinationChain: "Arc_Testnet", + irisStatus: "pending_confirmations", +}); + +console.log(view.stage); +console.log(RECEIPT_STAGE_LABELS[view.stage]); +console.log(view.sourceExplorerUrl); +``` + +That prints `awaiting_attestation`, `Confirming on source chain` and a Base +Sepolia explorer link. `deriveReceiptView` does no I/O: you call it again with +a fresher `irisStatus` to move the view forward. The React pieces below do the +polling for you. + +## Build a receipt page + +A receipt link only has to carry the hash and the two chains. Build it from the +`SendSuccess` you got at payment time. For a bridge the hash is on the `burn` +step; for a same-chain send it is on the `transfer` step. + +```ts receipt-link.ts +import type { Chain, SendSuccess } from "@usewhisk/react"; + +export function receiptLink( + result: SendSuccess, + sourceChain: Chain, + destinationChain: Chain, +): string { + const burn = result.steps.find( + (step) => step.name === "burn" || step.name === "transfer", + ); + const url = new URL("/receipt", window.location.origin); + url.searchParams.set("tx", burn?.txHash ?? ""); + url.searchParams.set("from", sourceChain); + url.searchParams.set("to", destinationChain); + return url.toString(); +} +``` + +The page reads the link back, checks the chain ids, and renders +[` `](/widget/whisk-receipt): + +```tsx ReceiptPage.tsx +import { WhiskReceipt, isChainId } from "@usewhisk/react"; + +export function ReceiptPage() { + const params = new URLSearchParams(window.location.search); + const tx = params.get("tx"); + const from = params.get("from") ?? ""; + const to = params.get("to") ?? ""; + + if (!tx || !isChainId(from) || !isChainId(to)) { + return This receipt link is incomplete.
; + } + + return ( ++ ); +} +``` + +Render it inside a [` `](/widget/whisk-provider). For a +cross-chain transfer that has not settled, ` ` shows a **Finish +transfer** button. It calls `engine.resumeFromTx`, which waits for the +attestation and mints, unless Circle's Forwarder minted or the destination +already received the USDC. It never signs a second burn. If the mint needs a wallet on the destination chain, the visitor +has to connect one first. See [recovery](/concepts/recovery). + +Link parameters are untrusted. `isChainId` rejects a chain Whisk does not +know; a wrong hash only shows a receipt that never progresses. A receipt is +for the payer's eyes. Do not use it to decide whether an order is paid; see +[verify on your server](/flows/checkout#verify-on-your-server). + +## Stages + +| `ReceiptStage` | When | Label (`RECEIPT_STAGE_LABELS`) | +| ---------------------- | ------------------------------------------------------------------------ | ------------------------------ | +| `submitted` | Cross-chain, Iris has not seen the burn yet (no status, or `not_found`). | Submitted | +| `awaiting_attestation` | Iris reports `pending_confirmations`. | Confirming on source chain | +| `attested` | Iris reports `complete` and no destination tx hash was given. | Minting on destination | +| `settled` | A destination tx hash was given, or the transfer is on one chain. | Settled | +| `failed` | The caller passed `hasError: true`. | Failed | + +`RECEIPT_STAGE_HELP` holds a one-line English explanation for each stage. +Both maps are plain records, so you can swap in your own copy or translations. + +Two limits follow from the fact that the view only knows what you pass it and +what Iris says: + +- **A cross-chain transfer only reaches `settled` when you pass + `destinationTxHash`.** Iris reporting `complete` means the attestation is + signed, not that the mint landed, so the view stops at `attested`. Polling + also stops there. If you have the mint hash (`finalTxHash` from the send + result), pass it. +- **A same-chain transfer is `settled` as soon as you pass a hash.** Nothing is + read from the chain. Check the transaction yourself if the hash came from a + link. + +`failed` is never inferred. Pass `hasError` when you already hold a +`SendFailure`. + +## ReceiptView + + + One of the five stages above. + ++ A single `transfer` step for a same-chain send. Otherwise `burn`, + `fetchAttestation` and `mint`, each with a `state` of `pending`, `success`, + `error` or `noop`. The burn step carries the source hash and explorer link; + the mint step carries the destination ones when you passed a destination hash. + ++ `sourceChain !== destinationChain`. + ++ Explorer link for the source tx. + ++ Explorer link for the destination tx, when you passed its hash. + + +The input type is `ReceiptInput`: `sourceChain`, `sourceTxHash`, +`destinationChain`, and optional `destinationTxHash`, `irisStatus` and +`hasError`. + +## Your own receipt UI + +[`useReceipt`](/hooks/use-receipt) polls Iris and returns the same view, so you +can draw it however you like: + +```tsx TransferStatus.tsx +import { + RECEIPT_STAGE_HELP, + RECEIPT_STAGE_LABELS, + useReceipt, + type Chain, +} from "@usewhisk/react"; + +export function TransferStatus(props: { + sourceChain: Chain; + destinationChain: Chain; + burnTxHash: string; + mintTxHash?: string; +}) { + const { view, isLoading, error } = useReceipt({ + sourceChain: props.sourceChain, + sourceTxHash: props.burnTxHash, + destinationChain: props.destinationChain, + destinationTxHash: props.mintTxHash, + pollIntervalMs: 5000, + }); + + if (isLoading) returnLooking up the transfer...
; + if (error) returnCould not reach Circle: {error.message}
; + if (!view) return null; + + return ( ++ + ); +} +``` + +`useReceipt` polls every 3 seconds by default and gives up after 10 minutes +(`pollIntervalMs`, `pollTimeoutMs`). It does not poll a same-chain transfer, a +transfer with a `destinationTxHash`, or one with `hasError`. + +## On a server + +Without React, fetch the Iris status yourself and feed it through the same +function. This is useful for a worker that records settlement with no browser +open. + +```ts receipt-stage.ts +import { + deriveReceiptView, + fetchAttestationOnce, + type Chain, + type ReceiptStage, +} from "@usewhisk/core"; + +export async function receiptStage( + sourceChain: Chain, + destinationChain: Chain, + burnTxHash: string, +): Promise{RECEIPT_STAGE_LABELS[view.stage]}
+{RECEIPT_STAGE_HELP[view.stage]}
++ {view.steps.map((step) => ( +
+- + {step.name}: {step.state} + {step.explorerUrl && view} +
+ ))} +{ + const iris = await fetchAttestationOnce(sourceChain, burnTxHash); + return deriveReceiptView({ + sourceChain, + sourceTxHash: burnTxHash, + destinationChain, + irisStatus: iris.status, + }).stage; +} +``` + +The Iris host (mainnet or sandbox) is picked from the source chain's network. +`pollAttestation` does the loop for you, with `timeout`, `pollingInterval` and +an `onUpdate` callback. + +## Explorer links + +`explorerTxUrl` builds a link for any supported chain, including the cluster +query Solana's explorer needs on devnet: + +```ts +import { explorerTxUrl } from "@usewhisk/core"; + +const url = explorerTxUrl( + "Arc_Testnet", + "0x8a3f5c0e2b7d4a91c6e0f3b2d5a8c7e1f0b9a6d3c2e5f8a1b4d7c0e3f6a9b2c5", +); +console.log(url); +``` + +Use it instead of a hard-coded explorer host, so a link for a Base payment does +not point at Arc's explorer. `explorerAddressUrl` does the same for addresses. diff --git a/flows/refunds.mdx b/flows/refunds.mdx new file mode 100644 index 0000000..18b4fe1 --- /dev/null +++ b/flows/refunds.mdx @@ -0,0 +1,240 @@ +--- +title: Refunds +description: Send a payment back to the payer from the merchant wallet, linked to the original transfer. +--- + +A refund is an ordinary send in the other direction: the merchant pays from the +chain where the original payment landed, back to the payer's address, on the +chain the payer should receive on. [`useRefund`](/hooks/use-refund) runs it +from the connected EVM wallet: + +```tsx RefundButton.tsx +import { REFUND_OF_TX_KEY, useRefund } from "@usewhisk/react"; + +export function RefundButton(props: { + orderId: string; + originalTxHash: string; + payerAddress: string; + amount: string; +}) { + const { refund, data, error, isPending } = useRefund(); + + return ( + + + {error &&+ ); +} +``` + +This runs in your back office, not on the payer's page. The wallet connected +in that browser is the merchant: it holds the USDC being returned and signs +the transfer. + +## What happens to the money + +1. Whisk validates the input (below). Nothing is signed if it fails. +2. It quotes a fresh transfer from `originalDestinationChain` to + `refundDestinationChain` for `amount`, to `originalSenderAddress`. +3. It sends that quote at once. There is no confirmation step between quote and + signature beyond the wallet prompt. + +When the two chains are the same, the refund is a plain USDC transfer with no +bridge fees. When they differ, it is a CCTP burn on the merchant's chain and a +mint on the payer's, and the config's `feeBearer` decides who covers the fees: + +| `feeBearer` | Merchant is debited | Payer receives | +| -------------------- | ------------------------- | ----------------------------- | +| `"sender"` (default) | `amount` plus bridge fees | at least `amount` | +| `"receiver"` | `amount` | `amount` less the bridge fees | + +A `feePolicy` on the config applies to refunds too, and the merchant, as the +sender, pays it. As on any transfer, the fee goes with the refund's burn or +after it, never before, and the result's `customFee` says whether it was paid. + +A refund that fails after its burn is in flight like any other transfer: it is +in the in-flight store and can be finished from a +[`{error.message}
} + {data?.kind === "failure" &&{data.error.message}
} + {data?.kind === "success" && ( +Refunded. Linked to {String(data.metadata?.[REFUND_OF_TX_KEY])}.
+ )} +`](/widget/resume-list) in the same browser, or from the burn +hash. See [recovery](/concepts/recovery). + + + Whisk does not look up the original payment. `originalTxHash` is recorded, not + checked, and `amount` is not compared with what was paid. Before you call + `refund`, check against your own order records that the order was paid, that + the refund plus any earlier refunds does not exceed it, and that the address + is the one that paid. + + +## RefundParams + +`useRefund` takes a `RefundInput` plus optional `listeners`. The core engine's +`refund` takes `RefundParams`: the same fields plus the adapters. + ++ Source-chain tx hash of the original payment: the burn for a bridge, the + transfer for a same-chain send. Stamped into the result's metadata. + ++ Where the merchant received the original payment. The refund is sent from + here, so the merchant wallet must hold USDC on it. + ++ Where the payer receives the refund, usually the chain they paid from. Equal + to `originalDestinationChain` for a same-chain refund. Must be on the same + network. + ++ The payer's address on `refundDestinationChain`. + ++ Decimal USDC, such as `"10.50"`. Can be less than the original for a partial + refund. + ++ At most 256 characters. Recorded as `__refundReason`. + ++ Your own correlation keys. Keys starting with `__` are rejected. + ++ Core only. The wallet holding the funds. `useRefund` uses the connected EVM + wallet. + ++ Core only. Signs the mint when Circle does not forward it. + ++ `useRefund` only. `onStep` and `onBurnSubmitted`, as on a send. + + +`useRefund` returns `refund` (fire and forget), `refundAsync` (resolves to the +`RefundResult`, rejects on a thrown error), `data`, `error`, `isPending` and +`reset`. A `RefundResult` is a `SendResult`: branch on `kind`. + ++ `useRefund` only signs with an EVM wallet and passes no `destinationAdapter`. + For a merchant wallet on Solana, Stellar or Starknet, or a refund route that + needs a destination wallet to mint, call `refund` on the engine from + [`useWhiskEngine`](/hooks/use-whisk-engine) or on a [server](/headless/server) + with the adapters you need. + + +## Validate before you ask for a signature + +`validateRefundInput` runs the same checks `refund` runs first, so a form can +show the problem before anything else happens: + +```ts check-refund.ts +import { + ConfigError, + validateRefundInput, + type RefundInput, +} from "@usewhisk/react"; + +export function checkRefund(input: RefundInput): string | null { + try { + validateRefundInput(input); + return null; + } catch (err) { + if (err instanceof ConfigError) return err.message; + throw err; + } +} +``` + +It throws `ConfigError` when: + +- `originalTxHash` or `originalSenderAddress` is empty (both are trimmed), +- `amount` is not a positive decimal string (`"0"`, `"-1"` and `"1e3"` fail), +- `metadata` fails [`validateMetadata`](/flows/metadata), including any + `__`-prefixed key, +- `reason` is longer than 256 characters. + +It does not check chains or addresses. Those fail later, when the refund is +quoted, with `InvalidAddressError` or `NetworkMismatchError`. + +## Link the refund to the payment + +The result's `metadata` carries two reserved keys on top of yours: + +| Key | Value | +| --------------------------------------- | ------------------------- | +| `__refundOfTxHash` (`REFUND_OF_TX_KEY`) | `originalTxHash`, trimmed | +| `__refundReason` (`REFUND_REASON_KEY`) | `reason`, when given | + +```ts refund-link.ts +import { + REFUND_OF_TX_KEY, + REFUND_REASON_KEY, + type SendResult, +} from "@usewhisk/core"; + +export function refundLink(result: SendResult) { + return { + refundOf: result.metadata?.[REFUND_OF_TX_KEY], + reason: result.metadata?.[REFUND_REASON_KEY], + orderId: result.metadata?.orderId, + }; +} +``` + +The reserved keys are written after yours, so your metadata cannot overwrite +them. Like all Whisk metadata, they live only on the returned result: nothing +about the refund's link to the original is written on chain. Save the refund's +tx hashes and these keys in your own records when the result comes back. + +## Without React + +The core engine takes the merchant adapter directly. Config `defaultMetadata` +is merged in before the refund keys: + +```ts refund.ts +import { createWhisk, type EvmAdapter } from "@usewhisk/core"; + +declare const merchantAdapter: EvmAdapter; + +const engine = createWhisk({ + chains: ["Base_Sepolia", "Arc_Testnet"], + defaultMetadata: { store: "atelier" }, +}); + +const result = await engine.refund( + { + originalTxHash: + "0x8a3f5c0e2b7d4a91c6e0f3b2d5a8c7e1f0b9a6d3c2e5f8a1b4d7c0e3f6a9b2c5", + originalDestinationChain: "Base_Sepolia", + refundDestinationChain: "Arc_Testnet", + originalSenderAddress: "0x000000000000000000000000000000000000cafe", + amount: "10.50", + reason: "damaged_item", + merchantAdapter, + }, + { onStep: (step) => console.log(step.name, step.state) }, +); + +console.log(result.kind, result.metadata); +``` + +On success `result.metadata` is `{ store: "atelier", __refundOfTxHash: "0x8a3f...", +__refundReason: "damaged_item" }`. See [server usage](/headless/server) for +running the engine outside a browser. diff --git a/headless/core-engine.mdx b/headless/core-engine.mdx new file mode 100644 index 0000000..d6c4b30 --- /dev/null +++ b/headless/core-engine.mdx @@ -0,0 +1,350 @@ +--- +title: The core engine +description: Use @usewhisk/core without React to resolve, quote, send, and finish USDC transfers with your own adapter. +--- + +`@usewhisk/core` is the engine under the React widget. It has no React, wagmi or +DOM dependency, so it runs in a script, a server, a worker, or another +framework. + +```ts +import { createWhisk } from "@usewhisk/core"; + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); + +const recipient = await engine.resolve( + "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + "Arc_Testnet", +); +console.log(recipient.address); +``` + +```bash +pnpm add @usewhisk/core viem +``` + +`viem` is a peer dependency. `@usewhisk/cctp`, the protocol layer with the chain +registry and Circle's contracts, comes with core. + +## The flow + +1. `createWhisk(config)` builds an engine for a list of chains. Only `chains` + is required. Mainnet or testnet follows from the chain ids you list; a + bridge between a mainnet and a testnet chain is refused with + `NetworkMismatchError`. +2. `engine.resolve(input, chain)` turns an address (or a name, with a + resolver that knows names) into a `ResolvedRecipient`. +3. `engine.quote(params)` prices the transfer for a given payer adapter. Show + `amountIn` (what the payer is debited) and `amountOut` (the least the + recipient gets) before the payer confirms. +4. `engine.send({ quote, adapter }, listeners)` signs exactly that quote. + +The engine signs nothing itself. Every write goes through an adapter you pass +in, which wraps your wallet or key. + +## A complete script + +The adapter turns a viem `WalletClient` into an `EvmAdapter`. It is pinned to +the wallet's chain, which suits a server key; a browser wallet would call +`wallet.switchChain` instead (see [Vue](/headless/vue)). + +```ts adapter.ts +import { + createPublicClient, + http, + type Account, + type Chain as ViemChain, + type Transport, + type WalletClient, +} from "viem"; +import { toWhiskError, WrongChainError, type EvmAdapter } from "@usewhisk/core"; + +export function toEvmAdapter( + wallet: WalletClient, + rpcUrl?: string, +): EvmAdapter { + const publicClient = createPublicClient({ + chain: wallet.chain, + transport: http(rpcUrl), + }); + + return { + kind: "evm", + address: wallet.account.address, + + async getChainId() { + return wallet.getChainId(); + }, + + async switchChain(chainId) { + if (chainId !== wallet.chain.id) { + throw new WrongChainError(String(chainId)); + } + }, + + async sendCalls(calls, options) { + const hashes: `0x${string}`[] = []; + for (const [index, call] of calls.entries()) { + try { + const hash = await wallet.sendTransaction({ + to: call.to, + data: call.data, + value: call.value, + ...(call.maxFeePerGas !== undefined && { + maxFeePerGas: call.maxFeePerGas, + }), + ...(call.maxPriorityFeePerGas !== undefined && { + maxPriorityFeePerGas: call.maxPriorityFeePerGas, + }), + }); + hashes.push(hash); + options?.onSubmitted?.(hash, index); + // The burn spends the approve's allowance, so wait for each call to land. + const receipt = await publicClient.waitForTransactionReceipt({ + hash, + confirmations: 2, + }); + if (receipt.status === "reverted") { + throw toWhiskError( + new Error(`Reverted: ${hash}`), + "Transaction reverted on-chain.", + "reverted_onchain", + ); + } + } catch (cause) { + throw toWhiskError(cause, "Failed to submit transaction."); + } + } + return { hashes }; + }, + + async waitForReceipt(hash) { + try { + const receipt = await publicClient.waitForTransactionReceipt({ hash }); + return { + status: receipt.status === "success" ? "success" : "reverted", + blockNumber: receipt.blockNumber, + }; + } catch (cause) { + throw toWhiskError(cause, "Failed waiting for receipt."); + } + }, + }; +} +``` + +The script reads the balance, works out the largest amount the wallet can +send, quotes 1.00 USDC from Base Sepolia to Arc Testnet, and sends it. + +```ts send.ts +import { createWalletClient, http, type Hex } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { baseSepolia } from "viem/chains"; +import { + createWhisk, + formatUsdcAmount, + QuoteChangedError, +} from "@usewhisk/core"; +import { toEvmAdapter } from "./adapter.js"; + +const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex); +const wallet = createWalletClient({ + account, + chain: baseSepolia, + transport: http(), +}); +const adapter = toEvmAdapter(wallet); + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); + +const balance = await engine.balance({ + chain: "Base_Sepolia", + address: adapter.address, +}); +console.log( + `Balance: ${balance === null ? "unknown" : formatUsdcAmount(balance)} USDC`, +); + +const recipient = await engine.resolve(process.env.TO ?? "", "Arc_Testnet"); +const route = { + sourceChain: "Base_Sepolia", + destinationChain: "Arc_Testnet", + recipient, + adapter, +} as const; + +const max = await engine.maxSendable(route); +console.log(`Can send up to ${max?.amount ?? "?"} USDC`); + +let quote = await engine.quote({ ...route, amount: "1.00" }); +console.log( + `Pay ${quote.amountIn}, recipient gets at least ${quote.amountOut}, fees ${quote.fees.total}`, +); + +const listeners = { + onStep: (step: { name: string; state: string; txHash?: string }) => + console.log(`${step.name}: ${step.state}`, step.txHash ?? ""), + onBurnSubmitted: (txHash: string) => console.log(`Burn submitted: ${txHash}`), +}; + +let result; +try { + result = await engine.send( + { quote, adapter, metadata: { orderId: "ord_123" } }, + listeners, + ); +} catch (err) { + if (!(err instanceof QuoteChangedError)) throw err; + console.log(`Fees rose. New total: ${err.quote.amountIn} USDC`); + quote = err.quote; + result = await engine.send( + { quote, adapter, metadata: { orderId: "ord_123" } }, + listeners, + ); +} + +if (result.kind === "success") { + console.log(`Delivered. Mint tx: ${result.finalTxHash ?? "not reported"}`); +} else { + console.error(`${result.error.code}: ${result.error.message}`); +} +``` + +Run it with `PRIVATE_KEY=0x... TO=0x... npx tsx send.ts` from a package with +`"type": "module"`, since the script uses top-level `await`. The wallet needs +testnet USDC on Base Sepolia and Base Sepolia ETH for gas. On Arc, gas is paid in +USDC from the same balance. + +### What the adapter has to do + +- **`sendCalls`** submits the calls in order and waits for each to confirm + before the next. A bridge sends `approve` and then the burn, and the burn + reverts if it is estimated before the approval lands. Two confirmations + between calls guard against an RPC that is a block behind. +- **Pass `maxFeePerGas` and `maxPriorityFeePerGas` through** when the engine + sets them. Arc drops transactions below its 20 gwei base fee floor. +- **Call `options.onSubmitted`** with each hash as soon as you have it. The + engine records the burn hash from it, which is what makes a transfer + recoverable after a crash. +- **Throw `WhiskError`s.** The engine does not reclassify errors, so wrap + failures with `toWhiskError` and a wrong chain with `WrongChainError`. +- **Atomic batches are optional.** With a `feePolicy`, the engine asks + `supportsAtomicBatch(chainId)` and, on yes, sends the burn and the fee in one + `sendCalls` with `atomic: true`. An adapter that implements it must land + those calls all or nothing, or throw + `WalletCapabilityError("atomic_unsupported", ...)` before sending anything. + Leave it out, as above, and the fee is sent as separate calls once the burn + has landed. + +## Send results + +`send` refuses before anything is signed by **throwing**. The errors to expect: + +| Error | When | +| -------------------------- | --------------------------------------------------------------- | +| `QuoteExpiredError` | More than 60 seconds since the quote was issued | +| `QuoteChangedError` | Circle's fees rose past the quote; `error.quote` is a fresh one | +| `InsufficientBalanceError` | The EVM balance cannot cover `amountIn` plus, on Arc, gas | +| `ConfigError` | Invalid metadata | + +Once the wallet is involved, `send` **returns** a `SendResult`. On +`kind: "success"` the recipient has the USDC; `finalTxHash` is the mint (or the +same-chain transfer) when known. On `kind: "failure"`, check `result.steps`: if +the `burn` step succeeded, the USDC left the payer and the mint is still due. +Finish it with `resume`. With a `feePolicy`, both kinds carry `customFee`, +which says whether the merchant fee was paid; see [when the fee is +paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + +The listeners: + +- `onStep(step)` fires on each step change: `approve`, then `transfer` for a + same-chain send, or `burn`, `fetchAttestation` and `mint` for a bridge. A + `mint` step with `forwarded: true` was submitted by Circle's Forwarder. +- `onBurnSubmitted(txHash)` fires with the burn hash before any receipt wait. + If you keep your own records, save it here. + +## Balance and max amount + +`engine.balance({ chain, address })` returns USDC subunits as a `bigint`. +`engine.maxSendable(params)` takes the quote parameters without `amount` and +returns: + + + The largest decimal amount whose quote fits the balance, ready for `quote`. + + ++ The USDC balance in subunits. + + ++ Subunits held back for gas. Non-zero only where gas is paid in USDC, as on + Arc. + + +Both read EVM chains only today and return `null` for a Solana, Stellar or +Starknet source +([usewhisk/whisk#157](https://github.com/usewhisk/whisk/issues/157)). The +balance check before `send` is skipped in that case and the wallet has the +final say. + +## In-flight transfers + +Every bridge is written to the engine's `inflightStore`: as `signing` before +the wallet is asked, `burned` with the hash as soon as the wallet returns it, +`attested`, and `minted` at the end. A transfer that fails before the burn +leaves nothing behind. The default store is in memory and lasts as long as the +engine. Pass `createStorageInflightStore(localStorage)` in a browser, or your +own store on a server (see [server](/headless/server)). + +```ts resume.ts +import { createStorageInflightStore, createWhisk } from "@usewhisk/core"; + +const engine = createWhisk({ + chains: ["Base_Sepolia", "Arc_Testnet"], + inflightStore: createStorageInflightStore(window.localStorage), +}); + +for (const record of await engine.inflight()) { + if (record.step === "minted") { + await engine.dismiss(record.id); + continue; + } + if (record.step === "signing") continue; + const result = await engine.resume( + record, + {}, + { + onStep: (step) => console.log(record.id, step.name, step.state), + }, + ); + if (result.kind === "success") await engine.dismiss(record.id); +} + +const fromLink = await engine.resumeFromTx({ + sourceChain: "Base_Sepolia", + txHash: "0x...", +}); +console.log(fromLink.kind); +``` + +- `inflight()` lists the records, oldest first. +- `resume(record, options, listeners)` waits for the attestation, re-attests an + expired one, and mints, unless Circle forwards the mint or the destination + already has it. It never signs the burn again. A record with no burn hash + (stuck at `signing`) returns a failure asking for the tx hash. +- `resumeFromTx({ sourceChain, txHash })` does the same from a burn hash alone, + such as one from a receipt link. +- `dismiss(id)` removes a record. Burned records are never dropped on their + own. + +Pass `destinationAdapter` in `options` when the route needs the destination +wallet to sign the mint. + +## Other ecosystems + +The engine takes a `SolanaAdapter`, `StellarAdapter` or `StarknetAdapter` the +same way. The shapes are in [wallet adapters](/hooks/wallet-adapters), and the +React package's implementations are a good starting point for your own. A +bridge Circle does not forward (into Solana, Stellar or Starknet, or out of +Stellar or Starknet) needs `destinationAdapter` on `quote` and `send`. diff --git a/headless/react-headless.mdx b/headless/react-headless.mdx new file mode 100644 index 0000000..7144238 --- /dev/null +++ b/headless/react-headless.mdx @@ -0,0 +1,127 @@ +--- +title: React without the widget +sidebarTitle: React headless +description: The @usewhisk/react/headless entry gives you the provider and hooks with no Whisk components or styles. +--- + +`@usewhisk/react/headless` is the React package minus its UI: the provider, +the config builders, the hooks and the core re-exports, with no components, +theme helpers or CSS. + +```tsx App.tsx +import { useConnect, useDisconnect } from "wagmi"; +import { + WhiskProvider, + createWhiskConfig, + evm, + useWhisk, +} from "@usewhisk/react/headless"; + +const config = createWhiskConfig({ + wallets: [evm({ chains: ["Base_Sepolia", "Arc_Testnet"] })], + chains: ["Base_Sepolia", "Arc_Testnet"], +}); + +function Wallet() { + const { isConnected, address } = useWhisk(); + const { connectors, connect, isPending } = useConnect(); + const { disconnect } = useDisconnect(); + + if (isConnected) { + return ; + } + return ( ++ {connectors.map((connector) => ( + + ))} ++ ); +} + +export function App() { + return ( ++ + ); +} +``` + +Everything you render is yours. Do not import `@usewhisk/react/styles.css`; +nothing here uses it. + +## What the entry leaves out + +Both entries export the same provider, config builders (`createWhiskConfig`, +`evm`, `solana`, `stellar`, `starknet`), hooks, resolvers, errors, fee and +chain helpers, receipt and refund helpers, and amount formatting. The headless +entry does not export: + +| Left out | Exports | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| Widget components | `WhiskSend`, `WhiskReceipt`, `ResumeList` and their props types | +| UI primitives | `Banner`, `Button`, `Card`, `ChainPicker`, `ConnectModal`, `FieldBox`, `PoweredByWhisk`, `StepRail` and their props types | +| Theme helpers | `getThemePreset`, `listThemeNames`, `resolveTheme`, `themePresets`, `themeToCssVars`, `tokensToCssVars` and the theme types | +| Browser in-flight store | `createBrowserInflightStore` | + +`createBrowserInflightStore` is missing only as an export. `+ ` +still uses it by default, so transfers are kept in `localStorage` and survive +a reload. To pass a store of your own, build it with +`createStorageInflightStore` or `createMemoryInflightStore` from +`@usewhisk/core`. + +Both entries load the provider and hooks from one shared chunk of the +published build, so they share one context. Importing `ConnectModal` from the +main entry and everything else from `/headless` works. + +## Connecting wallets yourself + +Without ` `, connecting is up to you: + +- **EVM:** use wagmi's own hooks (`useConnect`, `useDisconnect`) inside the + provider, as above. `evm()` sets up the wagmi config and connectors, and + `useWhisk` reads the account from it. Add `wagmi` 2 to your dependencies so + your app and Whisk share one copy; two copies mean two contexts, and Whisk + will not see the account. +- **Solana:** `solana()` mounts the Solana wallet adapter's + `ConnectionProvider` and `WalletProvider`, so `useWallet` from + `@solana/wallet-adapter-react` (0.15) connects a Wallet Standard wallet. +- **Stellar and Starknet:** 0.3 has no public hook to connect these wallets. + Render ` ` from the main entry for them, or drive the engine + with your own `StellarAdapter` or `StarknetAdapter`. + +## What the provider still renders + +` ` wraps its children in a ` ` and adds an empty +`` after them. Lay out your own markup knowing the +wrapper is there. The `theme` prop still applies to it: `"dark"` adds +`class="dark"`, which turns on Tailwind `dark:` variants inside it if your app +uses the class strategy, and the named palettes and token overrides set +`--whisk-*` variables inline, which do nothing without Whisk's CSS. The default +`"light"` adds neither. + +It also mounts wagmi, react-query and, when configured, the Solana, Stellar +and Starknet providers. An outer `WagmiProvider` or `QueryClientProvider` is +reused instead of mounting a second one. + +## Building the UI + +From here the hooks do the work: + +- [`useWhisk`](/hooks/use-whisk) for quote and send with the EVM wallet, and a + full custom send component built on Whisk's state machine. +- [`useAdapterFor`](/hooks/wallet-adapters) and + [`useWhiskEngine`](/hooks/use-whisk-engine) for other ecosystems and for + balances and in-flight transfers. +- [`useReceipt`](/hooks/use-receipt) for transfer status. +- [`useRefund`](/hooks/use-refund) for merchant refunds. + +If you are not using React at all, use [the core engine](/headless/core-engine) +directly. diff --git a/headless/server.mdx b/headless/server.mdx new file mode 100644 index 0000000..d768560 --- /dev/null +++ b/headless/server.mdx @@ -0,0 +1,261 @@ +--- +title: Running the engine on a server +sidebarTitle: Server +description: Send USDC from Node with a key you hold, keep transfers on disk, and avoid paying anyone twice. +--- + +On a server the engine signs with a key your service holds, for payouts, +refunds and treasury moves that no user approves in a wallet. The engine is +the same `@usewhisk/core` as in the browser; what changes is who holds the key +and what happens when the process dies mid-transfer. + +```ts payout.ts +import { createWalletClient, http, type Hex } from "viem"; +import { nonceManager, privateKeyToAccount } from "viem/accounts"; +import { arcTestnet } from "viem/chains"; +import { createWhisk } from "@usewhisk/core"; +import { toEvmAdapter } from "./adapter.js"; +import { createFileInflightStore } from "./store.js"; + +declare const db: { + claimPayout(id: string): Promise; + releasePayout(id: string): Promise ; + recordPayout( + id: string, + result: { burnTx?: string; mintTx?: string; error?: string }, + ): Promise ; +}; + +const key = process.env.PAYOUT_PRIVATE_KEY; +if (!key) throw new Error("PAYOUT_PRIVATE_KEY is not set."); + +const account = privateKeyToAccount(key as Hex, { nonceManager }); +const wallet = createWalletClient({ + account, + chain: arcTestnet, + transport: http(process.env.ARC_RPC_URL), +}); +const adapter = toEvmAdapter(wallet, process.env.ARC_RPC_URL); + +const engine = createWhisk({ + chains: ["Arc_Testnet", "Base_Sepolia"], + inflightStore: createFileInflightStore("./data/whisk-inflight.json"), + ...(process.env.ARC_RPC_URL && { + rpcUrls: { Arc_Testnet: process.env.ARC_RPC_URL }, + }), +}); + +export async function payout(id: string, to: string, amount: string) { + if (!(await db.claimPayout(id))) return; + + const recipient = await engine.resolve(to, "Base_Sepolia"); + const quote = await engine.quote({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient, + amount, + adapter, + }); + + let burnTx: string | undefined; + let result; + try { + result = await engine.send( + { quote, adapter, metadata: { payoutId: id } }, + { onBurnSubmitted: (hash) => (burnTx = hash) }, + ); + } catch (err) { + // No burn means no USDC left the wallet, so the payout can run again. + if (!burnTx) await db.releasePayout(id); + throw err; + } + + await db.recordPayout(id, { + ...(burnTx && { burnTx }), + ...(result.kind === "success" + ? { ...(result.finalTxHash && { mintTx: result.finalTxHash }) } + : { error: result.error.message }), + }); +} +``` + +This builds on the viem adapter from [the core engine](/headless/core-engine) +and the file store below. The runnable version is +[`examples/node-headless`](https://github.com/usewhisk/whisk/tree/main/examples/node-headless) +in the Whisk repo, with scripts for a send, a payroll loop, a refund and a +receipt watcher. + +## Keys + +- Read the key from the environment or a secret manager at startup, and fail + if it is missing. Never log it, and never put it in metadata: metadata is + echoed in results and may reach your logs. +- Use a dedicated payout wallet holding only what the next payouts need, not + your treasury. +- Use viem's `nonceManager` on the account so sends from the same key in one + process do not reuse a nonce. Sends from several processes with one key can + still collide; run payouts from one worker, or one key per worker. +- The wallet pays gas on the source chain: ETH on most EVM chains, USDC on + Arc. On Arc the engine keeps a gas reserve out of `maxSendable` and checks + for it before sending. + +## One adapter per chain + +A server adapter is pinned to the chain of its wallet client and refuses to +switch. Build one per source chain. On a forwarded EVM to EVM bridge Circle +submits the mint, so the source adapter is enough. When it does not (with +`useForwarder: false`, or into a chain without forwarding), the engine signs +the EVM mint with `destinationAdapter`, falling back to the source adapter, +which then refuses to switch. Pass an adapter for the destination chain: + +```ts +import { + createWhisk, + type EvmAdapter, + type ResolvedRecipient, +} from "@usewhisk/core"; + +const engine = createWhisk({ + chains: ["Arc_Testnet", "Base_Sepolia"], + useForwarder: false, +}); + +const quote = await engine.quote({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient, + amount: "25.00", + adapter: arcAdapter, + destinationAdapter: baseAdapter, +}); +await engine.send({ + quote, + adapter: arcAdapter, + destinationAdapter: baseAdapter, +}); +``` + +## Keep in-flight transfers on disk + +The engine records each bridge in its `inflightStore` before the wallet signs, +and records the burn hash the moment the wallet returns it. The default store +is in memory, so a crash or a deploy between burn and mint forgets the +transfer. The USDC is not lost, since Circle's attestation still exists, but +you would have to find the burn hash yourself. Give the engine a store that +survives restarts. + +`InflightStore` is three async methods over JSON-safe records (amounts are +subunit strings): + +```ts store.ts +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { InflightRecord, InflightStore } from "@usewhisk/core"; + +export function createFileInflightStore(path: string): InflightStore { + let queue: Promise = Promise.resolve(); + + async function load(): Promise > { + try { + return JSON.parse(await readFile(path, "utf8")) as Record< + string, + InflightRecord + >; + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return {}; + throw err; + } + } + + async function save(records: Record ) { + await mkdir(dirname(path), { recursive: true }); + await writeFile(`${path}.tmp`, JSON.stringify(records, null, 2)); + await rename(`${path}.tmp`, path); + } + + // One write at a time, so two updates to the same file never interleave. + function serial (task: () => Promise ): Promise { + const next = queue.then(task); + queue = next.catch(() => undefined); + return next; + } + + return { + put: (record) => + serial(async () => { + const records = await load(); + records[record.id] = record; + await save(records); + }), + list: () => + serial(async () => + Object.values(await load()).sort((a, b) => a.createdAt - b.createdAt), + ), + remove: (id) => + serial(async () => { + const records = await load(); + delete records[id]; + await save(records); + }), + }; +} +``` + +A file works for a single worker. With several, use your database: a table +keyed by `id` holding the record as JSON. Writes for one transfer arrive in +order, so a plain upsert is enough. + +On startup, finish what the last process left: + +```ts resume-on-boot.ts +import { createWhisk } from "@usewhisk/core"; +import { createFileInflightStore } from "./store.js"; + +const engine = createWhisk({ + chains: ["Arc_Testnet", "Base_Sepolia"], + inflightStore: createFileInflightStore("./data/whisk-inflight.json"), +}); + +for (const record of await engine.inflight()) { + if (record.step === "minted") { + await engine.dismiss(record.id); + } else if (record.sourceTxHash) { + const result = await engine.resume(record); + console.log(record.id, result.kind); + if (result.kind === "success") await engine.dismiss(record.id); + } else { + console.warn( + `${record.id} never recorded a burn. Check the wallet before dismissing it.`, + ); + } +} +``` + +A record stuck at `signing` has no burn hash. The process died between asking +for the signature and getting the hash back, so the burn may or may not have +been sent. Look up the wallet's transactions; if a burn is there, finish it +with `engine.resumeFromTx({ sourceChain, txHash })`. + +## Do not pay twice + +Whisk does not deduplicate payouts. Each `send` with a fresh quote is a new +transfer, and a retry after a timeout pays again. The payout above guards +against that: + +1. **Claim before sending.** `claimPayout` marks the payout as taken in the + same transaction that checks it, so two workers or a retried job cannot both + send it. +2. **Release only if nothing burned.** `send` throws for refusals before + signing, such as an expired quote, changed fees or a low balance. When it + throws and `onBurnSubmitted` never fired, no USDC left the wallet and the + payout can run again. +3. **Never re-send after a burn.** If the result is a failure but a burn hash + exists, the money is in flight. Finish it with `resume`, not a new `send`. +4. **Tag the transfer.** `metadata: { payoutId }` comes back on the result, so + logs and receipts tie to your records. + +## Watching without signing + +A worker that only reports status needs no key. `pollAttestation` and +`deriveReceiptView` follow a transfer from its burn hash; see +[receipts](/flows/receipts). diff --git a/headless/vue.mdx b/headless/vue.mdx new file mode 100644 index 0000000..ebb83ef --- /dev/null +++ b/headless/vue.mdx @@ -0,0 +1,328 @@ +--- +title: Vue +description: Wire @usewhisk/core into a Vue 3 app with a composable and an injected browser wallet. +--- + +Whisk has no Vue package. The engine in `@usewhisk/core` is framework-agnostic, +so a Vue app creates it once and wraps it in a composable that holds the flow +state in refs. + +```ts composables/useWhisk.ts +import { ref, shallowRef } from "vue"; +import { + createPublicClient, + createWalletClient, + custom, + http, + type EIP1193Provider, +} from "viem"; +import { + createWhisk, + toWhiskError, + tryChainByEvmChainId, + type Chain, + type EvmAdapter, + type Quote, + type Step, + type WhiskError, +} from "@usewhisk/core"; + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); + +function browserAdapter( + provider: EIP1193Provider, + address: `0x${string}`, +): EvmAdapter { + const wallet = createWalletClient({ + account: address, + transport: custom(provider), + }); + // Injected wallets are slow to report receipts, so poll the chain's public RPC. + const publicClientFor = async () => { + const chain = tryChainByEvmChainId(await wallet.getChainId()); + return createPublicClient({ + transport: chain ? http(chain.defaultRpcUrls[0]) : custom(provider), + }); + }; + + return { + kind: "evm", + address, + getChainId: () => wallet.getChainId(), + async switchChain(id) { + try { + await wallet.switchChain({ id }); + } catch (cause) { + throw toWhiskError(cause, "Failed to switch chain."); + } + }, + async sendCalls(calls, options) { + const publicClient = await publicClientFor(); + const hashes: `0x${string}`[] = []; + for (const [index, call] of calls.entries()) { + try { + const hash = await wallet.sendTransaction({ + chain: null, + to: call.to, + data: call.data, + value: call.value, + ...(call.maxFeePerGas !== undefined && { + maxFeePerGas: call.maxFeePerGas, + }), + ...(call.maxPriorityFeePerGas !== undefined && { + maxPriorityFeePerGas: call.maxPriorityFeePerGas, + }), + }); + hashes.push(hash); + options?.onSubmitted?.(hash, index); + await publicClient.waitForTransactionReceipt({ + hash, + confirmations: 2, + }); + } catch (cause) { + throw toWhiskError(cause, "Failed to submit transaction."); + } + } + return { hashes }; + }, + async waitForReceipt(hash) { + const receipt = await ( + await publicClientFor() + ).waitForTransactionReceipt({ hash }); + return { + status: receipt.status === "success" ? "success" : "reverted", + blockNumber: receipt.blockNumber, + }; + }, + }; +} + +type SendState = + | { kind: "idle" } + | { kind: "quoting" } + | { kind: "review"; quote: Quote } + | { kind: "sending"; quote: Quote; steps: Step[] } + | { kind: "done"; txHash: string | undefined; steps: Step[] } + | { kind: "failed"; error: WhiskError }; + +export function useWhisk() { + const adapter = shallowRef (null); + const state = ref ({ kind: "idle" }); + + async function connect() { + const provider = (window as { ethereum?: EIP1193Provider }).ethereum; + if (!provider) { + state.value = { + kind: "failed", + error: toWhiskError(new Error("No browser wallet found.")), + }; + return; + } + try { + const [address] = await provider.request({ + method: "eth_requestAccounts", + }); + if (address) adapter.value = browserAdapter(provider, address); + } catch (err) { + state.value = { + kind: "failed", + error: toWhiskError(err, "Connect failed."), + }; + } + } + + async function quote( + to: string, + amount: string, + sourceChain: Chain, + destinationChain: Chain, + ) { + if (!adapter.value) return; + state.value = { kind: "quoting" }; + try { + const recipient = await engine.resolve(to, destinationChain); + const q = await engine.quote({ + sourceChain, + destinationChain, + recipient, + amount, + adapter: adapter.value, + }); + state.value = { kind: "review", quote: q }; + } catch (err) { + state.value = { + kind: "failed", + error: toWhiskError(err, "Quote failed."), + }; + } + } + + async function send() { + if (state.value.kind !== "review" || !adapter.value) return; + const q = state.value.quote; + const steps: Step[] = []; + state.value = { kind: "sending", quote: q, steps }; + try { + const result = await engine.send( + { quote: q, adapter: adapter.value }, + { + onStep(step) { + const i = steps.findIndex((s) => s.name === step.name); + if (i === -1) steps.push(step); + else steps[i] = step; + state.value = { kind: "sending", quote: q, steps: [...steps] }; + }, + }, + ); + state.value = + result.kind === "success" + ? { kind: "done", txHash: result.finalTxHash, steps: result.steps } + : { kind: "failed", error: result.error }; + } catch (err) { + state.value = { + kind: "failed", + error: toWhiskError(err, "Send failed."), + }; + } + } + + function reset() { + state.value = { kind: "idle" }; + } + + return { adapter, state, connect, quote, send, reset }; +} +``` + +This follows +[`examples/vue-headless`](https://github.com/usewhisk/whisk/tree/main/examples/vue-headless) +in the Whisk repo, which has the full page with a form, review screen and step +list. + +## Install + +```bash +pnpm add @usewhisk/core viem vue buffer +``` + +## Vite setup + +`@usewhisk/core` brings in `@usewhisk/cctp`, which loads `@solana/web3.js` +and `@stellar/stellar-sdk`. Both read Node's `Buffer` when they load, even if +your app only uses EVM chains, and Vite does not provide it. Set it before +anything else imports Whisk: + +```ts main.ts +import { Buffer } from "buffer"; +if (typeof globalThis.Buffer === "undefined") { + globalThis.Buffer = Buffer; +} + +import { createApp } from "vue"; +import App from "./App.vue"; + +createApp(App).mount("#app"); +``` + +The example's `vite.config.ts` also aliases `buffer` to the npm package, +stubs Node's `crypto` with an empty module (nothing calls it in the browser), +and defines `global` as `globalThis` and `process.env` as `{}`. + +## How the composable works + +- **One engine per app.** `createWhisk` runs at module level, so every + component shares the engine and its in-flight store. Add chains to `chains` + to widen it; mainnet or testnet follows from the chain ids. +- **The adapter wraps `window.ethereum`.** viem's `custom` transport signs + through the injected wallet. `switchChain` asks the wallet to switch, since + the engine moves the wallet to the source chain before sending. Receipts are + polled over the chain's public RPC from Whisk's registry, because injected + providers are slow to report them. +- **Errors become `WhiskError`s.** Adapter failures go through `toWhiskError` + so the engine and your UI see typed errors, such as `UserRejectedError` when + the payer cancels in the wallet. +- **The state is a tagged union.** `idle`, `quoting`, `review`, `sending`, + `done` and `failed`, so the template renders one branch per `kind`. + `@usewhisk/core` also exports `reduce` and `initialState` if you would rather + reuse Whisk's own state machine; see + [useWhisk](/hooks/use-whisk#the-state-machine). +- **`adapter` is a `shallowRef`.** Vue would otherwise wrap the adapter object + in a reactive proxy. + +`send` throws, and the composable shows `failed`, when the engine refuses +before signing: an expired quote (60 seconds), changed fees, or a balance too +low. After the burn, a failure means USDC is in flight; the engine keeps the +transfer in its in-flight store so it can be finished with `engine.resume`. +The default store is memory, so pass +`inflightStore: createStorageInflightStore(window.localStorage)` to +`createWhisk` to keep transfers across a reload. See +[the core engine](/headless/core-engine#in-flight-transfers). + +## Using it in a component + +```vue App.vue + + + + + + + + Getting a quote...
+ +++ +You pay {{ state.quote.amountIn }} USDC
+Recipient gets at least {{ state.quote.amountOut }} USDC
+ + ++
+ +- + {{ step.name }}: {{ step.state }} +
+++ +``` + +## What you build yourself + +Compared with the React widget, a Vue app has no connect modal, theming or +recipient chip. Resolution still works: `engine.resolve` accepts addresses on +every ecosystem, and you can add a name resolver with the `resolver` option. +The example is EVM only. For Solana, Stellar or Starknet, write a +`SolanaAdapter`, `StellarAdapter` or `StarknetAdapter` in the same way; their +shapes are in [wallet adapters](/hooks/wallet-adapters). diff --git a/hooks/use-receipt.mdx b/hooks/use-receipt.mdx new file mode 100644 index 0000000..b421c4f --- /dev/null +++ b/hooks/use-receipt.mdx @@ -0,0 +1,211 @@ +--- +title: useReceipt +description: Poll Circle for one transfer and get back its stage, steps and explorer links. +--- + +`useReceipt` follows a transfer from its source-chain tx hash. It is the hook +behind [`Delivered. Mint tx: {{ state.txHash ?? "not reported" }}
+ +`](/widget/whisk-receipt), for when you want the status +in your own markup. + +```tsx TransferStatus.tsx +import { + RECEIPT_STAGE_HELP, + RECEIPT_STAGE_LABELS, + useReceipt, +} from "@usewhisk/react"; + +export function TransferStatus({ txHash }: { txHash: string }) { + const { view, isLoading, error } = useReceipt({ + sourceChain: "Base_Sepolia", + sourceTxHash: txHash, + destinationChain: "Arc_Testnet", + }); + + if (error) return Could not reach Circle: {error.message}
; + if (isLoading || !view) returnLooking up the transfer...
; + return ( ++ {RECEIPT_STAGE_LABELS[view.stage]} ++ ); +} +``` + +It runs on react-query, so it needs a `QueryClient` in scope. +[`{RECEIPT_STAGE_HELP[view.stage]}
+ Source transaction +`](/widget/whisk-provider) provides one, or reuses yours. It +does not need a connected wallet. + +## How it polls + +- A **same-chain** send never polls. The source transaction is the settlement, + so the view is `settled` at once (or `failed` with `hasError`). +- A **cross-chain** transfer asks Circle's Iris API about the burn every + `pollIntervalMs` (3 seconds by default). It stops when Iris reports + `complete`, when `pollTimeoutMs` passes (10 minutes by default), or when you + pass `destinationTxHash` or `hasError`. +- The timeout clock starts when the hook first sees a source chain and hash, + and restarts only when one of them changes, not on every render. +- Iris is picked from the source chain: the production API for a mainnet + chain, the sandbox for a testnet one. + + + Iris knows about the attestation, not the mint. When it reports `complete` the + stage moves to `attested` ("Minting on destination") and polling stops. The + hook does not watch the destination chain, so it reaches `settled` only when + you pass `destinationTxHash`. Take it from `SendSuccess.finalTxHash`. On a + forwarded mint that hash can be missing; a successful `SendResult` already + means the USDC was minted. + + +## Stages + +`view.stage` is a `ReceiptStage`. `RECEIPT_STAGE_LABELS` and +`RECEIPT_STAGE_HELP` hold the English text `` shows; both are +plain records you can replace to translate. + +| Stage | When | `RECEIPT_STAGE_LABELS` | `RECEIPT_STAGE_HELP` | +| ---------------------- | ------------------------------------------------------------- | -------------------------- | --------------------------------------------------------------------- | +| `submitted` | Burn sent; Iris has not seen it yet (or answered `not_found`) | Submitted | We're waiting for the burn to be picked up. | +| `awaiting_attestation` | Iris is waiting on source-chain confirmations | Confirming on source chain | Circle is signing the cross-chain message. This usually takes 30–90s. | +| `attested` | Attestation ready, no destination tx known | Minting on destination | Attestation ready. The destination mint will land shortly. | +| `settled` | `destinationTxHash` given, or a same-chain send | Settled | Funds have landed on the destination chain. | +| `failed` | You passed `hasError` | Failed | Something went wrong. Check the source tx for the full revert. | + +`view.steps` is a single `transfer` step for a same-chain send, and `burn`, +`fetchAttestation`, `mint` for a bridge, each with a `state` of `pending`, +`success`, `error` or `noop`. + +## Follow a send you just made + +Start the receipt from `onBurnSubmitted`, which fires as soon as the wallet +returns the burn hash, then hand it the mint hash when `send` resolves. + +```tsx PayAndTrack.tsx +import { useState } from "react"; +import { + RECEIPT_STAGE_LABELS, + toWhiskError, + useReceipt, + useWhisk, + type Quote, +} from "@usewhisk/react"; + +export function PayAndTrack({ quote }: { quote: Quote }) { + const { send } = useWhisk(); + const [burnTx, setBurnTx] = useState (); + const [mintTx, setMintTx] = useState (); + const [failed, setFailed] = useState(false); + const [message, setMessage] = useState (); + + const { view } = useReceipt({ + sourceChain: "Base_Sepolia", + sourceTxHash: burnTx, + destinationChain: "Arc_Testnet", + destinationTxHash: mintTx, + hasError: failed, + }); + + async function pay() { + try { + const result = await send({ quote }, { onBurnSubmitted: setBurnTx }); + if (result.kind === "success") setMintTx(result.finalTxHash); + else setFailed(true); + } catch (err) { + setMessage(toWhiskError(err).message); + } + } + + return ( + + + {message ?+ ); +} +``` + +If the burn landed but the mint did not, the transfer can be finished from the +hash alone with `engine.resumeFromTx`. `{message}
: null} + {view ?{RECEIPT_STAGE_LABELS[view.stage]}
: null} +` shows a button for +that; see [recovery](/concepts/recovery). + +## Input + + + The chain the transfer was sent from. Its network picks the Iris endpoint. + + ++ The burn (or same-chain transfer) hash. While it is `undefined` the hook does + nothing and `view` is `null`. + + ++ Equal to `sourceChain` for a same-chain send. + + ++ The mint hash, when you have it. Marks the transfer `settled` and stops + polling. + + ++ Forces the `failed` stage and stops polling, for a caller that already has a + `SendFailure`. + + ++ Milliseconds between Iris requests. Default `3000`. + + ++ Stop polling after this many milliseconds. Default `600000` (10 minutes). + + +## Result + ++ `stage`, `steps`, `isCrossChain`, `sourceExplorerUrl` and, once + `destinationTxHash` is known, `destinationExplorerUrl`. `null` without a + `sourceTxHash`. + + ++ The latest Iris status: `pending_confirmations`, `complete` or `not_found`. + + ++ The latest Iris response, with `message` and `attestation` once signed. + + ++ `true` while waiting for the first Iris response of a cross-chain transfer. + + ++ Set when an Iris request fails, such as on a network error. + + +## Without React + +`deriveReceiptView` is the pure function the hook feeds each Iris answer +through. Use it on a server or in another framework, with `pollAttestation` or +`fetchAttestationOnce` for the polling. + +```ts +import { deriveReceiptView, RECEIPT_STAGE_LABELS } from "@usewhisk/react"; + +const view = deriveReceiptView({ + sourceChain: "Base_Sepolia", + sourceTxHash: "0x...", + destinationChain: "Arc_Testnet", + irisStatus: "complete", +}); + +console.log(RECEIPT_STAGE_LABELS[view.stage]); +``` + +`describeReceiptChains(view, input)` adds the chains' display labels. See +[receipts](/flows/receipts) for receipt links and a server-side worker. diff --git a/hooks/use-refund.mdx b/hooks/use-refund.mdx new file mode 100644 index 0000000..41dfc54 --- /dev/null +++ b/hooks/use-refund.mdx @@ -0,0 +1,261 @@ +--- +title: useRefund +description: Send USDC back to the payer of an earlier transfer from the connected merchant wallet. +--- + +`useRefund` sends a refund from the connected EVM wallet, which acts as the +merchant, to the wallet that paid you. + +```tsx RefundButton.tsx +import { useRefund } from "@usewhisk/react"; + +export function RefundButton() { + const { refund, isPending, data, error } = useRefund(); + + return ( ++ + {error ?+ ); +} +``` + +## What a refund is + +A refund in Whisk is a new transfer in the other direction. Nothing about the +original payment is reversed or touched: CCTP burns and mints cannot be +undone. The refund is an ordinary send or bridge from the merchant wallet, on +the chain where the payment landed, to the payer's address, on the chain you +choose. + +That has consequences for the money: + +- **The merchant wallet pays.** It needs the USDC on + `originalDestinationChain`, plus gas there (USDC on Arc). +- **The merchant pays the bridge fees.** With the default + `feeBearer: "sender"`, the burn is sized up so the payer receives the full + `amount`. With `"receiver"`, the payer receives `amount` less the fees. +- **Your own fee applies too.** If the provider config has a `feePolicy`, the + refund quote includes it, and the merchant wallet pays it like any payer + would (90% to your fee recipient, 10% to the Whisk treasury). The result's + `customFee` says whether it was paid. +- **Whisk does not check the original payment.** It does not look up + `originalTxHash`, compare `amount` with what was paid, or remember earlier + refunds. Partial refunds work, and so does refunding the same order twice. + Keep the refund state in your own order records and check it before calling. + +## Correlation metadata + +The result's `metadata` links the refund to the payment it returns. Whisk adds +two reserved keys on top of your own metadata: + +| Constant | Key | Value | +| ------------------- | ------------------ | -------------------------------- | +| `REFUND_OF_TX_KEY` | `__refundOfTxHash` | `originalTxHash`, trimmed | +| `REFUND_REASON_KEY` | `__refundReason` | `reason`, only when you pass one | + +Your own `metadata` cannot use keys that start with `__`; the refund is refused +with a `ConfigError` before anything is quoted. + +```ts useRefundOrder.ts +import { + REFUND_OF_TX_KEY, + REFUND_REASON_KEY, + useRefund, +} from "@usewhisk/react"; + +type Order = { + id: string; + paymentTxHash: string; + payer: string; + amount: string; +}; + +export function useRefundOrder() { + const { refundAsync } = useRefund(); + + return async function refundOrder(order: Order) { + const result = await refundAsync({ + originalTxHash: order.paymentTxHash, + originalDestinationChain: "Arc_Testnet", + refundDestinationChain: "Base_Sepolia", + originalSenderAddress: order.payer, + amount: order.amount, + reason: "out_of_stock", + metadata: { orderId: order.id }, + listeners: { onStep: (step) => console.log(step.name, step.state) }, + }); + + if (result.kind === "failure") throw result.error; + + // { orderId: "...", __refundOfTxHash: "0x...", __refundReason: "out_of_stock" } + console.log( + result.metadata?.[REFUND_OF_TX_KEY], + result.metadata?.[REFUND_REASON_KEY], + ); + await markRefunded(order.id, result.finalTxHash); + }; +} +``` + +## Variables + +`refund` and `refundAsync` take a `UseRefundVariables`: a `RefundInput` plus +optional `listeners`. + +{error.message}
: null} + {data?.kind === "failure" ? ( +{data.error.message}
+ ) : null} + {data?.kind === "success" ?Refunded.
: null} ++ Source-chain tx hash of the payment being refunded. Stored as + `__refundOfTxHash`. + + ++ Where the merchant received the payment. The refund is sent from here. + + ++ Where the payer gets the refund, usually the chain they paid from. Equal to + `originalDestinationChain` for a same-chain refund. + + ++ The payer's address on `refundDestinationChain`. + + ++ Decimal USDC, such as `"10.50"`. Must be positive. May be less than the + original payment. + + ++ At most 256 characters. Stored as `__refundReason`. + + ++ Your own correlation keys. No `__` prefixes. + + ++ `onStep` and `onBurnSubmitted`, as for a send. + + +## Result + ++ Starts a refund without returning a promise. The outcome lands on `data` or + `error`. + + ++ Starts a refund and resolves to its `RefundResult`. Rejects when the refund + throws. + + ++ The latest result. `RefundResult` is a `SendResult`: branch on `data.kind`. + + ++ Set when the refund threw: no wallet connected, invalid input, a quote that + could not be built, or a network failure. + + ++ `true` while a refund is in flight. + + ++ Clears `data` and `error`. + + +As with a send, a thrown error means nothing was signed. A `data.kind` of +`"failure"` after the burn means the merchant's USDC left and the mint is +still due; the refund sits in the in-flight store and can be finished with +`engine.resume` (see [recovery](/concepts/recovery)). + +## Refunds from or to other ecosystems + +`useRefund` uses the connected EVM wallet as `merchantAdapter` and has no way to +pass a `destinationAdapter`. That covers refunds out of an EVM chain into one +where Circle forwards the mint. For a merchant wallet on Solana, Stellar or +Starknet, or a refund into a chain that needs the destination wallet to sign +the mint, call `engine.refund` yourself: + +```ts useCrossEcosystemRefund.ts +import { + useAdapterFor, + useWhiskEngine, + type RefundInput, +} from "@usewhisk/react"; + +export function useCrossEcosystemRefund() { + const engine = useWhiskEngine(); + const adapterFor = useAdapterFor(); + + return async function refund(input: RefundInput) { + const merchantAdapter = adapterFor(input.originalDestinationChain); + if (!merchantAdapter) + throw new Error("Connect the wallet that received the payment."); + const destinationAdapter = adapterFor(input.refundDestinationChain); + + return engine.refund({ + ...input, + merchantAdapter, + ...(destinationAdapter && { destinationAdapter }), + }); + }; +} +``` + +## Building the metadata yourself + +`validateRefundInput` and `buildRefundMetadata` are the two steps +`engine.refund` runs before quoting. Use them to check refund input in a form, +or to tag a payout you send some other way with the same keys. + +```ts +import { buildRefundMetadata, validateRefundInput } from "@usewhisk/react"; + +const plan = validateRefundInput({ + originalTxHash: "0x9f2c...e41a", + originalDestinationChain: "Arc_Testnet", + refundDestinationChain: "Base_Sepolia", + originalSenderAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + amount: "4.50", + reason: "partial_return", +}); + +const metadata = buildRefundMetadata(plan.originalTxHash, plan.reason, { + orderId: "ord_123", +}); +// { orderId: "ord_123", __refundOfTxHash: "0x9f2c...e41a", __refundReason: "partial_return" } +``` + +`validateRefundInput` throws a `ConfigError` for an empty tx hash or address, +an amount that is not a positive decimal, a reason over 256 characters, or +invalid metadata. Chains are checked later, when the refund is quoted. +`buildRefundMetadata` does not merge an engine's `defaultMetadata`; pass your +metadata already merged if you need it. + +See [refunds](/flows/refunds) for the end-to-end merchant flow. diff --git a/hooks/use-whisk-engine.mdx b/hooks/use-whisk-engine.mdx new file mode 100644 index 0000000..5f31bc6 --- /dev/null +++ b/hooks/use-whisk-engine.mdx @@ -0,0 +1,157 @@ +--- +title: useWhiskEngine and useWhiskContext +sidebarTitle: useWhiskEngine +description: Reach the engine and config that WhiskProvider built, for direct engine calls inside React. +--- + +`useWhiskEngine` returns the `WhiskEngine` that `` created. Use it +for anything the other hooks do not wrap: balances, in-flight transfers, +resuming, or quoting with a non-EVM wallet. + +```tsx PendingTransfers.tsx +import { useEffect, useState } from "react"; +import { useWhiskEngine } from "@usewhisk/react"; +import type { InflightRecord } from "@usewhisk/core"; + +export function PendingTransfers() { + const engine = useWhiskEngine(); + const [records, setRecords] = useState ([]); + + useEffect(() => { + engine.inflight().then(setRecords, console.error); + }, [engine]); + + return ( + + {records.map((r) => ( +
+ ); +} +``` + +It is the same engine you would get from `createWhisk` in +[`@usewhisk/core`](/headless/core-engine), so every method on +[the engine reference](/reference/core/engine) is available. The difference is +what the provider set up for it: + +- It is built once, on the provider's first mount, from the provider's + `config`. Later changes to `config` do not reach it. +- Its resolver is `config.resolver`, or addresses plus ENS when you set none. +- Its in-flight store is `config.inflightStore`, or `localStorage` when the + page can write to it (memory otherwise, as in Safari private mode or during + server rendering). + +Methods that sign take an adapter. Get one from the +[wallet adapter hooks](/hooks/wallet-adapters). + +## Balances + +`engine.balance` returns USDC subunits as a `bigint` (6 decimals). Format it +only for display. + +```tsx UsdcBalance.tsx +import { useEffect, useState } from "react"; +import { formatUsdcAmount, useWhisk } from "@usewhisk/react"; + +export function UsdcBalance() { + const { engine, address } = useWhisk(); + const [balance, setBalance] = useState- + {r.sourceChain} to {r.destinationChain}: {r.step} +
+ ))} +(null); + + useEffect(() => { + if (!address) return; + engine + .balance({ chain: "Base_Sepolia", address }) + .then(setBalance, console.error); + }, [engine, address]); + + if (balance === null) return null; + return {formatUsdcAmount(balance)} USDC on Base Sepolia
; +} +``` + +`balance` and `maxSendable` read EVM chains only today. They return `null` for +a Solana, Stellar or Starknet source +([usewhisk/whisk#157](https://github.com/usewhisk/whisk/issues/157)). + +## Finishing a transfer + +A bridge is written to the in-flight store from the moment the payer is asked +to sign. If the page closes between the burn and the mint, the record is still +there on the next load. `engine.resume` finishes it without signing the burn +again. + +```ts useFinishTransfer.ts +import { useAdapterFor, useWhiskEngine } from "@usewhisk/react"; +import type { InflightRecord } from "@usewhisk/core"; + +export function useFinishTransfer() { + const engine = useWhiskEngine(); + const adapterFor = useAdapterFor(); + + return async function finish(record: InflightRecord) { + const destinationAdapter = adapterFor(record.destinationChain); + const result = await engine.resume(record, { + ...(destinationAdapter && { destinationAdapter }), + }); + if (result.kind === "success") await engine.dismiss(record.id); + return result; + }; +} +``` + +Records stay in the store until you call `dismiss`, even after a successful +mint. [``](/widget/resume-list) does this with its own UI; see +[recovery](/concepts/recovery) for the full flow. + +`InflightRecord` is exported from `@usewhisk/core`, not from +`@usewhisk/react`. Add `@usewhisk/core` to your dependencies to import its +type. + +## useWhiskContext + +`useWhiskContext` returns everything the provider holds: + + + The engine, as returned by `useWhiskEngine`. + + ++ The `config` prop passed to ` + +`, including `wallets` and + `chains`. + + The `theme` prop passed to ` + +```tsx ChainList.tsx +import { useWhiskContext } from "@usewhisk/react"; + +export function ChainList() { + const { config, engine } = useWhiskContext(); + + return ( +`. + + {config.chains.map((chain) => ( +
+ ); +} +``` + +`config` is the provider prop as you passed it. `engine.config` is what the +engine was built from, with defaults filled in (`feeBearer: "sender"`, +`useForwarder: true`), and it does not change after the first mount. + +Both hooks throw a `ConfigError` when called outside `- + {chain} + {chain === engine.config.defaultSourceChain + ? " (default source)" + : null} +
+ ))} +`, with a +message that says to wrap the tree in the provider. diff --git a/hooks/use-whisk.mdx b/hooks/use-whisk.mdx new file mode 100644 index 0000000..19be0f4 --- /dev/null +++ b/hooks/use-whisk.mdx @@ -0,0 +1,327 @@ +--- +title: useWhisk +description: The engine, the connected EVM wallet, and quote and send actions for a send UI you build yourself. +--- + +`useWhisk` gives a custom component what ` ` uses: the engine, the +connected EVM wallet, and `resolve`, `quote` and `send` bound to that wallet. + +```tsx WalletBadge.tsx +import { useWhisk } from "@usewhisk/react"; + +export function WalletBadge() { + const { isConnected, address, isSending } = useWhisk(); + + if (!isConnected) return Connect a wallet to send USDC.
; + return ( ++ {address} {isSending ? "(sending)" : null} +
+ ); +} +``` + +Call it anywhere under [``](/widget/whisk-provider). It reads the +EVM account from wagmi, so the provider needs `evm()` in `config.wallets` or an +outer `WagmiProvider` of your own. The hook covers EVM wallets only. For a +Solana, Stellar or Starknet source, get the adapter from +[`useAdapterFor`](/hooks/wallet-adapters) and call the engine directly. + +## Quote, then send + +`quote` and `send` take the same parameters as `engine.quote` and `engine.send`, +minus `adapter`: the hook fills in the connected wallet. Amounts are decimal +USDC strings such as `"1.50"`. + +```ts usePay.ts +import { useWhisk } from "@usewhisk/react"; + +export function usePay() { + const { resolve, quote, send } = useWhisk(); + + return async function pay(to: string, amount: string) { + const recipient = await resolve(to, "Arc_Testnet"); + const q = await quote({ + sourceChain: "Base_Sepolia", + destinationChain: "Arc_Testnet", + recipient, + amount, + }); + // Show q.amountIn and q.amountOut to the payer before this line. + return send( + { quote: q, metadata: { orderId: "ord_123" } }, + { + onStep: (step) => console.log(step.name, step.state), + onBurnSubmitted: (txHash) => console.log("burned in", txHash), + }, + ); + }; +} +``` + +`send` signs exactly what the quote says. It takes the chains, the recipient and +the amounts from `quote`, so there is nothing else to pass except optional +`metadata` (see [metadata](/flows/metadata)). A quote is good for 60 seconds +from `issuedAt`; check `quote.expiresAt` and fetch a fresh one before the payer +confirms a stale one. + +`send` ends in one of two ways: + +- It **throws** when it refuses before anything is signed: no wallet connected + (`ConfigError`), the quote expired (`QuoteExpiredError`), fees rose past what + the payer confirmed (`QuoteChangedError`, which carries the fresh quote on + `error.quote`), or the balance cannot cover the debit + (`InsufficientBalanceError`). No USDC has moved. +- It **resolves** to a `SendResult` once the wallet is involved. Branch on + `result.kind`. A `"failure"` after the burn means USDC left the payer's + wallet and has not been minted yet. The transfer is kept in the in-flight + store and can be finished; see [recovery](/concepts/recovery). + +## Returns + + + The engine built by ` + +`. Same object as + [`useWhiskEngine()`](/hooks/use-whisk-engine). + + The connected wagmi account as an `EvmAdapter`. `null` until an EVM wallet + connects. + + ++ The connected EVM address. + + ++ `true` when an EVM wallet is connected. + + ++ Turns an address or a name into a `ResolvedRecipient` for `chain`, using the + provider's resolver (addresses and ENS by default). Throws `ConfigError` when + nothing matches. + + ++ Builds a quote for the connected wallet. Throws `ConfigError` with no wallet + connected. Pass `destinationAdapter` for routes where Circle does not forward + the mint. + + ++ Sends a confirmed quote. `listeners.onStep` fires on every step change and + `listeners.onBurnSubmitted` fires with the burn hash as soon as the wallet + returns it. + + ++ `true` while a `send` is in flight. + + ++ The result of the latest `send`, success or failure. + + ++ Set when the latest `send` threw. The promise returned by `send` also rejects + with it. + + ++ Clears `lastResult` and `sendError`. It does not cancel a send in flight. + + +`isSending`, `lastResult` and `sendError` track `send` only. `quote` and +`resolve` keep no state, so track their loading and errors yourself. + +## The state machine + +`useWhisk` does not hold a flow state. `@usewhisk/core` ships the one Whisk uses +as a plain reducer, so a custom UI can reuse it with `useReducer`: +`WhiskState` is the state, `WhiskStateKind` is the union of its `kind` values, +and `reduce(state, action)` moves between them. + +| `kind` | Carries | Reached by | +| -------------- | ------------------------------------------------------- | -------------------------------------------------- | +| `disconnected` | nothing | `initialState`, `DISCONNECTED` | +| `idle` | nothing | `CONNECTED`, `RESET` | +| `resolving` | `input` | `RESOLVE_START` from `idle` or `resolved` | +| `resolved` | `recipient` | `RESOLVE_SUCCESS`, `REVIEW_BACK` | +| `quoting` | `recipient`, `amount` | `QUOTE_START` from `resolved` or `review` | +| `review` | `quote` | `QUOTE_SUCCESS` | +| `sending` | `quote`, `steps`, `currentStep` | `SEND_START` from `review`, `RETRY_START` | +| `succeeded` | `quote`, `steps`, `finalTxHash?` | `SEND_SUCCESS` | +| `failed` | `error`, and `quote`, `steps`, `raw` when a send failed | `RESOLVE_FAILURE`, `QUOTE_FAILURE`, `SEND_FAILURE` | + +An action that does not fit the current state returns the state unchanged +instead of throwing. `SEND_START` fills `steps` with every step of the route +as `pending` (`approve`, `transfer` for a same-chain send; `approve`, `burn`, +`fetchAttestation`, `mint` for a bridge), and each `STEP_UPDATE` merges one +step in. `RESET` goes back to `idle` from anywhere except `disconnected`. + +`reduce`, `initialState` and `initialSteps` are exported from `@usewhisk/core` +only. `@usewhisk/react` depends on it, but add it to your own `package.json` +before importing from it. The `WhiskState` and `WhiskStateKind` types are +exported from both packages. + +## Build a custom send UI + +This component quotes a Base Sepolia to Arc Testnet bridge, shows the review, +sends, and shows each step, all on Whisk's reducer. It starts in `idle` because +it renders a connect prompt itself while no wallet is connected. + +```tsx CustomSend.tsx +"use client"; + +import { useReducer, useState, type FormEvent } from "react"; +import { + toWhiskError, + useWhisk, + type Chain, + type ResolvedRecipient, +} from "@usewhisk/react"; +import { reduce } from "@usewhisk/core"; + +const SOURCE: Chain = "Base_Sepolia"; +const DESTINATION: Chain = "Arc_Testnet"; + +export function CustomSend() { + const { isConnected, resolve, quote, send } = useWhisk(); + const [state, dispatch] = useReducer(reduce, { kind: "idle" }); + const [to, setTo] = useState(""); + const [amount, setAmount] = useState(""); + + async function getQuote(event: FormEvent) { + event.preventDefault(); + dispatch({ type: "RESET" }); + dispatch({ type: "RESOLVE_START", input: to }); + let recipient: ResolvedRecipient; + try { + recipient = await resolve(to, DESTINATION); + } catch (err) { + dispatch({ type: "RESOLVE_FAILURE", error: toWhiskError(err) }); + return; + } + dispatch({ type: "RESOLVE_SUCCESS", recipient }); + dispatch({ type: "QUOTE_START", recipient, amount }); + try { + const q = await quote({ + sourceChain: SOURCE, + destinationChain: DESTINATION, + recipient, + amount, + }); + dispatch({ type: "QUOTE_SUCCESS", quote: q }); + } catch (err) { + dispatch({ type: "QUOTE_FAILURE", error: toWhiskError(err) }); + } + } + + async function confirm() { + if (state.kind !== "review") return; + dispatch({ type: "SEND_START" }); + try { + const result = await send( + { quote: state.quote }, + { onStep: (step) => dispatch({ type: "STEP_UPDATE", step }) }, + ); + if (result.kind === "success") { + dispatch({ type: "SEND_SUCCESS", finalTxHash: result.finalTxHash }); + } else { + dispatch({ + type: "SEND_FAILURE", + error: result.error, + raw: result.raw, + }); + } + } catch (err) { + dispatch({ type: "SEND_FAILURE", error: toWhiskError(err) }); + } + } + + if (!isConnected) returnConnect a wallet to continue.
; + + switch (state.kind) { + case "resolving": + case "quoting": + returnGetting a quote...
; + + case "review": + return ( +++ ); + + case "sending": + return ( +You pay {state.quote.amountIn} USDC
+Recipient gets at least {state.quote.amountOut} USDC
+Fees: {state.quote.fees.total} USDC
+ + ++ {state.steps.map((step) => ( +
+ ); + + case "succeeded": + return- + {step.name}: {step.state} +
+ ))} +Delivered. Mint tx: {state.finalTxHash ?? "not reported"}
; + + default: + return ( + + ); + } +} +``` + +A few things this leaves to you: + +- **Connecting.** Render [``](/widget/connect-modal) or your own + wagmi connect buttons where the prompt is. +- **Quote expiry.** If the payer waits more than 60 seconds on the review + screen, `send` throws `QuoteExpiredError` and the form shows its message. + Re-quote on a timer instead if you want the review to stay live. +- **Changed fees.** `QuoteChangedError` lands in `failed` the same way. Its + `error.quote` is the fresh quote if you would rather show it straight away. +- **Retry.** `RETRY_START` exists for the widget's own retry. To finish a + bridge that failed after the burn, use `engine.resume`; see + [recovery](/concepts/recovery). + +## Related + +- [`useAdapterFor`](/hooks/wallet-adapters) for non-EVM wallets. +- [`useReceipt`](/hooks/use-receipt) to follow a transfer after the burn. +- [Errors](/concepts/errors) for every `error.code`. diff --git a/hooks/wallet-adapters.mdx b/hooks/wallet-adapters.mdx new file mode 100644 index 0000000..297cde6 --- /dev/null +++ b/hooks/wallet-adapters.mdx @@ -0,0 +1,198 @@ +--- +title: Wallet adapter hooks +sidebarTitle: Wallet adapters +description: Turn the wallets connected through WhiskProvider into the adapters the engine signs with. +--- + +The engine never talks to a wallet directly. It builds calls and hands them to +a `WhiskAdapter`, one shape per ecosystem. These hooks turn whatever the payer +connected through ` ` into that shape. + +```ts useQuoteFrom.ts +import { useAdapterFor, useWhiskEngine, type Chain } from "@usewhisk/react"; + +export function useQuoteFrom() { + const engine = useWhiskEngine(); + const adapterFor = useAdapterFor(); + + return async function quoteFrom( + sourceChain: Chain, + destinationChain: Chain, + to: string, + amount: string, + ) { + const adapter = adapterFor(sourceChain); + if (!adapter) throw new Error(`Connect a wallet for ${sourceChain} first.`); + const destinationAdapter = adapterFor(destinationChain); + const recipient = await engine.resolve(to, destinationChain); + + return engine.quote({ + sourceChain, + destinationChain, + recipient, + amount, + adapter, + ...(destinationAdapter && { destinationAdapter }), + }); + }; +} +``` + +` ` uses them internally, so you only need them when you call the +engine yourself: a custom UI, a headless send, a refund from a non-EVM wallet, +or finishing a stuck transfer. + +## The hooks + +| Hook | Returns | `null` when | +| ---------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------- | +| `useEvmAdapter()` | `EvmAdapter \| null` | No wagmi account is connected | +| `useSolanaAdapter()` | `SolanaAdapter \| null` | No Wallet Standard wallet is connected, or `solana()` is not configured | +| `useStellarAdapter()` | `StellarAdapter \| null` | No Stellar wallet is connected, or `stellar()` is not configured | +| `useStarknetAdapter()` | `StarknetAdapter \| null` | No Starknet wallet is connected, or `starknet()` is not configured | +| `useAdapterFor()` | `(chain: Chain) => WhiskAdapter \| null` | The returned function gives `null` when no wallet for that chain's ecosystem is connected | + +Each adapter is rebuilt when its wallet's account changes, so read the hook +again rather than keeping an adapter in a ref. Every hook needs +[` `](/widget/whisk-provider) above it. `useEvmAdapter`, and so +`useAdapterFor`, read wagmi and also need `evm()` in `config.wallets` or a +`WagmiProvider` of your own. + +`useAdapterFor` picks by the chain's ecosystem, which is the usual way to get +both sides of a bridge: + +- `adapter`: `adapterFor(sourceChain)`, the wallet that pays and signs the + burn. +- `destinationAdapter`: `adapterFor(destinationChain)`, the wallet that signs + the mint on routes where Circle's Forwarder does not. Circle forwards burns + from EVM or Solana into EVM chains that support it; anything into Solana, + Stellar or Starknet, or out of Stellar or Starknet, needs it. Without it, + `quote` throws `RouteUnavailableError` with + `reason: "destination_adapter_required"`. + +## One ecosystem + +Use the specific hook when a component only handles one ecosystem. This one +quotes a Solana Devnet to Base Sepolia bridge. + +```tsx SolanaToBase.tsx +import { useEffect, useState } from "react"; +import { useSolanaAdapter, useWhiskEngine } from "@usewhisk/react"; + +export function SolanaToBase({ to, amount }: { to: string; amount: string }) { + const engine = useWhiskEngine(); + const solana = useSolanaAdapter(); + const [fees, setFees] = useState (); + + useEffect(() => { + if (!solana) return; + let cancelled = false; + engine + .resolve(to, "Base_Sepolia") + .then((recipient) => + engine.quote({ + sourceChain: "Solana_Devnet", + destinationChain: "Base_Sepolia", + recipient, + amount, + adapter: solana, + }), + ) + .then((quote) => { + if (!cancelled) setFees(quote.fees.total); + }) + .catch((err: unknown) => console.error(err)); + return () => { + cancelled = true; + }; + }, [engine, solana, to, amount]); + + if (!solana) return Connect a Solana wallet.
; + returnFees: {fees ?? "..."} USDC
; +} +``` + +`useWhisk` covers only the EVM wallet, so for a Solana, Stellar or Starknet +source you call `engine.quote` and `engine.send` with the adapter yourself. +Connecting those wallets is done through +[``](/widget/connect-modal). + +## What each adapter does + +All four come from `@usewhisk/core` and are discriminated on `kind`: + +```ts +import type { WhiskAdapter } from "@usewhisk/react"; + +export function describe(adapter: WhiskAdapter): Promise { + switch (adapter.kind) { + case "evm": + return adapter.getChainId().then((id) => `EVM chain ${id}`); + case "solana": + return adapter.getCluster(); + case "stellar": + return adapter.getNetwork(); + case "starknet": + return adapter.getChainId(); + } +} +``` + +| Adapter | `kind` | `address` | Signs with | +| ----------------- | ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `EvmAdapter` | `"evm"` | `0x` hex | `sendCalls(calls, options)`: one transaction per call, each waiting for the last to confirm, or one atomic batch | +| `SolanaAdapter` | `"solana"` | Base58 public key | `sendTransaction(instructions, { extraSigners })`: one transaction, partly signed by the engine's one-off keypairs first | +| `StellarAdapter` | `"stellar"` | `G...` strkey | `submitInvocation(invocations)`: one Soroban transaction per invocation, simulated, signed and polled until it lands | +| `StarknetAdapter` | `"starknet"` | felt252 hex | `submitCalls(calls)`: one multicall, so approve and burn land together | + +Each also has a confirm method (`waitForReceipt` on EVM, `confirmTransaction` +elsewhere) and a way to read its network: `getChainId` on EVM and Starknet, +`getCluster` on Solana, `getNetwork` on Stellar. The engine checks the network +before each write and, on EVM, calls `switchChain` when the wallet is on +another chain. Wallet and RPC failures come back as `WhiskError`s, with a +rejection in the wallet as `UserRejectedError`. + +The React adapters behave like this: + +- **EVM** (`useEvmAdapter`) sends through wagmi's `sendTransaction`. It waits + for two confirmations between calls, so a burn is never estimated against an + allowance a lagging RPC has not seen yet, and one confirmation after the + last. A reverted receipt throws. For a transfer that carries a merchant fee, + it reads wagmi's `getCapabilities` and, when the wallet supports atomic + EIP-5792 batches, sends the burn and the fee as one batch through wagmi's + `sendCalls`. On Arc, where every call carries its own gas price, the fee is + a separate request after the burn. See [when the fee is + paid](/concepts/quotes-and-fees#when-the-fee-is-paid). +- **Solana** (`useSolanaAdapter`) builds a legacy transaction with the wallet + as fee payer and the latest blockhash, and confirms at `confirmed`. The + cluster comes from `solana({ network })`: `mainnet-beta`, otherwise + `devnet`. +- **Stellar** (`useStellarAdapter`) signs through Stellar Wallets Kit and + waits up to 60 seconds for each transaction, so an `approve` lands before the + burn that spends it. Its `getTrustline` reads a recipient's USDC trustline + over Soroban RPC, which the engine checks before a burn into Stellar. +- **Starknet** (`useStarknetAdapter`) calls the wallet's + `wallet_addInvokeTransaction` and polls the configured RPC for up to 10 + minutes. + +## Outside React + +`createWagmiEvmAdapter(wagmiConfig, address)` is the function behind +`useEvmAdapter`. Use it where hooks cannot run, such as an event handler in +another store. It needs the wagmi `Config` the payer connected through, such as +the one you pass to your own `WagmiProvider`. + +```ts currentEvmAdapter.ts +import { getAccount, type Config } from "@wagmi/core"; +import { createWagmiEvmAdapter, type EvmAdapter } from "@usewhisk/react"; + +declare const wagmiConfig: Config; + +export function currentEvmAdapter(): EvmAdapter | null { + const { address } = getAccount(wagmiConfig); + return address ? createWagmiEvmAdapter(wagmiConfig, address) : null; +} +``` + +To write an adapter for a signer Whisk does not wrap, such as a server key or +an injected wallet outside React, see [the core engine](/headless/core-engine). diff --git a/index.mdx b/index.mdx new file mode 100644 index 0000000..cc12ae2 --- /dev/null +++ b/index.mdx @@ -0,0 +1,80 @@ +--- +title: "Whisk" +description: "Send and bridge USDC over Circle CCTP V2 across EVM chains, Solana, Stellar and Starknet, with a React widget or a framework-agnostic engine." +--- + +Whisk moves USDC between wallets: on one chain, or across chains through Circle's Cross-Chain Transfer Protocol V2 (CCTP V2). It covers EVM chains, Solana, Stellar and Starknet, and every pair of those ecosystems can bridge in both directions. You can embed it as a React widget, or drive the same engine from your own UI or a server. + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; +import "@usewhisk/react/styles.css"; + +const config = createWhiskConfig({ + wallets: [evm({ chains: ["Base_Sepolia", "Arc_Testnet"] })], + chains: ["Base_Sepolia", "Arc_Testnet"], +}); + +export default function App() { + return ( + + + ); +} +``` + +That renders a widget with a Send tab (USDC on one chain) and a Bridge tab (USDC across chains). It connects the payer's wallet, resolves the recipient, shows the fees before the payer confirms, and follows the transfer through approve, burn, attestation and mint. + +## What happens to the money + +A bridge burns USDC on the source chain and mints the same USDC on the destination. Circle's attestation service (Iris) signs the burn, and the mint is submitted either by Circle's Forwarding Service or by a wallet the payer connects on the destination. Whisk calls Circle's CCTP V2 contracts and Iris directly. There is no Whisk server in the path, and no private key ever reaches Whisk: every transaction is signed in the payer's wallet. + +Before anything is signed, the payer sees a quote with every fee in it. `send` signs exactly that quote, and refuses it if it expired or fees rose. Every bridge is saved from the moment the burn is signed, so if the tab closes between the burn and the mint, the widget lists the transfer after a reload and finishes the mint without a second burn. See [how it works](/concepts/how-it-works). + +Mainnet or testnet always follows the source chain. There is no `mode` option, and a route that mixes the two is refused before anything is signed. + +## Packages + +| Package | Use it when | +| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@usewhisk/react` | You have a React app. Ships `WhiskProvider`, the `WhiskSend` widget, receipts and resume UI, the wallet factories, and hooks such as `useWhisk`. | +| `@usewhisk/core` | You want the engine without React: a Vue or Svelte UI, a Node script, a server route. Exports `createWhisk`, the adapter interfaces, errors, fees and amounts. | +| `@usewhisk/cctp` | You want the protocol layer on its own: the chain registry, CCTP V2 contract addresses and ABIs, burn and mint builders, fee maths and the Iris client. | + +`@usewhisk/react` depends on `@usewhisk/core`, which depends on `@usewhisk/cctp`, so installing the widget brings the other two with it. These docs cover `@usewhisk/react` and `@usewhisk/core` 0.3.x, and `@usewhisk/cctp` 0.1.x. + +Using the engine without React looks like this: + +```ts server.ts +import { createWhisk } from "@usewhisk/core"; +import { getChain } from "@usewhisk/cctp"; + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); +const arc = getChain("Arc_Testnet"); +console.log(engine, arc.cctpDomain, arc.capabilities.fastSource); +``` + +## Where to go next + +console.log(result.finalTxHash)} /> + + diff --git a/installation.mdx b/installation.mdx new file mode 100644 index 0000000..072e07b --- /dev/null +++ b/installation.mdx @@ -0,0 +1,159 @@ +--- +title: "Installation" +description: "Packages, peer dependencies, stylesheets and framework setup for Whisk." +--- + +For a React app, install the widget package and its peers: + +```bash +npm install @usewhisk/react @tanstack/react-query viem +``` + +Then import the stylesheet once and render the widget: + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; +import "@usewhisk/react/styles.css"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia", "Arc_Testnet"], +}); + +export function App() { + return ( ++ A working send widget in a React app, on testnet. + ++ Routes, burns, attestations, mints and what Whisk does at each step. + ++ Every prop of the widget: locked fields, defaults, tabs and callbacks. + ++ Quote, send and resume transfers with `@usewhisk/core`, without React. + ++ The protocol layer: chains, builders, Iris and fees. + ++ + ); +} +``` + +`pnpm add`, `yarn add` and `bun add` work the same way. Every package needs Node 20 or later. + +## Packages + +| Package | Version | Install it when | +| ----------------- | ------- | ----------------------------------------------------------------------------------- | +| `@usewhisk/react` | 0.3.0 | You render the widget or use the React hooks. | +| `@usewhisk/core` | 0.3.0 | You run the engine outside React, or import from it directly in a React app. | +| `@usewhisk/cctp` | 0.1.1 | You use the CCTP protocol layer on its own (chain registry, builders, Iris client). | + +`@usewhisk/react` depends on `@usewhisk/core`, and `@usewhisk/core` depends on `@usewhisk/cctp`, so one install brings all three. `@usewhisk/react` re-exports the engine types, errors, chain helpers and amount helpers you are likely to need, so most React apps never import `@usewhisk/core` by name. + +Without React: + +```bash +npm install @usewhisk/core viem +``` + +See [core engine](/headless/core-engine) and [server usage](/headless/server). + +## Peer dependencies + +| Package | Peer | Range | +| ----------------- | ----------------------- | ------------- | +| `@usewhisk/react` | `react` | `>=18` | +| | `react-dom` | `>=18` | +| | `@tanstack/react-query` | `>=5` | +| | `viem` | `>=2.57.5 <3` | +| `@usewhisk/core` | `viem` | `>=2.57.5 <3` | +| `@usewhisk/cctp` | none | | + +`@usewhisk/cctp` lists `viem` (`>=2.57.5 <3`) as a regular dependency, so it shares your app's copy when the versions agree. + +Regular dependencies of `@usewhisk/react`, installed for you: + +- EVM: `wagmi` and `@wagmi/core` (`^2.17.0`) +- Solana: `@solana/web3.js`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-base` +- Stellar: `@stellar/stellar-sdk`, `@creit.tech/stellar-wallets-kit` +- Starknet: `starknet`, `@starknet-io/get-starknet-core` + +`@usewhisk/react` 0.3 needs `@wagmi/core` 2.17 or later, the first version with the EIP-5792 actions (`getCapabilities`, `sendCalls`, `waitForCallsStatus`) its EVM adapter uses. If your lockfile, overrides or resolutions hold `@wagmi/core` below 2.17, raise them. + +You do not install wallet libraries per ecosystem. Each ecosystem's provider is mounted only when its factory is in `config.wallets`. See [wallets](/wallets). + +## Stylesheets + +| Import | What it is | +| ---------------------------- | --------------------------------------------------------------------------------------------- | +| `@usewhisk/react/styles.css` | The widget's styles and default theme. Required for the bundled components. | +| `@usewhisk/react/fonts.css` | Optional. Loads Inter, Familjen Grotesk and Geist Mono from jsDelivr for apps that lack them. | + +```tsx +import "@usewhisk/react/styles.css"; +import "@usewhisk/react/fonts.css"; +``` + +Every rule in `styles.css` is scoped under `[data-whisk]`, the element `WhiskProvider` renders, so it does not restyle the rest of your page. Whisk loads no fonts by default: the widget asks for Inter and falls back to system fonts. Import `fonts.css` only if your app does not already load those faces. See [fonts](/theming/fonts) and [theming](/theming/overview). + +## Tailwind + +`@usewhisk/react/tailwind` exports `whiskTheme()`, a Tailwind preset that maps the `--whisk-*` CSS variables to classes such as `bg-whisk-primary` and `rounded-whisk`. The variables themselves still come from `styles.css`. + +```ts tailwind.config.ts +import { whiskTheme } from "@usewhisk/react/tailwind"; + +export default { + presets: [whiskTheme()], + content: ["./src/**/*.{ts,tsx}"], +}; +``` + +See [Tailwind](/theming/tailwind). + +## Headless entry + +`@usewhisk/react/headless` exports the provider, config builders, wallet factories and hooks, without the visual components. It needs no stylesheet. + +```ts +import { + WhiskProvider, + createWhiskConfig, + evm, + useWhisk, +} from "@usewhisk/react/headless"; +``` + +See [React headless](/headless/react-headless). + +## Next.js + +`WhiskProvider` and the hooks are client components. In the App Router, put the provider and the widget in a file that starts with `"use client"`, and load that file with `next/dynamic` and `ssr: false`, so wagmi and the wallet libraries do not start during prerender: + +```tsx app/pay-gate.tsx +"use client"; + +import dynamic from "next/dynamic"; + +const Pay = dynamic(() => import("./pay"), { ssr: false }); + +export function PayGate() { + return+ ; +} +``` + +Import `@usewhisk/react/styles.css` from your root layout. Environment variables read in the browser, such as a WalletConnect project ID, need the `NEXT_PUBLIC_` prefix. The `ecommerce-checkout`, `invoice-link` and `themed-saas` examples in the Whisk repository use this setup with Next.js 15. + +## Vite with Solana + +`@solana/web3.js` expects Node's `Buffer` global. Next.js provides it; Vite does not, so the first Solana operation throws `Buffer is not defined`. If you use `solana()` on Vite, install `buffer` and set the global at the top of your entry file, before anything imports Whisk: + +```bash +npm install buffer +``` + +```ts src/main.tsx +import { Buffer } from "buffer"; + +if (typeof globalThis.Buffer === "undefined") { + globalThis.Buffer = Buffer; +} +``` + +Skip this if you do not use Solana. The `donate-button` and `payroll-batch` examples run on Vite 6 with this polyfill. diff --git a/logo/whisk.png b/logo/whisk.png new file mode 100644 index 0000000..aa43e59 Binary files /dev/null and b/logo/whisk.png differ diff --git a/migration/0-1-to-0-2.mdx b/migration/0-1-to-0-2.mdx new file mode 100644 index 0000000..46eead6 --- /dev/null +++ b/migration/0-1-to-0-2.mdx @@ -0,0 +1,511 @@ +--- +title: "Migrate from 0.1 to 0.2" +sidebarTitle: "0.1 to 0.2" +description: "Upgrade @usewhisk/core and @usewhisk/react from 0.1 to 0.2, which replace Circle App Kit with a direct CCTP V2 integration." +--- + +This page is for apps on `@usewhisk/core@0.1.0` or `@usewhisk/react@0.1.0`. Start by upgrading both packages and adding `viem`, which is now a peer dependency: + +```bash +npm install @usewhisk/react@^0.2.0 @usewhisk/core@^0.2.0 viem@^2.57.5 +``` + +Whisk 0.2 no longer uses Circle App Kit. It calls Circle's CCTP V2 contracts and the Iris API directly, through a new package, `@usewhisk/cctp@0.1.0`. A transfer's network now comes from its source chain, so the `mode` option is gone. Whisk 0.2 also adds Stellar and Starknet next to EVM chains and Solana, bound quotes, resumable transfers, theme presets and a balance with a Max button. + +Chain ids did not change. Every chain id from 0.1 works in 0.2. + +There are 16 breaking changes below. The [upgrade checklist](#upgrade-checklist) at the end lists the work in order. + +## Install + +`@usewhisk/core` only needs to be a direct dependency if you import from it. `@usewhisk/cctp` is installed for you as a dependency of `@usewhisk/core`. + +### Dependency changes + +| Package | 0.1 | 0.2 | +| ----------------- | --------------------------------------------------- | ------------------------------------------------------ | +| `@usewhisk/core` | depends on `@circle-fin/app-kit` | depends on `@usewhisk/cctp`; peer `viem` `>=2.57.5 <3` | +| `@usewhisk/react` | peers `react`, `react-dom`, `@tanstack/react-query` | same peers, plus `viem` `>=2.57.5 <3` | + +Removed from the dependency tree: + +- `@circle-fin/app-kit` +- `@circle-fin/adapter-viem-v2` +- `@circle-fin/adapter-solana-kit` +- `@solana/kit` +- `nanoevents` + +If your app installed any of these only for Whisk, you can remove them. + +The Stellar and Starknet wallet libraries (`@creit.tech/stellar-wallets-kit`, `@starknet-io/get-starknet-core`, `@stellar/stellar-sdk`, `starknet`) are regular dependencies of `@usewhisk/react`. You do not install anything extra to use them. See [installation](/installation). + +## Breaking changes + +### 1. Chain ids are unchanged, and 19 were added + +`Chain` is still a union of Circle's chain name strings. All 37 ids from 0.1 exist in 0.2 with the same spelling. None were renamed or removed. + +0.2 adds these ids: + +- EVM mainnets: `Arc`, `Cronos`, `Edge`, `Injective`, `Morph`, `Pharos`, `Plasma`, `X_Layer` +- EVM testnets: `Cronos_Testnet`, `Edge_Testnet`, `Injective_Testnet`, `Morph_Testnet`, `Pharos_Testnet`, `Plasma_Testnet`, `X_Layer_Testnet` +- Stellar: `Stellar`, `Stellar_Testnet` +- Starknet: `Starknet`, `Starknet_Sepolia` + +`ChainKind` was `"evm" | "solana"`. It is now `"evm" | "solana" | "stellar" | "starknet"`. A `switch` over it needs the two new cases: + +```ts +import type { ChainKind } from "@usewhisk/react"; + +export function walletLabel(kind: ChainKind): string { + switch (kind) { + case "evm": + return "EVM"; + case "solana": + return "Solana"; + case "stellar": + return "Stellar"; + case "starknet": + return "Starknet"; + } +} +``` + +The `evm()` wallet factory cannot switch a wallet to the new `Cronos`, `Edge`, `Injective`, `Morph`, `Pharos`, `Plasma` and `X_Layer` ids or their testnets. See [chains](/chains). + +### 2. `mode` is removed + +In 0.1, `mode` (`"mainnet"` or `"testnet"`) was set on the config or inferred from `chains`. In 0.2 each transfer takes its network from its source chain. + +- `mode` is gone from `createWhisk` and `createWhiskConfig`. +- `WhiskMode`, `inferMode` and `resolveMode` are removed. +- `createDefaultResolver` no longer takes `mode`. It picks Sepolia or mainnet ENS from the destination chain's network. +- A config may list mainnet and testnet chains together. `WhiskSend` offers only destinations on the same network as the selected source chain. +- If a source and destination are on different networks, `quote` throws `NetworkMismatchError` before anything is signed. + + + +```tsx 0.1 +const config = createWhiskConfig({ + wallets: [evm({ projectId })], + chains: ["Arc_Testnet", "Base_Sepolia"], + mode: "testnet", +}); +``` + +```tsx 0.2 +const config = createWhiskConfig({ + wallets: [evm({ projectId })], + chains: ["Arc_Testnet", "Base_Sepolia"], +}); +``` + + + +See [chains](/chains#network-comes-from-the-chain). + +### 3. App Kit, swap and the kit key are removed + +0.1 ran transfers through Circle App Kit and offered a swap tab that needed a Circle Console kit key. 0.2 moves USDC only, with CCTP V2. + +Removed from `@usewhisk/react`: + +- `WhiskSend` props: `kitKey`, `defaultTab`, `swapDefaultChain`, `swapDefaultTokenIn`, `swapDefaultTokenOut`, `onSwapSuccess`, `onSwapError`, `onSwapStateChange` +- `SwapTab`, `SwapTabProps`, `WhiskSendTab` +- `useWhiskSwap`, `UseWhiskSwapResult`, `SwapState`, `SwapInput` + +Removed from `@usewhisk/core`: + +- `engine.estimateSwap` and `engine.swap` +- `SwapParams` (which held `kitKey`), `SwapEstimate`, `SwapResult`, `SwapSuccess`, `SwapFailure` +- `fromAppKitFees` + +There is no kit key or app ID to configure in 0.2. + +### 4. `WhiskSend` props + +| 0.1 | 0.2 | +| -------------------------------------------------------- | ----------------------------------------------- | +| `tabs?: ("transfer" \| "swap")[]` | `tabs?: ReadonlyArray<"send" \| "bridge">` | +| `onSuccess?: (result: { quote; finalTxHash? }) => void` | `onSuccess?: (result: SendSuccess) => void` | +| `onError?: (error: Error) => void` | `onFailure?: (result: SendFailure) => void` | +| `onStateChange` | removed | +| `onAmountChange`, `onRecipientChange` | removed | +| `onSourceChainChange`, `onDestinationChainChange` | removed | +| `showFooter`, `className` | removed | +| `amount`, `recipient`, `sourceChain`, `destinationChain` | unchanged (each locks its field) | +| `defaultAmount`, `defaultRecipient` | unchanged | +| none | `defaultSourceChain`, `defaultDestinationChain` | +| none | `title`, `description` | + +The 0.1 `"transfer"` tab covered same-chain sends and bridges. In 0.2 these are two tabs, `"send"` and `"bridge"`, and both show by default. + +`onSuccess` now receives the engine's `SendSuccess` (`finalTxHash`, `steps`, `metadata`), not the quote. `onFailure` receives a `SendFailure` with a typed `error`. An error thrown before the engine returns a result is shown in the widget and does not call `onFailure`. + +The widget always shows a "Powered by Whisk" badge. + ++ +```tsx 0.1 + + +See [WhiskSend](/widget/whisk-send). + +### 5. `WhiskProvider` theme + +| 0.1 | 0.2 | +| ------------------------------- | --------------------------------------------------------------------------------------- | +| `"light" \| "dark" \| "system"` | `"light" \| "dark" \| "auto"`, a named palette, a `WhiskTheme`, or `{ preset, tokens }` | +| default `"system"` | default `"light"` | + +`"system"` is renamed `"auto"`. The default no longer follows the OS. To keep the 0.1 behavior, pass `theme="auto"`: + +```tsx +track(quote.amountOut, finalTxHash)} + onError={(error) => report(error)} + showFooter +/> +``` + +```tsx 0.2 + track(result.finalTxHash)} + onFailure={(result) => report(result.error)} +/> +``` + + + +``` + +See [theming](/theming/overview). + +### 6. `feeBearer` defaults to `"sender"` + +In 0.1 the default was `"receiver"`: bridge fees came out of the amount, and the recipient got less than the payer entered. In 0.2 the default is `"sender"`: the payer covers the fees, and the recipient gets the amount entered. The payer's debit grows by the fees. + ++ + This changes what payers are charged without any code change on your side. If + your prices already account for bridge fees, or recipients should keep paying + them, set `feeBearer: "receiver"`. + + +```tsx +const config = createWhiskConfig({ + wallets: [evm({ projectId })], + chains: ["Arc_Testnet", "Base_Sepolia"], + feeBearer: "receiver", +}); +``` + +See [quotes and fees](/concepts/quotes-and-fees). + +### 7. Custom fee split + +`feePolicy` still splits the fee 90% to your `recipient` and 10% elsewhere. In 0.1, App Kit sent the 10% to Arc. In 0.2 it goes to the Whisk treasury, exported as `WHISK_TREASURY_ADDRESS`. `feePolicy.bps` was swap only in 0.1 and is ignored in 0.2. Use `value`, a decimal USDC string such as `"0.25"`, which the payer pays on top of the transfer. + +### 8. USDC only + +0.1 used the `token` option for same-chain sends of other tokens, such as EURC or USDT. 0.2 moves USDC on every route, whatever `token` says: the `Token` type still lists the other symbols, but no route moves them. Remove any `token` setting other than `"USDC"`. + +### 9. `useWhisk` is a different hook + +In 0.1, `useWhisk()` returned a state machine: `{ state, actions, connected, address }`, with `actions.resolve`, `actions.quote`, `actions.send`, `actions.retry`, `actions.back` and `actions.reset`. + +In 0.2 it returns the engine and promise-based calls for the connected EVM wallet: `engine`, `adapter`, `address`, `isConnected`, `resolve`, `quote`, `send`, `isSending`, `lastResult`, `sendError` and `reset`. It signs with the EVM wallet only. For other ecosystems, use `useWhiskEngine` with `useSolanaAdapter`, `useStellarAdapter`, `useStarknetAdapter` or `useAdapterFor`. + ++ +```tsx 0.1 +const { state, actions, connected } = useWhisk(); + +await actions.resolve(input, "Base_Sepolia"); +// then actions.quote(recipient, amount, sourceChain) and actions.send() +``` + +```tsx 0.2 +import { useWhisk } from "@usewhisk/react"; + +export function usePay() { + const { resolve, quote, send, isConnected } = useWhisk(); + + return async function pay(input: string) { + if (!isConnected) throw new Error("Connect an EVM wallet first."); + const recipient = await resolve(input, "Base_Sepolia"); + const q = await quote({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient, + amount: "10", + }); + return send({ quote: q }); + }; +} +``` + + + +`reduce`, `initialState` and `initialSteps` are still exported from `@usewhisk/core` if you drive your own state machine. See [useWhisk](/hooks/use-whisk). + +### 10. Removed hooks and components + +| 0.1 | 0.2 | +| --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| `useWhiskAdapter(chain)` | `useAdapterFor()(chain)`, or `useEvmAdapter`, `useSolanaAdapter`, `useStellarAdapter`, `useStarknetAdapter` | +| `useWhiskAccount` | no equivalent; read the wallet library directly (for EVM, wagmi's `useAccount`) | +| `useChainBalance` | `engine.balance({ chain, address })` | +| `useManualMint` | `engine.resume`, `engine.resumeFromTx`, or `WhiskReceipt` | +| `usePreflight`, `useTabLock` | no equivalent | +| `useWhiskSwap`, `SwapTab` | removed with swap | +| `Input`, `Field`, `FieldBoxSelect`, `Badge`, `ChainIcon`, `TokenIcon`, `TokenPicker`, `AccountChip`, `NetworkPill`, `BalanceLine` | removed | + +`Button`, `Card`, `FieldBox`, `ChainPicker`, `StepRail`, `Banner` and `ConnectModal` are still exported, and `PoweredByWhisk` is new. Check your props against the 0.2 types if you use them directly. See [primitives](/widget/primitives). + +### 11. Wallet factories + +- `evm()` takes the same options: `chains`, `projectId`, `rpcUrls`, `appName`. +- `solana()` drops `cluster` (use `network`) and `wallets`. Solana wallets are found through Wallet Standard, so legacy adapters are not passed in. +- `stellar()` and `starknet()` are new. +- `evm()` is no longer required. A config with only `solana()`, `stellar()` or `starknet()` is accepted. + +See [wallets](/wallets). + +### 12. Chain lookups + +Core's chain table is replaced by the registry in `@usewhisk/cctp`, re-exported from `@usewhisk/core` and `@usewhisk/react`. + +| 0.1 | 0.2 | +| ---------------------------------------- | --------------------------------------------------------------- | +| `chainInfo(chain)` | `getChain(chain)` | +| `chainByEvmId(id)` (returns `undefined`) | `tryChainByEvmChainId(id)`, or `chainByEvmChainId(id)` (throws) | +| `allChains()` | `CHAINS` | +| `chainsByKind(kind)` | `CHAINS.filter((c) => c.ecosystem === kind)` | +| `chainsByNetwork(network)` | `chainsByNetwork(network)`, returns registry entries | +| `cctpDomainFor(chain)` | `getChain(chain).cctpDomain` | +| `chainForCctpDomain(domain)` | `chainByDomain(domain, network)` | +| `supportedTokensFor`, `tokenAddressFor` | removed; `getChain(chain).usdc` for the USDC address | +| `ChainInfo`, `SupportedTokenAlias` | `CctpChain` | + +Field names on an entry changed too: `chain` is `id`, `kind` is `ecosystem`, `nativeSymbol` is `nativeCurrency.symbol`, and `usdcAddress` is `usdc`. For the input pattern and hint (`addressRegex` and `addressHint` in 0.1), use `addressFormat(chain)`, which returns `{ pattern, hint }`. `explorerTxUrl` and `explorerAddressUrl` keep their signatures. + +```ts +import { + CHAINS, + addressFormat, + chainByDomain, + chainByEvmChainId, + chainsByNetwork, + explorerTxUrl, + getChain, + tryChainByEvmChainId, + type CctpChain, +} from "@usewhisk/react"; + +const base: CctpChain = getChain("Base"); +console.log(base.id, base.ecosystem, base.nativeCurrency.symbol, base.usdc); +console.log(chainByEvmChainId(8453).id, tryChainByEvmChainId(1)?.id); +console.log(CHAINS.filter((c) => c.ecosystem === "solana").map((c) => c.id)); +console.log(chainsByNetwork("testnet").length); +console.log(chainByDomain(6, "mainnet").id); +const { pattern, hint } = addressFormat("Solana"); +console.log(pattern, hint, explorerTxUrl("Base", "0xabc")); +``` + +### 13. Core engine: `send` takes the quote + +This applies if you call `@usewhisk/core` directly. + +In 0.1, `send` took the quote parameters again plus the quote. In 0.2 it takes the quote the payer confirmed and reads the chains, recipient and amount from it. + ++ +```ts 0.1 +const quote = await engine.quote({ + sourceChain, + destinationChain, + recipient, + amount, + adapter, +}); +const result = await engine.send({ + sourceChain, + destinationChain, + recipient, + amount, + adapter, + quote, +}); +``` + +```ts 0.2 +const quote = await engine.quote({ + sourceChain, + destinationChain, + recipient, + amount, + adapter, +}); +const result = await engine.send({ quote, adapter }); +``` + + + +`send` can now throw before signing. Handle both quote errors: + +```ts +import { QuoteChangedError, QuoteExpiredError } from "@usewhisk/core"; + +try { + const result = await engine.send({ quote, adapter }); + console.log(result.kind); +} catch (err) { + if (err instanceof QuoteChangedError) { + console.log("confirm", err.quote.amountIn); + } else if (err instanceof QuoteExpiredError) { + console.log("quote again"); + } else { + throw err; + } +} +``` + +`QuoteChangedError` carries the fresh quote as `err.quote`; show it to the payer and send it once they confirm. On `QuoteExpiredError`, call `engine.quote` again. + +Other engine changes: + +- `engine.retry` and `RetryParams` are removed. Use `engine.resume` or `engine.resumeFromTx`. +- `QuoteParams` and `SendParams` take an optional `destinationAdapter`. A route whose mint Circle does not forward throws `RouteUnavailableError` with `reason: "destination_adapter_required"` until you pass one. +- `SendFailure.raw` is Whisk's recovery snapshot, not App Kit's `BridgeResult`. +- `Quote` gains `id`, `issuedAt`, `expiresAt`, `feeMode`, `subunits` and `plan`, and `amountBurned` is required. Code that builds a `Quote` by hand no longer type checks. Get quotes from `engine.quote`. + +See [core engine](/headless/core-engine). + +### 14. Wallet adapters + +This applies if you built a `WhiskAdapter` yourself. + +In 0.1, `WhiskAdapter` was `{ appKitAdapter, kind, address }`, wrapping an App Kit adapter. In 0.2 it is a union of `EvmAdapter`, `SolanaAdapter`, `StellarAdapter` and `StarknetAdapter`. Each one signs and submits the calls the engine builds. `@usewhisk/react` ships them as hooks (`useEvmAdapter`, `useSolanaAdapter`, `useStellarAdapter`, `useStarknetAdapter`), and `createWagmiEvmAdapter(config, address)` builds the EVM one outside React. See [wallet adapters](/hooks/wallet-adapters). + +### 15. Errors + +`WhiskErrorCode` has four new codes. An exhaustive `switch` over it needs them: + +| Code | Class | When | +| ------------------- | ----------------------- | -------------------------------------------------------------------------------------- | +| `NETWORK_MISMATCH` | `NetworkMismatchError` | source and destination are on different networks | +| `ROUTE_UNAVAILABLE` | `RouteUnavailableError` | a wallet is missing, the recipient cannot receive, or source and destination are equal | +| `QUOTE_EXPIRED` | `QuoteExpiredError` | the quote is past `expiresAt` | +| `QUOTE_CHANGED` | `QuoteChangedError` | fees rose past what the payer confirmed | + +`RouteUnavailableError.reason` says which: `"source_adapter_required"`, `"destination_adapter_required"`, `"recipient_account_missing"` or `"same_chain"`. + +```ts +import type { WhiskErrorCode } from "@usewhisk/react"; + +export function message(code: WhiskErrorCode): string { + switch (code) { + case "NETWORK_MISMATCH": + return "Pick a source and destination on the same network."; + case "ROUTE_UNAVAILABLE": + return "Connect the wallet this route needs."; + case "QUOTE_EXPIRED": + return "The quote expired. Get a new one."; + case "QUOTE_CHANGED": + return "Fees went up. Confirm the new quote."; + default: + return "Something went wrong."; + } +} +``` + +All four are thrown before anything is signed. `@usewhisk/react` re-exports all four classes, so a React app does not need to import `@usewhisk/core` for them. See [errors](/concepts/errors). + +### 16. In-flight transfers from 0.1 + +0.1 saved failed bridges in `localStorage` as snapshots. 0.2 uses a new record format and ignores 0.1 snapshots. The 0.1 helpers (`saveInflight`, `loadInflight`, `clearInflight`, `listInflightSnapshots`, `serializeError`, `deserializeError`, `INFLIGHT_TTL_MS`, `STORAGE_PREFIX`, `InflightSnapshot`, `WalletKind`) are removed. + ++ A payer whose 0.1 bridge burned but never minted will not see it in the 0.2 + widget's resume list. The USDC is not lost: finish the mint from the burn's + transaction hash, with the Finish transfer button in `WhiskReceipt` or with + `engine.resumeFromTx`. + + +```ts +import { createWhisk, type WhiskAdapter } from "@usewhisk/core"; + +declare const adapter: WhiskAdapter; +declare const burnTxHash: string; + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); + +const result = await engine.resumeFromTx({ + sourceChain: "Base_Sepolia", + txHash: burnTxHash, + destinationAdapter: adapter, +}); +console.log(result.kind); +``` + +`destinationAdapter` is the wallet that signs the mint. Leave it out when Circle forwards the mint on that route. See [recovery](/concepts/recovery) and [WhiskReceipt](/widget/whisk-receipt). + +## New in 0.2 + +- **Bound quotes.** `send` signs exactly the fees in the quote the payer saw. A quote lasts 60 seconds. `WhiskSend` refreshes it before it expires and asks the payer to confirm again when fees rise. +- **Resumable transfers.** Every bridge is saved in an `InflightStore` from before the wallet signs until the mint. `WhiskProvider` uses `localStorage` by default (`createBrowserInflightStore`); pass `inflightStore` to change it. `engine.inflight()`, `engine.resume(record)`, `engine.resumeFromTx(...)` and `engine.dismiss(id)` manage them. `WhiskSend` lists unfinished transfers with Resume and Dismiss, and `ResumeList` is exported on its own. +- **Receipts.** `WhiskReceipt` and `useReceipt` show a transfer's status from Iris. +- **More ecosystems.** Stellar and Starknet, through `stellar()` and `starknet()`, next to EVM and Solana, on mainnet and testnet. +- **Theme presets.** `theme` takes `"light"`, `"dark"`, `"auto"`, `"wine"`, `"indigo"`, `"emerald"`, `"monochrome"`, a full `WhiskTheme`, or `{ preset, tokens }`. `themePresets`, `getThemePreset` and `resolveTheme` are exported. +- **Balance and Max.** `engine.balance({ chain, address })` and `engine.maxSendable(params)` read the payer's USDC on EVM chains (`null` on Solana, Stellar and Starknet). `WhiskSend` shows the balance with a Max button. +- **Typed errors.** The new error classes above, with `RouteUnavailableError.reason` for the cause. +- **Refunds and metadata.** `engine.refund` and `useRefund` send funds back to a payer. `SendParams.metadata` and `WhiskConfig.defaultMetadata` (on `createWhisk`) tag transfers. See [refunds](/flows/refunds) and [metadata](/flows/metadata). +- **Webhook signing.** `signWebhook` and `verifyWebhook` in `@usewhisk/core`, for server code. +- **Amount helpers.** `parseUsdcAmount` and `formatUsdcAmount` convert between decimal strings and `bigint` subunits. See [amounts and units](/concepts/amounts-and-units). + +## Upgrade checklist + ++ diff --git a/migration/0-2-to-0-3.mdx b/migration/0-2-to-0-3.mdx new file mode 100644 index 0000000..8304ec3 --- /dev/null +++ b/migration/0-2-to-0-3.mdx @@ -0,0 +1,315 @@ +--- +title: "Migrate from 0.2 to 0.3" +sidebarTitle: "0.2 to 0.3" +description: "Upgrade @usewhisk/core and @usewhisk/react from 0.2 to 0.3, which never take the merchant fee before the burn and check Stellar and Starknet recipients before anything is signed." +--- + +This page is for apps on `@usewhisk/core` or `@usewhisk/react` 0.2.x. Start by upgrading both packages: + +```bash +npm install @usewhisk/react@^0.3.0 @usewhisk/core@^0.3.0 +``` + +0.3 is a fund-safety release. It gathers three fixes: + +- **0.2.1:** bridges into Stellar and Starknet check the destination before the burn, including the Stellar recipient's USDC trustline. +- **0.2.2** (with `@usewhisk/cctp` 0.1.1): a quote into Starknet refuses an Ethereum-shaped address and, unless the payer confirms, an address with no account deployed. +- **0.3.0:** a `feePolicy` fee is never sent before the burn or the same-chain transfer, and results say whether it was paid. + +`@usewhisk/react` 0.2.x depends on `@usewhisk/core` `^0.2.0`, so an app that reinstalled since 0.2.0 may already run the 0.2.1 and 0.2.2 checks. Everything below applies either way. + +Most apps only need the install above. Read on if you set a `feePolicy`, write your own wallet adapters, switch over `RouteUnavailableReason`, or bridge into Starknet. The [upgrade checklist](#upgrade-checklist) at the end lists the work in order. + +## Install + +### Dependency changes + +| Package | 0.2 | 0.3 | +| ----------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------- | +| `@usewhisk/react` | depends on `@usewhisk/core` `^0.2.0` and `@wagmi/core` `^2.16.3` | depends on `@usewhisk/core` `^0.3.0` and `@wagmi/core` `^2.17.0` | +| `@usewhisk/core` | depends on `@usewhisk/cctp` `^0.1.0` | depends on `@usewhisk/cctp` `^0.1.1` | +| Peers | `react`, `react-dom`, `@tanstack/react-query`, `viem` `>=2.57.5 <3` | unchanged | + +`@wagmi/core` 2.17 is the first version with the EIP-5792 actions the React EVM adapter now uses: `getCapabilities`, `sendCalls` and `waitForCallsStatus`. It is a regular dependency of `@usewhisk/react`, so a normal install picks it up. If your lockfile, `overrides` or `resolutions` hold `@wagmi/core` below 2.17, raise them. + +## Changes + +### 1. The merchant fee comes with the burn or after it + +In 0.2 a `feePolicy` fee went out as USDC transfers ahead of the approve and the burn. A payer who then rejected the burn, or whose burn reverted, had paid the fee for nothing. + +In 0.3, on an EVM source: + +- When the adapter's `supportsAtomicBatch` says yes for the source chain, the approve, the burn and the fee shares go in one `sendCalls` with `atomic: true`. The wallet lands all of them or none. +- Otherwise the burn or transfer goes alone. Once it lands, the engine asks for each fee share as its own request, before waiting for the attestation. A payer who rejects that request, or whose fee transfer reverts, still gets the transfer. + +`useEvmAdapter` answers `supportsAtomicBatch` from wagmi's `getCapabilities`. On Arc every call carries its own gas price, which a batch cannot carry, so on Arc the fee is always a separate request after the burn. + ++ Install `@usewhisk/react@^0.2.0`, `@usewhisk/core@^0.2.0` if you import it, + and `viem@^2.57.5`. + ++ Remove `mode` from `createWhiskConfig` and `createWhisk`, and from + `createDefaultResolver`. + ++ Remove `kitKey`, the swap props, `SwapTab` and `useWhiskSwap`. + ++ Rename `onError` to `onFailure`, update `onSuccess`, and change `tabs` to + `"send"` and `"bridge"`. + ++ Change `theme="system"` to `theme="auto"`, or pass `"auto"` if you relied on + the old default. + ++ Set `feeBearer: "receiver"` if recipients should keep paying bridge fees. + ++ Replace removed chain helpers with `getChain`, `CHAINS` and + `chainByEvmChainId`. + ++ Rewrite `useWhisk` callers and direct `engine.send` calls to pass the quote. + ++ Handle `QuoteChangedError`, `QuoteExpiredError`, `NetworkMismatchError` and + `RouteUnavailableError`. + ++ Finish any 0.1 transfer that burned but never minted, using its burn hash. + ++ Run a testnet transfer end to end, on every route you offer, before + shipping. + ++ A payer on a wallet without atomic batches can now decline the fee and keep + the transfer. If you fulfil orders from `onSuccess`, check `customFee` first. + + +Nothing changes on Solana, Stellar and Starknet sources: the quote still lists the fee, and no fee transfer is sent. + +See [when the fee is paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + +### 2. Results carry `customFee` + +`SendSuccess` and `SendFailure` gain `customFee?: CustomFeeOutcome`. It is set whenever a fee policy charged the transfer, which means on EVM sources with a `feePolicy` whose `value` is above zero. + +```ts +type CustomFeeOutcome = + | { status: "paid"; txHashes: `0x${string}`[]; amount: string } + | { + status: "unpaid"; + amount: string; + error?: WhiskError; + txHashes?: `0x${string}`[]; + }; +``` + +- `paid`: every share landed. `txHashes` are the fee's transactions, or the one hash of an atomic batch that shares it. +- `unpaid` with `error`: the burn or transfer landed, then the payer rejected the fee or it reverted. `txHashes` lists a share that landed before the payer stopped, if any. +- `unpaid` with no `error`: the fee was never asked for, because the burn or transfer did not land. + +`amount` is the whole fee as a decimal USDC string. `CustomFeeOutcome` is exported from `@usewhisk/core`; from `@usewhisk/react`, use `NonNullable`. + + + +```tsx 0.2 + + +`fulfil(result.finalTxHash)} /> +``` + +```tsx 0.3 + { + if (result.customFee?.status === "unpaid") { + holdOrder(result.customFee.amount, result.finalTxHash); + return; + } + fulfil(result.finalTxHash); + }} +/> +``` + + ` itself now adds "The 0.25 USDC fee was not paid" to its success banner, with the reason, when `customFee` is `unpaid`. + +In-flight records gain `customFee: { amount, status, txHashes? }`, with `amount` in subunits. A transfer resumed with `resume` or `resumeFromTx` reports the fee from its record and never asks the payer for it again. Records written by 0.2 have no `customFee` and still load. If you store records yourself, keep the new field. + +### 3. Custom EVM adapters: `supportsAtomicBatch` and `atomic` + +This applies if you built an `EvmAdapter` yourself. + +`EvmAdapter` gains an optional `supportsAtomicBatch(chainId)`, and `SendCallsOptions` an optional `atomic`. Both are optional, so a 0.2 adapter still compiles and works: without `supportsAtomicBatch`, the engine never sets `atomic`, and sends the fee as separate `sendCalls([call])` requests once the burn has landed. + +Implement them only when your wallet can land a batch all or nothing. With `atomic: true`, `sendCalls` must land every call or none, or throw `WalletCapabilityError("atomic_unsupported", ...)` before sending anything. On that error the engine sends the calls one by one instead. + +```ts atomicAdapter.ts +import { + WalletCapabilityError, + toWhiskError, + type EvmAdapter, + type EvmCall, +} from "@usewhisk/core"; + +declare const sequential: EvmAdapter; +declare function walletBatchesAtomically(chainId: number): Promise ; +declare function sendAtomicBatch(calls: EvmCall[]): Promise<`0x${string}`>; + +export const adapter: EvmAdapter = { + ...sequential, + supportsAtomicBatch: walletBatchesAtomically, + async sendCalls(calls, options) { + if (!options?.atomic) return sequential.sendCalls(calls, options); + // A batch has no per-call gas price, and on Arc every call sets one. + if (calls.some((c) => c.maxFeePerGas !== undefined)) { + throw new WalletCapabilityError( + "atomic_unsupported", + "These calls need their own gas price.", + ); + } + let hash: `0x${string}`; + try { + hash = await sendAtomicBatch(calls); + } catch (cause) { + throw toWhiskError(cause, "Failed to submit the batch."); + } + options.onSubmitted?.(hash, calls.length - 1); + return { hashes: [hash] }; + }, +}; +``` + +`sendAtomicBatch` stands for your wallet's EIP-5792 call: submit the batch, wait for it to land, and resolve to a transaction hash from it. A batch that does not land must throw. + +See [EvmAdapter](/reference/core/engine#evmadapter). + +### 4. Custom Stellar adapters need `getTrustline` for classic accounts + +This applies if you built a `StellarAdapter` yourself and use it as the destination wallet of a bridge into Stellar. + +Before a burn into Stellar, the engine reads the recipient's USDC trustline through the destination adapter's new optional `getTrustline(account, asset)`. It refuses a `G` account, or the `G` account behind an `M` address, whose trustline is missing, not authorized or without room for the amount, with `RouteUnavailableError` reason `recipient_account_missing`. + +A custom adapter without `getTrustline` still compiles. Bridges into `C` contract addresses work as before, but a bridge into a `G` or `M` address is refused before the burn with a `ConfigError`. Add the method: + +```ts stellarTrustline.ts +import { Asset, Keypair, rpc, xdr } from "@stellar/stellar-sdk"; +import { toWhiskError, type StellarAdapter } from "@usewhisk/core"; + +declare const base: StellarAdapter; + +const server = new rpc.Server("https://soroban-testnet.stellar.org"); + +export const adapter: StellarAdapter = { + ...base, + async getTrustline(account, asset) { + try { + const key = xdr.LedgerKey.trustline( + new xdr.LedgerKeyTrustLine({ + accountId: Keypair.fromPublicKey(account).xdrAccountId(), + asset: new Asset(asset.code, asset.issuer).toTrustLineXDRObject(), + }), + ); + const { entries } = await server.getLedgerEntries(key); + const entry = entries[0]; + if (!entry) return null; + const line = entry.val.trustLine(); + return { + balance: BigInt(line.balance().toString()), + limit: BigInt(line.limit().toString()), + authorized: + (line.flags() & xdr.TrustLineFlags.authorizedFlag().value) !== 0, + }; + } catch (cause) { + throw toWhiskError(cause, "Failed to read the Stellar USDC trustline."); + } + }, +}; +``` + +Return `null` only when the account has no trustline, and throw on an RPC failure: the engine refuses the send either way, but a thrown error tells the payer the real cause. `balance` and `limit` are in stroops (7 decimals). The adapter from `useStellarAdapter` already implements it. + +See [StellarAdapter](/reference/core/engine#stellaradapter) and [recipients](/concepts/recipients#stellar-trustlines-and-the-forwarder). + +### 5. Stellar and Starknet destinations are checked before the burn + +In 0.2.0 a destination Stellar or Starknet wallet on the wrong network failed only at the mint, after the burn, and a Stellar recipient without a trustline failed the same way. Since 0.2.1, on every route into Stellar or Starknet, `send` checks these before it asks the source wallet for anything, and returns a failure with nothing signed: + +| Check | Failure | +| ------------------------------------------------------------------ | -------------------------------------------------------------- | +| The destination wallet is on the destination's network or chain id | `WrongChainError` | +| A Stellar `G` or `M` recipient has a usable USDC trustline | `RouteUnavailableError`, `reason: "recipient_account_missing"` | +| The destination `StellarAdapter` can read trustlines | `ConfigError` | + +A transfer that used to burn and then wait in the resume list now fails before the burn. Show these failures as something the payer can fix, not as a transfer to resume. + +### 6. Starknet recipients are checked at quote time + +Up to 0.2.1 a Starknet recipient was checked only for its shape, so a pasted Ethereum address got a quote and the USDC was minted to an address nobody controls. Since 0.2.2, a quote into Starknet, for a bridge or a same-chain send: + +- throws `InvalidAddressError` for an address below `2**160` (one that fits in 20 bytes, even zero-padded) or at or past `2**251 - 256`; +- reads the address with `starknet_getClassHashAt`, over the config's `rpcUrls` for the destination and then the registry's defaults, and throws `RouteUnavailableError` with `reason: "recipient_not_deployed"` when no account is deployed there. An RPC failure fails the quote. + +The connected Starknet wallet's own address, passed as `adapter` or `destinationAdapter`, skips the deployed check. For any other undeployed address, ask the payer to confirm it is their own new wallet, then quote again with `allowUndeployedRecipient: true`: + +```ts +import { + RouteUnavailableError, + type Quote, + type QuoteParams, + type WhiskEngine, +} from "@usewhisk/core"; + +declare const engine: WhiskEngine; +declare function payerConfirms(address: string): Promise ; + +export async function quoteIntoStarknet( + params: QuoteParams, +): Promise { + try { + return await engine.quote(params); + } catch (err) { + if ( + err instanceof RouteUnavailableError && + err.reason === "recipient_not_deployed" + ) { + if (!(await payerConfirms(params.recipient.address))) return null; + return engine.quote({ ...params, allowUndeployedRecipient: true }); + } + throw err; + } +} +``` + +`` does this itself, with an "It's my wallet, continue" button. + +`RouteUnavailableReason` gains `"recipient_not_deployed"`. An exhaustive `switch` over it needs the new case: + +```ts +import type { RouteUnavailableReason } from "@usewhisk/react"; + +export function reasonMessage(reason: RouteUnavailableReason): string { + switch (reason) { + case "same_chain": + return "Pick a different destination."; + case "source_adapter_required": + case "destination_adapter_required": + return "Connect the wallet this route needs."; + case "recipient_account_missing": + return "The recipient cannot receive USDC yet."; + case "recipient_not_deployed": + return "No Starknet account is deployed at this address."; + } +} +``` + +`InvalidAddressError` takes an optional third `message` argument, used for the Starknet messages. Code that constructs it with one or two arguments is unaffected. + +See [recipients](/concepts/recipients#starknet-felt-addresses). + +### 7. Max works before a recipient is entered + +`engine.maxSendable` no longer runs the recipient checks, since it only works out fees. Up to 0.2.1 it threw `InvalidAddressError` for a bridge into Solana when the payer's EVM address stood in for the recipient. It now returns the amount for bridges into Solana and Starknet before a recipient is entered. No change is needed. + +## New in 0.3 + +- **`CustomFeeOutcome`** (`@usewhisk/core`), on `SendSuccess.customFee` and `SendFailure.customFee`. +- **`EvmAdapter.supportsAtomicBatch`** and **`SendCallsOptions.atomic`**, both optional. +- **`StellarAdapter.getTrustline`**, optional, and the **`StellarTrustline`** type (`@usewhisk/core`). +- **`QuoteParams.allowUndeployedRecipient`**. +- **`RouteUnavailableReason`** `"recipient_not_deployed"`. +- **`InflightRecord.customFee`**. +- **`getStarknetClassHashAt(chain, address, options?)`** in `@usewhisk/cctp` 0.1.1: the class hash at an address, or `null` when nothing is deployed. See [reading chain state](/reference/cctp/builders#reading-chain-state). + +## Upgrade checklist + + + diff --git a/quickstart.mdx b/quickstart.mdx new file mode 100644 index 0000000..55a208d --- /dev/null +++ b/quickstart.mdx @@ -0,0 +1,187 @@ +--- +title: "Quickstart" +description: "Add a working USDC send and bridge widget to a React app, on testnet first." +--- + +This page takes a React app to a working widget that sends USDC on Base Sepolia and bridges it to Arc Testnet. The finished code is two files: + +```tsx App.tsx +import { WhiskProvider, WhiskSend } from "@usewhisk/react"; +import "@usewhisk/react/styles.css"; +import { config } from "./whisk"; + +export default function App() { + return ( ++ Install `@usewhisk/react@^0.3.0`, and `@usewhisk/core@^0.3.0` if you import + it. Make sure nothing pins `@wagmi/core` below 2.17. + ++ If you set a `feePolicy`, read `result.customFee` in `onSuccess` and + `onFailure` before you fulfil an order. + ++ Leave them as they are, or add `supportsAtomicBatch` and honour `atomic` if + your wallet can land a batch all or nothing. + ++ Add `getTrustline` to any `StellarAdapter` you pass as a destination wallet. + ++ Handle `recipient_not_deployed` on quotes into Starknet, and the + `recipient_account_missing`, `WrongChainError` and `ConfigError` failures + before the burn on bridges into Stellar and Starknet. + ++ Run a testnet transfer with your fee policy on a wallet with and without + atomic batches, and a bridge into each of Stellar and Starknet you offer, + before shipping. + ++ + ); +} +``` + +```ts whisk.ts +import { createWhiskConfig, evm } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + evm({ + chains: ["Base_Sepolia", "Arc_Testnet"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "My Store", + }), + ], + chains: ["Base_Sepolia", "Arc_Testnet"], + defaultSourceChain: "Base_Sepolia", + defaultDestinationChain: "Arc_Testnet", +}); +``` + +## Steps + +console.log("settled", result.finalTxHash)} + onFailure={(result) => + console.error(result.error.code, result.error.message) + } + /> + + + +## Going to mainnet + +Change the chain ids. The network comes from the source chain, so there is no other switch: + +```ts whisk.ts +import { createWhiskConfig, evm } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + evm({ + chains: ["Base", "Arc"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "My Store", + }), + ], + chains: ["Base", "Arc"], + defaultSourceChain: "Base", + defaultDestinationChain: "Arc", +}); +``` + +Before you ship, set your own RPC endpoints. The defaults are public and rate limited. See [RPC endpoints](/rpc). + +## Next.js App Router + +wagmi and the wallet libraries should not run during prerender. Put the provider and widget in a client component and load it with `next/dynamic` and `ssr: false`: + +```tsx app/pay-gate.tsx +"use client"; + +import dynamic from "next/dynamic"; + +const Pay = dynamic(() => import("./pay"), { ssr: false }); + +export function PayGate() { + return+ ```bash + npm install @usewhisk/react @tanstack/react-query viem + ``` + + `react`, `react-dom`, `@tanstack/react-query` and `viem` (`>=2.57.5 <3`) are peer dependencies. wagmi, `@usewhisk/core` and the Solana, Stellar and Starknet wallet libraries come with `@usewhisk/react`. See [installation](/installation) for the full list. + + ++ ```tsx + import "@usewhisk/react/styles.css"; + ``` + + Import it once, anywhere in your app. The widget's components have no styling without it. The widget uses Inter if your page loads it and system fonts otherwise; to load Whisk's fonts too, see [fonts](/theming/fonts). + + ++ `createWhiskConfig` takes the wallet factories for the ecosystems you accept and the chains the widget offers. + + ```ts whisk.ts + import { createWhiskConfig, evm } from "@usewhisk/react"; + + export const config = createWhiskConfig({ + wallets: [ + evm({ + chains: ["Base_Sepolia", "Arc_Testnet"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "My Store", + }), + ], + chains: ["Base_Sepolia", "Arc_Testnet"], + defaultSourceChain: "Base_Sepolia", + defaultDestinationChain: "Arc_Testnet", + }); + ``` + + `evm({ chains })` lists the chains the wallet can switch to. `projectId` is optional: it is your WalletConnect Cloud project ID, and without one the WalletConnect option is left out while browser wallets (such as MetaMask or Rabby) and Coinbase Wallet still work. `appName` is shown in the WalletConnect and Coinbase Wallet pairing dialogs. + + `createWhiskConfig` throws a `ConfigError` if `wallets` or `chains` is empty, or if a default chain is not in `chains`. See [wallets](/wallets) for Solana, Stellar and Starknet. + + ++ Wrap the widget in `WhiskProvider`. The provider mounts wagmi, a react-query client and each wallet ecosystem in your config, and reuses a `WagmiProvider` or `QueryClientProvider` you already have. + + ```tsx App.tsx + import { WhiskProvider, WhiskSend } from "@usewhisk/react"; + import "@usewhisk/react/styles.css"; + import { config } from "./whisk"; + + export default function App() { + return ( + ++ + ); + } + ``` + + `onSuccess` fires when the transfer settles, with the final transaction hash (the mint, on a bridge) and every step. `onFailure` fires when the engine returns a failure, with a typed `error`. See [errors](/concepts/errors). + +console.log("settled", result.finalTxHash)} + onFailure={(result) => console.error(result.error.code, result.error.message)} + /> + + Get test USDC from [Circle's faucet](https://faucet.circle.com) on Base Sepolia, plus a little Base Sepolia ETH for gas. Start the app, connect a wallet, and try both tabs: + + - **Send** moves USDC to an address on the source chain. + - **Bridge** burns USDC on Base Sepolia and mints it on Arc Testnet. Base Sepolia offers Fast Transfer, so Circle attests the burn in seconds instead of waiting the 15 minutes or so for Ethereum finality. Circle's Forwarding Service submits the mint on Arc Testnet, so the payer does not need to switch wallets. + + The review screen shows "You pay" and "Recipient gets" before the wallet asks for a signature. By default the payer covers the bridge fees, so the recipient gets the amount entered. See [quotes and fees](/concepts/quotes-and-fees). + + Arc pays gas in USDC, so a send from Arc Testnet needs only USDC. Arc has no Fast Transfer and does not need it: its blocks are final in under a second, so a Standard burn from Arc is attested about as quickly. + + +; +} +``` + +Here `./pay` is the `App` component above. Render ` ` from any server component. + +## Lock the fields for a checkout + +For an invoice or a fixed-price checkout, pass the values as props. A prop you pass locks its field; a `default*` prop fills it but leaves it editable. + +```tsx Checkout.tsx +import { WhiskProvider, WhiskSend } from "@usewhisk/react"; +import { config } from "./whisk"; + +export function Checkout() { + return ( + + + ); +} +``` + +Amounts are decimal USDC strings, so `"25.00"` is 25 USDC. See [WhiskSend](/widget/whisk-send) for every prop. diff --git a/recipes/donate-button.mdx b/recipes/donate-button.mdx new file mode 100644 index 0000000..1943cac --- /dev/null +++ b/recipes/donate-button.mdx @@ -0,0 +1,166 @@ +--- +title: Donate button +description: A donation page where the recipient and destination chain are fixed and the donor picks a tier or types an amount. +--- + +The `donate-button` example is a Vite and React landing page for a fictional +reforestation charity, OpenForest. Donors pick a tier ($5, $25 or $100) or a +custom amount and pay from an EVM wallet or Phantom on Solana. The treasury +always receives on Optimism Sepolia, with the donor covering the bridge fees. + +```tsx donate-card.tsx +import { useState } from "react"; +import { WhiskSend } from "@usewhisk/react"; + +const TREASURY_ADDRESS = "0xbe03CE9d6001D27BE41fc87e3E3f777d04e70Fe2"; +const TIERS = ["5", "25", "100"]; + +export function DonateCard() { + const [tier, setTier] = useState+ ("25"); + const [paidTx, setPaidTx] = useState (null); + + if (paidTx !== null) + return Thank you. Transaction: {paidTx || "pending"}
; + + return ( ++ {TIERS.map((amount) => ( + + ))} + + ++ ); +} +``` + +This is a trimmed version of `src/components/donate-card.tsx` and +`src/hooks/use-donation.ts`. The full example adds a hero, a donor wall and a +project grid, all static data. + +## How it works + +- **Tier or custom.** A tier passes `amount`, which locks the amount field. + "Custom" passes `undefined`, which hands the field back to the donor. Switching + between them is just changing one prop. +- **Fixed recipient and chain.** `recipient` and `destinationChain` are locked, + so a donor cannot redirect the gift. +- **Any source.** The config lists four EVM testnets and Solana Devnet. A + Solana donor's USDC is burned on Solana and minted to the EVM treasury on + Optimism Sepolia through CCTP. +- **Donor pays the fees.** `feeBearer: "sender"` sizes the burn up so a $25 + tier lands as at least $25. The donor sees the total before signing. +- **Thank-you.** `onSuccess` swaps the widget for a thank-you with the final + tx hash. `finalTxHash` can be undefined when Circle's Forwarder minted and + did not report its hash, so the example falls back to an empty string. + +The provider, from `src/providers.tsx`: + +```tsx providers.tsx +import { useMemo, type ReactNode } from "react"; +import { WhiskProvider, createWhiskConfig, evm, solana } from "@usewhisk/react"; + +export function Providers({ children }: { children: ReactNode }) { + const config = useMemo( + () => + createWhiskConfig({ + feeBearer: "sender", + wallets: [ + evm({ + chains: [ + "Arc_Testnet", + "Base_Sepolia", + "Ethereum_Sepolia", + "Optimism_Sepolia", + ], + projectId: import.meta.env.VITE_WALLETCONNECT_PROJECT_ID, + appName: "OpenForest", + }), + solana({ network: "devnet" }), + ], + chains: [ + "Arc_Testnet", + "Base_Sepolia", + "Ethereum_Sepolia", + "Optimism_Sepolia", + "Solana_Devnet", + ], + defaultSourceChain: "Arc_Testnet", + defaultDestinationChain: "Optimism_Sepolia", + appLabel: "whisk-example-donate", + }), + [], + ); + + return ( +setPaidTx(finalTxHash ?? "")} + /> + + {children} + + ); +} +``` + +The treasury receives on Optimism rather than Ethereum because the Forwarder's +mint fee there is cents, where an Ethereum mint costs dollars. + +## Run it locally + +From a clone of [usewhisk/whisk](https://github.com/usewhisk/whisk), with Node +20 or later and pnpm: + +```bash +pnpm install +pnpm build +cp examples/donate-button/.env.example examples/donate-button/.env.local +pnpm --filter @usewhisk/example-donate-button dev +``` + +Open http://localhost:3011. `pnpm build` builds the packages the example +imports from the workspace. + +| Variable | Required | Effect | +| ------------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `VITE_WALLETCONNECT_PROJECT_ID` | No | Adds the WalletConnect connector. Without it, injected wallets and Coinbase Wallet still work. | + +You need testnet USDC on one of the listed chains (Circle's faucet) and a +little native gas, except on Arc Testnet, where gas is paid in USDC. + +To use it in your own Vite app, install `@usewhisk/react`, import +`@usewhisk/react/styles.css` before your own CSS (see `src/main.tsx`), and copy +the `resolve.alias`, `define` and `optimizeDeps` blocks from `vite.config.ts`. +They point `buffer` at the browser polyfill (the Solana and Stellar SDKs need +it) and stub two wagmi dependencies that have no browser build. + +## For production + +- **Switch to mainnet chains.** Replace each `_Sepolia` and `_Devnet` id with + its mainnet id (`Arc`, `Base`, `Ethereum`, `Optimism`, `Solana`), use + `solana({ network: "mainnet-beta" })`, and lock `destinationChain` to a + mainnet chain. A mainnet donor quoted against a testnet destination gets + `NetworkMismatchError`. +- **Use your treasury address**, and make sure it can receive on the + destination chain. +- **Show only the Bridge tab** with `tabs={["bridge"]}`. With both tabs, the + Send tab pays the treasury on the donor's own source chain, not on Optimism. +- **Record donations on your server.** The donor wall and totals are + hard-coded. If you publish donors or issue tax receipts, post the tx hashes + to your server and verify them on chain first, as in + [checkout](/flows/checkout#verify-on-your-server). +- **Link the receipt** with `explorerTxUrl` or a + [receipt page](/flows/receipts) rather than a fixed explorer host. +- **Set your own RPC URLs** with `rpcUrls` on the config and on `evm()`; the + public defaults are rate-limited. + ++ The example's README says the treasury is pinned to Arc Testnet and the dev + server runs on port 5173. The code pins Optimism Sepolia and the `dev` script + uses port 3011. + diff --git a/recipes/ecommerce-checkout.mdx b/recipes/ecommerce-checkout.mdx new file mode 100644 index 0000000..7453d25 --- /dev/null +++ b/recipes/ecommerce-checkout.mdx @@ -0,0 +1,140 @@ +--- +title: E-commerce checkout +description: A storefront whose payment step is a WhiskSend locked to the cart total, the merchant address and one chain. +--- + +The `ecommerce-checkout` example is a Next.js 15 storefront for a fictional +brand, Atelier Hibiscus: a product grid, a cart, a checkout page and an order +confirmation. At the payment step every value the payer could change is +locked: + +```tsx payment-aside.tsx +"use client"; + +import { WhiskSend } from "@usewhisk/react"; + +const MERCHANT_ADDRESS = "0x5B8ecaB7096F8aBED873D246629ef9f05f467605"; + +export function PaymentAside({ + totalStr, + onPaid, +}: { + totalStr: string; + onPaid: (txHash?: string) => void; +}) { + return ( +onPaid(finalTxHash)} + /> + ); +} +``` + +`totalStr` is the cart total formatted to two decimals, such as `"184.00"`. +This is `src/components/checkout/payment-aside.tsx` without its layout. + +## How it works + +- **Locked payment.** `amount`, `recipient`, `sourceChain` and + `destinationChain` are all controlled, so the payer can neither edit the + price nor pick a chain. Source and destination are the same, so this is a + same-chain USDC transfer on Base Sepolia: no CCTP, no bridge fees, and the + merchant receives exactly the total. +- **Confirmation.** `onSuccess` hands `finalTxHash` (the transfer's hash) to + `src/app/checkout.tsx`, which copies the cart into a paid order and shows the + confirmation. +- **Client only.** `src/app/client-gate.tsx` loads the provider and the checkout + with `next/dynamic` and `ssr: false`, because the wallet libraries need + `window`. +- **Themed.** `src/app/globals.css` sets the `--whisk-*` variables on + `[data-whisk]` to the store's palette. See [theming](/theming/tokens). + +The provider, from `src/app/providers.tsx`: + +```tsx providers.tsx +"use client"; + +import { useMemo, type ReactNode } from "react"; +import { WhiskProvider, createWhiskConfig, evm } from "@usewhisk/react"; + +export function Providers({ children }: { children: ReactNode }) { + const config = useMemo( + () => + createWhiskConfig({ + feeBearer: "sender", + wallets: [ + evm({ + chains: ["Arc_Testnet", "Base_Sepolia"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "Atelier Hibiscus", + }), + ], + chains: ["Arc_Testnet", "Base_Sepolia"], + defaultSourceChain: "Arc_Testnet", + defaultDestinationChain: "Arc_Testnet", + appLabel: "whisk-example-ecommerce", + }), + [], + ); + + return ( + + {children} + + ); +} +``` + +`feeBearer: "sender"` only matters for a bridge. The widget's locked chains +override the config defaults. + +## Run it locally + +From a clone of [usewhisk/whisk](https://github.com/usewhisk/whisk), with Node +20 or later and pnpm: + +```bash +pnpm install +pnpm build +cp examples/ecommerce-checkout/.env.example examples/ecommerce-checkout/.env.local +pnpm --filter @usewhisk/example-ecommerce-checkout dev +``` + +Open http://localhost:3010, add something to the cart and check out. You need +testnet USDC and a little ETH for gas on Base Sepolia. + +| Variable | Required | Effect | +| -------------------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID` | No | Adds the WalletConnect connector. Without it, injected wallets and Coinbase Wallet still work. | + +To move it into your own Next.js app, install `@usewhisk/react`, import +`@usewhisk/react/styles.css` in the root layout before your own CSS, and copy +the `webpack` block from `next.config.ts`, which stubs two wagmi dependencies +that have no browser build. + +## For production + +The example is a front end only. Before it takes real money: + +- **Create the order on your server first.** The example makes an order id + after payment, in the browser (`makeOrderId`), so nothing ties the payment to + an order. Create the order, with its price and merchant address, before + showing the widget. +- **Verify on your server before fulfilling.** Post `finalTxHash` with the + order id and check the USDC transfer on chain, as in + [checkout](/flows/checkout#verify-on-your-server). Whisk 0.3 does not notify + your server. The example's README mentions a webhook; there is none. +- **Switch to a mainnet chain.** Replace `Base_Sepolia` with `Base` (or your + settlement chain) in both the config and the widget. +- **Accept other chains if you want them.** To let payers pay from any chain + and settle on yours, drop `sourceChain`, keep `destinationChain`, and pass + `tabs={["bridge"]}`. The payer then pays the bridge fees on top. +- **Fix the explorer link.** `src/lib/order.ts` links every hash to Arc + Testnet's explorer, though the payment is on Base Sepolia. Use + `explorerTxUrl(chain, hash)`. +- **Remove the "Built on Circle App Kit" footer**, which is left over from + Whisk 0.1. diff --git a/recipes/invoice-link.mdx b/recipes/invoice-link.mdx new file mode 100644 index 0000000..44f7257 --- /dev/null +++ b/recipes/invoice-link.mdx @@ -0,0 +1,168 @@ +--- +title: Invoice link +description: A shareable payment link that carries the recipient, amount and chain in its query string and opens a locked WhiskSend. +--- + +The `invoice-link` example is a Next.js 15 app with two views. `/create` lets a +freelancer compose a link; `/` reads it back and renders an invoice with a +`` locked to its values. The link is the whole integration: + +```text +/?to=0x5B8ecaB7096F8aBED873D246629ef9f05f467605&amount=1200.00&chain=Base_Sepolia&memo=Brand+refresh +``` + +Reading it, with the example's `useSearchParams` call replaced by a plain +`URLSearchParams` argument: + +```ts parse-invoice.ts +import { getChain, isChainId, type Chain } from "@usewhisk/react"; + +export type InvoiceQuery = + | { + valid: true; + to: string; + amount: string; + chain: Chain; + chainLabel: string; + memo: string; + } + | { + valid: false; + reason: "missing-to" | "missing-amount" | "unknown-chain" | "missing"; + }; + +export function parseInvoice(params: URLSearchParams): InvoiceQuery { + const to = params.get("to")?.trim() ?? ""; + const amount = params.get("amount")?.trim() ?? ""; + const chain = params.get("chain")?.trim() ?? ""; + const memo = params.get("memo")?.trim() ?? ""; + + if (!to && !amount && !chain) return { valid: false, reason: "missing" }; + if (!to) return { valid: false, reason: "missing-to" }; + if (!amount) return { valid: false, reason: "missing-amount" }; + if (!isChainId(chain)) return { valid: false, reason: "unknown-chain" }; + + return { + valid: true, + to, + amount, + chain, + chainLabel: getChain(chain).label, + memo, + }; +} +``` + +And paying it, from `src/components/pay-aside.tsx`: + +```tsx pay-panel.tsx +"use client"; + +import { WhiskSend } from "@usewhisk/react"; +import type { InvoiceQuery } from "./parse-invoice"; + +type ValidInvoice = Extract ; + +export function PayPanel({ + invoice, + onPaid, +}: { + invoice: ValidInvoice; + onPaid: (txHash?: string) => void; +}) { + return ( + onPaid(finalTxHash)} + /> + ); +} +``` + +## How it works + +- **The link is untrusted input.** `isChainId` only passes a chain id Whisk + knows, so a tampered `chain` falls through to the empty state instead of + reaching the widget. A bad `to` fails in the widget's recipient check. +- **Same-chain payment.** Source and destination are both the invoice's chain, + so the payer sends USDC on that chain directly. There are no bridge fees and + the freelancer receives exactly `amount`. The payer needs USDC on that chain. +- **Paid stamp.** `onSuccess` stores the hash and the invoice card shows a + "Paid" stamp. +- **Composer.** `/create` (`src/hooks/use-invoice-link.ts`) checks the address + is a 20-byte hex address and the amount is positive, then builds the path: + +```ts build-link.ts +import type { Chain } from "@usewhisk/react"; + +export function invoicePath(draft: { + to: string; + amount: string; + chain: Chain; + memo: string; +}): string { + const search = new URLSearchParams(); + search.set("to", draft.to.trim()); + search.set("amount", draft.amount.trim()); + search.set("chain", draft.chain); + if (draft.memo.trim()) search.set("memo", draft.memo.trim()); + return `/?${search.toString()}`; +} +``` + +The provider config (`src/app/providers.tsx`) lists Arc Testnet, Base Sepolia, +Ethereum Sepolia, Arbitrum Sepolia and Optimism Sepolia, so an invoice can name +any of them. + +## Run it locally + +From a clone of [usewhisk/whisk](https://github.com/usewhisk/whisk), with Node +20 or later and pnpm: + +```bash +pnpm install +pnpm build +cp examples/invoice-link/.env.example examples/invoice-link/.env.local +pnpm --filter @usewhisk/example-invoice-link dev +``` + +Open http://localhost:3014 and pick one of the demo invoices, or compose one at +http://localhost:3014/create. + +| Variable | Required | Effect | +| -------------------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID` | No | Adds the WalletConnect connector. Without it, injected wallets and Coinbase Wallet still work. | + +## For production + + + Anyone holding the link can edit it. Change `amount=1200.00` to `amount=1.00` + and the widget locks to $1. A query-string invoice says what to pay, never + what was owed. + + +- **Keep invoices on your server.** Put only an invoice id in the link and load + the recipient, amount and chain from your database, or sign the parameters + with an HMAC and check the signature before rendering. +- **Verify payment on your server.** Mark an invoice paid only after checking + the transfer on chain against the stored amount and recipient, as in + [checkout](/flows/checkout#verify-on-your-server). The "Paid" stamp is only + the payer's browser. +- **Validate the amount.** The customer view passes `amount` straight to the + widget. Run it through `parseUsdcAmount`, which throws on anything that is + not a positive decimal USDC string, and reject links with more than 6 + decimals, which it would silently truncate. +- **Allow other source chains if you want them.** Drop `sourceChain`, keep + `destinationChain`, and pass `tabs={["bridge"]}`, so the payer can pay from + any chain on the same network and covers the bridge fees. +- **Fix the explorer link.** `src/lib/order.ts` always links to Arc Testnet's + explorer. Use `explorerTxUrl(invoice.chain, hash)`. +- **Drop the email promise.** The confirmation says "A receipt is on its way to + your email"; nothing sends one. +- **Use mainnet chain ids** (`Arc`, `Base`, `Ethereum`, `Arbitrum`, + `Optimism`) in the config and in the links you generate. + +The example's README gives port 3030; the `dev` script uses 3014. diff --git a/recipes/payroll-batch.mdx b/recipes/payroll-batch.mdx new file mode 100644 index 0000000..df07e4b --- /dev/null +++ b/recipes/payroll-batch.mdx @@ -0,0 +1,182 @@ +--- +title: Payroll batch +description: An admin tool that walks a list of payees and pays each one through the same WhiskSend, one signature per payee. +--- + +The `payroll-batch` example is a Vite and React tool for a fictional studio. An +operator reviews six payees, excludes any, then dispatches the run: the widget +loads the next payee's amount and chain, the operator signs, and `onSuccess` +moves on. The last step shows a run summary. + +The core is a hook that walks the list and records what happened to each +payee. This version tracks paid and skipped payees separately: + +```ts use-batch.ts +import { useCallback, useMemo, useState } from "react"; +import { formatUsdcAmount, parseUsdcAmount, type Chain } from "@usewhisk/react"; + +export type Payee = { + id: string; + name: string; + address: string; + amount: string; + chain: Chain; +}; + +export type Outcome = + { status: "paid"; txHash?: string } | { status: "skipped" }; + +export function useBatch(payees: Payee[]) { + const [index, setIndex] = useState(0); + const [outcomes, setOutcomes] = useState>({}); + const current = payees[index]; + + const record = useCallback( + (outcome: Outcome) => { + if (!current) return; + setOutcomes((prev) => ({ ...prev, [current.id]: outcome })); + setIndex((i) => i + 1); + }, + [current], + ); + + const markPaid = useCallback( + (txHash?: string) => record({ status: "paid", ...(txHash && { txHash }) }), + [record], + ); + const skip = useCallback(() => record({ status: "skipped" }), [record]); + + const totals = useMemo(() => { + let paid = 0n; + let skipped = 0n; + for (const payee of payees) { + const outcome = outcomes[payee.id]; + if (outcome?.status === "paid") paid += parseUsdcAmount(payee.amount); + if (outcome?.status === "skipped") + skipped += parseUsdcAmount(payee.amount); + } + return { paid: formatUsdcAmount(paid), skipped: formatUsdcAmount(skipped) }; + }, [payees, outcomes]); + + return { + current, + done: index >= payees.length, + outcomes, + totals, + markPaid, + skip, + }; +} +``` + + + The example as shipped calls the same `advance` function for **Skip** and for + a settled payment, so a skipped payee is counted, summed and listed as paid in + the run summary + ([usewhisk/whisk#159](https://github.com/usewhisk/whisk/issues/159)). The + example will be fixed. Until then, use the pattern above: one outcome per + payee, totals in `bigint` subunits, and the tx hash kept with each payment. + + +The widget for the payee in front of the operator: + +```tsx active-payee.tsx +import { WhiskSend } from "@usewhisk/react"; +import type { Payee } from "./use-batch"; + +const SOURCE_CHAIN = "Arc_Testnet"; + +export function ActivePayee({ + payee, + onPaid, + onSkip, +}: { + payee: Payee; + onPaid: (txHash?: string) => void; + onSkip: () => void; +}) { + return ( +++ ); +} +``` + +Wire them together with `const batch = useBatch(payees)` and render +`onPaid(finalTxHash)} + /> + + ` +while `batch.current` is set. + +## How it works + +- **One signature per payee.** Each payment is its own quote and wallet prompt + (two when a bridge needs a USDC approval first). The treasury wallet signs + every one. +- **Bridged from Arc.** Payments start on Arc Testnet, where gas is paid in + USDC, and bridge to each payee's chain. A payee on Arc gets a same-chain + transfer. The `tabs` line above picks the right tab; the example leaves both + tabs visible. +- **Treasury pays the fees.** The config sets `feeBearer: "sender"`, so each + bridge burns a little more than the salary and the payee receives at least + the full amount. +- **A fresh widget per payee.** `key={payee.id}` remounts ` `, so no + quote, result or error carries over from the previous payee. + +The provider (`src/providers.tsx`) lists Arbitrum Sepolia, Arc Testnet, Base +Sepolia and Optimism Sepolia, with `evm()` only. + +## Run it locally + +From a clone of [usewhisk/whisk](https://github.com/usewhisk/whisk), with Node +20 or later and pnpm: + +```bash +pnpm install +pnpm build +cp examples/payroll-batch/.env.example examples/payroll-batch/.env.local +pnpm --filter @usewhisk/example-payroll-batch dev +``` + +Open http://localhost:3013. The `dev` script sets the port; the README's 5174 +is out of date. + +| Variable | Required | Effect | +| ------------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `VITE_WALLETCONNECT_PROJECT_ID` | No | Adds the WalletConnect connector. Without it, injected wallets and Coinbase Wallet still work. | + + + The example's payee addresses are shortened display strings, so every payment + in the demo goes to one placeholder address (`STUDIO_TREASURY`). Its amounts + are large (thousands of USDC); exclude payees or edit `src/data/payees.ts` to + fit your testnet balance. + + +## For production + +- **Pay real addresses.** Pass each payee's full address as `recipient`, as in + the snippet above, not the placeholder. +- **Keep amounts as strings and sum in `bigint`.** The example stores salaries + as JavaScript numbers. Use decimal strings and `parseUsdcAmount` so totals + never go through float math. +- **Record every outcome.** Save each payee's status and tx hash as it happens, + on your server, so a reload or a closed tab does not lose the run. Skipped + payees stay unpaid in your records. +- **Handle failures.** Add an `onFailure` that stops the run. If the burn step + succeeded, the USDC is in flight; finish it from the + [``](/widget/resume-list) before paying anyone twice. See + [recovery](/concepts/recovery). +- **Consider a server.** For a long list, signing in a browser one payee at a + time is slow. The core engine runs the same sends from a server wallet; see + [server usage](/headless/server) and the `node-headless` example's + `payroll.ts`. +- **Use mainnet chain ids** (`Arc`, `Base`, `Optimism`, `Arbitrum`) for the + treasury's source chain and every payee's chain. diff --git a/recipes/themed-saas.mdx b/recipes/themed-saas.mdx new file mode 100644 index 0000000..2673d0c --- /dev/null +++ b/recipes/themed-saas.mdx @@ -0,0 +1,200 @@ +--- +title: Themed SaaS dashboard +sidebarTitle: Themed SaaS +description: A dark treasury dashboard that restyles WhiskSend with CSS variables so it matches the host product. +--- + +The `themed-saas` example is a Next.js 15 dashboard for a fictional company, +Steelpath Cloud, with a sidebar, KPI tiles, a vendor table and an activity log. +Clicking a vendor loads a ` ` with that vendor's amount. The point of +the example is the look: the widget takes the dashboard's dark navy and teal +palette through Whisk's `--whisk-*` CSS variables. + +```css globals.css +[data-whisk] { + --whisk-bg: #0c1827; + --whisk-card: #15263a; + --whisk-card-fg: #e8eef7; + --whisk-fg: #e8eef7; + --whisk-fg-muted: #6b7a8d; + --whisk-border: rgba(255, 255, 255, 0.16); + --whisk-input: rgba(255, 255, 255, 0.16); + --whisk-border-w: 1px; + --whisk-primary: #5dd9c5; + --whisk-primary-fg: #050810; + --whisk-ring: #5dd9c5; + --whisk-success: #4ade80; + --whisk-warning: #f5a142; + --whisk-destructive: #f87171; + --whisk-destructive-fg: #050810; + --whisk-radius: 10px; + --whisk-radius-sm: 6px; + --whisk-radius-md: 10px; + --whisk-radius-lg: 14px; +} +``` + +The example writes these as `var(--color-*)` references to its Tailwind v4 +`@theme` tokens; the values above are what they resolve to. It also maps +`--whisk-font`, `--whisk-font-display` and `--whisk-font-mono` to its own +fonts. + +## How it works + +- **The variables sit on `[data-whisk]`.** ` ` puts that + attribute on the element that wraps its children, and the portal its dialogs + render into sits inside it, so one rule reaches both. +- **Load order decides ties.** `src/app/layout.tsx` imports + `@usewhisk/react/styles.css` first and `./globals.css` second. Both target + `[data-whisk]` with the same specificity, so the later file wins. +- **Dark preset underneath.** The provider passes `theme="dark"`, so anything + the CSS does not override (and the `data-whisk-theme` attribute) comes from + the dark preset. +- **One widget, many vendors.** `src/hooks/use-payout.ts` holds which vendor is + selected and switches to a confirmed state with the tx hash from `onSuccess`. + +The provider and the payout widget, trimmed: + + + +```tsx providers.tsx +"use client"; + +import { useMemo, type ReactNode } from "react"; +import { WhiskProvider, createWhiskConfig, evm } from "@usewhisk/react"; + +export function Providers({ children }: { children: ReactNode }) { + const config = useMemo( + () => + createWhiskConfig({ + feeBearer: "sender", + wallets: [ + evm({ + chains: ["Arc_Testnet", "Base_Sepolia"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "Steelpath Cloud", + }), + ], + chains: ["Arc_Testnet", "Base_Sepolia"], + defaultSourceChain: "Arc_Testnet", + defaultDestinationChain: "Arc_Testnet", + appLabel: "whisk-example-themed-saas", + }), + [], + ); + + return ( + + +## The same theme without CSS + +The token overrides can also go on the provider, which writes the same +variables as an inline style on the `[data-whisk]` element: + +```tsx providers.tsx +import type { ReactNode } from "react"; +import { WhiskProvider, type WhiskClientConfig } from "@usewhisk/react"; + +declare const config: WhiskClientConfig; + +export function Providers({ children }: { children: ReactNode }) { + return ( ++ {children} + + ); +} +``` + +```tsx quick-send.tsx +"use client"; + +import { WhiskSend } from "@usewhisk/react"; + +export type Vendor = { id: string; name: string; amount: string }; + +const TREASURY = "0x5B8ecaB7096F8aBED873D246629ef9f05f467605"; + +export function QuickSend({ + vendor, + onPaid, +}: { + vendor: Vendor; + onPaid: (txHash?: string) => void; +}) { + return ( +++ ); +} +``` + +onPaid(finalTxHash)} + /> + + {children} + + ); +} +``` + +Inline styles beat any stylesheet rule on `[data-whisk]`, so pick one +approach. CSS is the better fit when the colours already live in your design +tokens, as they do here. See [theming](/theming/overview) and the +[token list](/theming/tokens). + +## Run it locally + +From a clone of [usewhisk/whisk](https://github.com/usewhisk/whisk), with Node +20 or later and pnpm: + +```bash +pnpm install +pnpm build +cp examples/themed-saas/.env.example examples/themed-saas/.env.local +pnpm --filter @usewhisk/example-themed-saas dev +``` + +Open http://localhost:3012 and click a row in "Scheduled vendors". The `dev` +script sets the port; the README's 3020 is out of date. + +| Variable | Required | Effect | +| -------------------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID` | No | Adds the WalletConnect connector. Without it, injected wallets and Coinbase Wallet still work. | + +## For production + +- **Pay the vendor, not the placeholder.** The example sends every payout to + one `TREASURY` address and ignores each vendor's handle and chain. Pass the + vendor's address (or an ENS name; the default resolver tries addresses, then + ENS) as `recipient`, and lock `destinationChain` to the vendor's chain with + `tabs={["bridge"]}`, or `sourceChain` and `destinationChain` to the same + chain with `tabs={["send"]}`. +- **Fix the explorer link.** The confirmed state links to Arc Testnet's + explorer whatever chain paid. Use `explorerTxUrl(chain, hash)`. +- **Record payouts on your server** with the tx hash, and verify them on chain + before marking an invoice settled, as in + [checkout](/flows/checkout#verify-on-your-server). The KPI tiles and + settlement feed are static data. +- **Use mainnet chain ids** (`Arc`, `Base`) in the config. +- **Check contrast.** If you change the palette, keep `--whisk-primary-fg` + readable on `--whisk-primary`, and `--whisk-fg-muted` readable on + `--whisk-card`. diff --git a/reference/cctp/builders.mdx b/reference/cctp/builders.mdx new file mode 100644 index 0000000..54eb07b --- /dev/null +++ b/reference/cctp/builders.mdx @@ -0,0 +1,760 @@ +--- +title: Burn and mint builders +sidebarTitle: Builders +description: Build CCTP V2 burn and mint calls for EVM, Solana, Stellar and Starknet, plus the hook data, address encoding and chain reads around them. +--- + +Builders turn a transfer into the exact calls a wallet signs. They validate the input, encode it, and return plain data; nothing is sent. + +```ts +import { + BaseSepolia, + ArcTestnet, + getBurnFees, + pickFeeTier, + buildBurnIntent, +} from "@usewhisk/cctp"; + +const tiers = await getBurnFees( + "testnet", + BaseSepolia.cctpDomain, + ArcTestnet.cctpDomain, +); + +const intent = buildBurnIntent({ + source: BaseSepolia, + destination: ArcTestnet, + amount: 10_000_000n, + mintRecipient: "0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e", + fee: { tier: pickFeeTier(tiers, "standard"), forwarderLevel: "med" }, +}); + +console.log(intent.calls.length, intent.maxFee, intent.withForwarder); +``` + +| Source | Burn builder | Destination | Mint builder | +| -------- | --------------------------------------------------------- | ----------- | ---------------------------- | +| EVM | `buildBurnIntent`, `buildBurnWithFeesIntent` | EVM | `buildMintIntent` | +| Solana | `buildSolanaBurnIntent` | Solana | `buildSolanaReceiveIntent` | +| Stellar | `buildStellarApproveInvocation`, `buildStellarBurnIntent` | Stellar | `buildStellarMintIntent` | +| Starknet | `buildStarknetApproveCall`, `buildStarknetBurnIntent` | Starknet | `buildStarknetReceiveIntent` | + +Any source can burn to any destination. The burn only needs the destination's domain and the recipient as 32 bytes. + ++ The burn moves the payer's USDC out of their wallet for good. Fetch the fees, + check the route and validate the recipient before you ask anyone to sign it. + If the mint never happens, the attested message is the only way to get the + money out, so keep the burn transaction hash. + + +## EVM burns + +### `buildBurnIntent` + +`buildBurnIntent(input: BuildBurnIntentInput): BurnIntent` + +Builds an optional `approve` on the source USDC, then `depositForBurnWithHook` (forwarder on, or custom hook data) or `depositForBurn` (forwarder off) on `TokenMessengerV2`. The source must be an EVM chain. The finality threshold comes from the fee tier: 1000 for Fast, 2000 for Standard. + ++ The EVM chain the USDC is burned on. A non-EVM source throws + `UnsupportedError("unsupported_ecosystem")`. + ++ Any chain in the registry with a different domain. The same domain throws + `InvalidInputError("no_route")`. + ++ USDC subunits, 6 decimals. Above zero and at most 10,000,000 USDC + (`10_000_000_000_000n`); CCTP refuses larger burns, and this throws + `ProtocolError("amount_too_large")`. + ++ The recipient in the destination's format, validated against it: - EVM: a + 20-byte `0x` address. - Solana: the recipient's USDC associated token account, + base58. CCTP mints to a token account, not to a wallet, so derive the ATA from + the wallet and the destination's `usdc` mint. - Stellar: the `CctpForwarder` + contract as 32-byte hex. See [burns to Stellar](#burns-to-stellar). - + Starknet: the account felt, zero-padded to 32-byte hex with + `feltToBytes32Hex`. + ++ ++ ++ A row from `getBurnFees`, picked with `pickFeeTier`. A Fast tier on a + chain without `fastSource` throws `ProtocolError("no_route")`. + ++ Which Iris forwarder fee to cover. Defaults to `"med"`. + ++ Whole basis points added to the forwarder fee. Defaults to `0`. + ++ Burn with exactly this cap instead of the one computed from the tier. Pass + the `maxFee` the payer confirmed. Must be below `amount`. + ++ Defaults to `true`: the burn carries `CCTP_FORWARD_HOOK_DATA` and Circle's + relayer submits the mint, paid out of the transfer. Set `false` when the + destination's `capabilities.forwardingDestination` is false; the builder does + not check this for you. With `false` the forwarder fee is left out of `maxFee` + and someone has to mint on the destination. + ++ Hook data to send instead of the forwarder's. Setting it always selects + `depositForBurnWithHook`, even with `withForwarder: false`. Used for Stellar. + ++ 32 bytes. Who may call `receiveMessage` on the destination. Defaults to + `ANY_DESTINATION_CALLER` (all zeros). + ++ Allowance to approve. Defaults to `amount`; set it higher to skip the approve + on later burns. Lower than `amount` throws. + ++ Leave out the approve call when the wallet already has enough allowance on + `TokenMessengerV2`. Defaults to `false`. + + +Returns a `BurnIntent`: + ++ Execute in order. Each is `{ to, data, value }` with `value` always `0n`. + Wallets that support EIP-5792 can batch them. + ++ The burned amount, 6-decimal subunits. + ++ The fee cap packed into the burn. Circle takes at most this much from + `amount`; the recipient gets at least `amount - maxFee`. + ++ The computed protocol fee, for a fee breakdown. + ++ The computed forwarder fee, `0n` with the forwarder off. + ++ The recipient as it appears in the CCTP message. + ++ Whether the forwarder hook was set. + ++ `FINALITY_FAST` or `FINALITY_STANDARD`, from the tier. + ++ The chains you passed. + + +If `maxFee` ends up negative or not below `amount`, the builder throws `InvalidInputError("invalid_amount")` because `TokenMessengerV2` would revert. + +### Burns to Stellar + +Stellar mints go through Circle's `CctpForwarder` contract, which mints to itself and passes the USDC to the recipient named in the hook data. Stellar is not on Circle's Forwarding Service, so there is no forwarder fee and the burn uses custom hook data instead: + +```ts +import { + BaseSepolia, + StellarTestnet, + getBurnFees, + pickFeeTier, + buildBurnIntent, + buildStellarForwarderHookData, + contractStrkeyToBytes32Hex, +} from "@usewhisk/cctp"; + +const tiers = await getBurnFees( + "testnet", + BaseSepolia.cctpDomain, + StellarTestnet.cctpDomain, + { includeForwarderFee: false }, +); +const forwarder = contractStrkeyToBytes32Hex(StellarTestnet.cctpForwarder); + +const intent = buildBurnIntent({ + source: BaseSepolia, + destination: StellarTestnet, + amount: 5_000_000n, + mintRecipient: forwarder, + destinationCaller: forwarder, + withForwarder: false, + customHookData: buildStellarForwarderHookData( + "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H", + ), + fee: { tier: pickFeeTier(tiers, "standard") }, +}); +``` + ++ `mintRecipient` and `destinationCaller` must both be the forwarder. If + `mintRecipient` is the user's account, even decoded to 32 bytes, the USDC + never reaches the forwarder and is stuck for good. + + +`buildStellarForwarderHookData(recipient, integratorPayload?)` takes the final recipient as a G, M or C strkey and returns the hook data as hex: 24 zero bytes, a big-endian `u32` version (`0`), a big-endian `u32` length, the strkey as UTF-8, then the optional payload bytes. An invalid strkey throws `InvalidInputError("invalid_address")`. + +The recipient receives 7-decimal USDC on Stellar: the 6-decimal burn amount times 10. + +### `buildBurnWithFeesIntent` + +`buildBurnWithFeesIntent(input: BuildBurnWithFeesIntentInput): BurnWithFeesIntent` + +For chains with `capabilities.upfrontFeeSource`, Circle sells a signed quote for the Fast and forwarding fees, paid in USDC on top of the amount rather than out of it. The recipient then gets the full `amount`. + +```ts +import { + Base, + Arbitrum, + getSignedBurnQuote, + buildBurnWithFeesIntent, +} from "@usewhisk/cctp"; + +const payer = "0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e"; +const amount = 100_000_000n; + +const quote = await getSignedBurnQuote( + "mainnet", + Base.cctpDomain, + Arbitrum.cctpDomain, + { amount, feeToken: Base.usdc, requests: ["PRE_FINALITY", "FORWARD"] }, +); + +const intent = buildBurnWithFeesIntent({ + source: Base, + destination: Arbitrum, + amount, + fee: quote.feeTotalAmount, + mintRecipient: payer, + signedQuote: quote.signedQuote, + refundAddress: payer, +}); +``` + ++ An EVM chain with `tokenMessengerWithFees`. Others throw + `UnsupportedError("unsupported_chain")`. + ++ Any other domain except Stellar, whose custom hook data Circle cannot bind to + an upfront fee. + ++ Exactly the amount the quote was requested for, in 6-decimal subunits. + ++ The quote's `feeTotalAmount`. The contract collects it on top of `amount`. + ++ Same rules as `buildBurnIntent`. + ++ From `getSignedBurnQuote`, submitted as is. + ++ An EVM address. Circle reserves it for refunds it does not make today. + ++ Defaults to `amount + fee`. Lower throws. + + +Returns `{ calls, amount, fee, mintRecipientBytes32 }`: an approve on USDC for `TokenMessengerWithFees`, then `depositForBurnWithFees`. The contract adds Circle's forwarding hook itself when the quote includes a `FORWARD` fee. The payer needs `amount + fee` USDC. Quotes expire; see [`getSignedBurnQuote`](/reference/cctp/iris#signed-upfront-fee-quotes). + +## EVM mints + +### `buildMintIntent` + +`buildMintIntent(input: BuildMintIntentInput): MintIntent` + +`receiveMessage(message, attestation)` on the destination's `MessageTransmitterV2`. Use it when the forwarder reports `FAILED`, or when you burned with `withForwarder: false`. + +```ts +import { + ArbitrumSepolia, + buildMintIntent, + type IrisMessage, +} from "@usewhisk/cctp"; + +const { call } = buildMintIntent({ + destination: ArbitrumSepolia, + message: msg.message, + attestation: msg.attestation, +}); +console.log(call.to, call.data, call.value); +``` + +| Param | Type | | +| ------------- | ------------------- | -------------------------------------------------------------------------------- | +| `destination` | `CctpChain` | Must be EVM. Other ecosystems throw `UnsupportedError` naming the right builder. | +| `message` | `` `0x${string}` `` | `IrisMessage.message`. | +| `attestation` | `` `0x${string}` `` | `IrisMessage.attestation`. | + +Returns `{ destination, call }`, where `call` is an `EvmCall` with `value: 0n`. Anyone can submit it unless the burn set a `destinationCaller`; whoever submits it pays the destination gas. A message mints once: check [`isNonceUsed`](#reading-chain-state) before you ask someone to pay for a second try. + +## Solana + +### `buildSolanaBurnIntent` + +`buildSolanaBurnIntent(input: BuildSolanaBurnIntentInput): SolanaBurnIntent` + +Builds `deposit_for_burn`, or `deposit_for_burn_with_hook` when `hookData` is set, on the `TokenMessengerMinterV2` program, with all 18 accounts derived. + +```ts +import { Keypair, PublicKey, Transaction } from "@solana/web3.js"; +import { getAssociatedTokenAddressSync } from "@solana/spl-token"; +import { + SolanaDevnet, + BaseSepolia, + FINALITY_STANDARD, + buildSolanaBurnIntent, + burnIntentToTransactionInstruction, + toBytes32, + CCTP_FORWARD_HOOK_DATA, +} from "@usewhisk/cctp"; + +const eventData = Keypair.generate(); +const intent = buildSolanaBurnIntent({ + source: SolanaDevnet, + destinationDomain: BaseSepolia.cctpDomain, + amount: 5_000_000n, + maxFee: 50_000n, + mintRecipientBytes32: Buffer.from( + toBytes32("0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e").slice(2), + "hex", + ), + owner, + ownerUsdcAta: getAssociatedTokenAddressSync( + new PublicKey(SolanaDevnet.usdc), + owner, + ), + messageSentEventDataKey: eventData.publicKey, + hookData: Buffer.from(CCTP_FORWARD_HOOK_DATA.slice(2), "hex"), + minFinalityThreshold: FINALITY_STANDARD, +}); + +const tx = new Transaction().add(burnIntentToTransactionInstruction(intent)); +tx.partialSign(eventData); +``` + +| Param | Type | | +| -------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `source` | `SolanaChain` | `Solana` or `SolanaDevnet`. | +| `destinationDomain` | `number` | The destination's `cctpDomain`. | +| `amount` | `bigint` | 6-decimal subunits, above zero, at most 10M USDC, and above `maxFee`. | +| `maxFee` | `bigint` | Fee cap in 6-decimal subunits. Compute it with [`computeMaxFee`](/reference/cctp/fees#computemaxfee). | +| `mintRecipientBytes32` | `Uint8Array` | 32 bytes. An EVM address left-padded (`toBytes32`), a Starknet felt zero-padded, the Stellar forwarder decoded (`strkeyTo32Bytes`). | +| `owner` | `PublicKey` | Signs, and pays the event account rent. | +| `ownerUsdcAta` | `PublicKey` | The owner's USDC token account, which is debited. | +| `messageSentEventDataKey` | `PublicKey` | A fresh keypair's public key. That keypair must also sign. | +| `minFinalityThreshold` | `1000 \| 2000` | From the fee tier. | +| `destinationCallerBytes32` | `Uint8Array` | Optional, 32 bytes. Defaults to any caller. | +| `hookData` | `Uint8Array` | Optional, non-empty. The forwarder bytes, or the Stellar forwarder's hook data. | + +Returns `{ source, destinationDomain, amount, maxFee, instruction, messageSentEventDataKey, withHook }`. `instruction` is a `SolanaInstruction` (`{ programId, keys, data, ecosystem: "solana" }`), kept independent of `@solana/web3.js` minor versions; `burnIntentToTransactionInstruction(intent)` turns it into a `TransactionInstruction`. + +### `buildSolanaReceiveIntent` + +`buildSolanaReceiveIntent(input: BuildSolanaReceiveIntentInput): SolanaReceiveIntent` + +`receive_message` on `MessageTransmitterV2`, with the 20 accounts it and the `TokenMessengerMinterV2` CPI need. The fee recipient's token account is not derivable: read it from the TokenMessenger account on chain. + +```ts +import { Connection, PublicKey, Transaction } from "@solana/web3.js"; +import { getAssociatedTokenAddressSync } from "@solana/spl-token"; +import { + SolanaDevnet, + BaseSepolia, + buildSolanaReceiveIntent, + receiveIntentToTransactionInstruction, + deriveTokenMessenger, + parseTokenMessengerFeeRecipient, + toBytes32, + type IrisMessage, +} from "@usewhisk/cctp"; + +const connection = new Connection(SolanaDevnet.defaultRpcUrls[0]); +const usdcMint = new PublicKey(SolanaDevnet.usdc); + +const tokenMessenger = deriveTokenMessenger( + new PublicKey(SolanaDevnet.tokenMessengerMinter), +); +const account = await connection.getAccountInfo(tokenMessenger); +if (!account) throw new Error("TokenMessenger account not found"); +const feeRecipient = parseTokenMessengerFeeRecipient(account.data); + +const hex = (h: string) => Buffer.from(h.slice(2), "hex"); + +const intent = buildSolanaReceiveIntent({ + destination: SolanaDevnet, + message: hex(msg.message), + attestation: hex(msg.attestation), + sourceDomain: BaseSepolia.cctpDomain, + sourceTokenBytes32: hex(toBytes32(BaseSepolia.usdc)), + feeRecipientUsdcAta: getAssociatedTokenAddressSync(usdcMint, feeRecipient), + recipientUsdcAta: getAssociatedTokenAddressSync(usdcMint, recipientWallet), + payer, +}); + +const tx = new Transaction().add(receiveIntentToTransactionInstruction(intent)); +``` + +| Param | Type | | +| ------------------------ | ------------- | ------------------------------------------------------------------ | +| `destination` | `SolanaChain` | | +| `message`, `attestation` | `Uint8Array` | Raw bytes from Iris (decode the hex). | +| `sourceDomain` | `number` | Domain of the burn's chain. | +| `sourceTokenBytes32` | `Uint8Array` | The source chain's USDC as 32 bytes. | +| `feeRecipientUsdcAta` | `PublicKey` | USDC token account of the TokenMessenger's `fee_recipient`. | +| `recipientUsdcAta` | `PublicKey` | The recipient's USDC token account. It must exist before the mint. | +| `payer` | `PublicKey` | Pays and signs; also passed as `caller`. | + +Returns `{ destination, instruction }`. `receiveIntentToTransactionInstruction(intent)` converts it. + +### Solana helpers + +| Export | | +| ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `parseTokenMessengerFeeRecipient(data: Uint8Array): PublicKey` | Reads `fee_recipient` from the TokenMessenger account data. Throws if the data is too short. | +| `deriveTokenMessenger(tmm)`, `deriveTokenMinter(tmm)`, `deriveSenderAuthority(tmm)` | Config PDAs on `TokenMessengerMinterV2`. | +| `deriveRemoteTokenMessenger(tmm, domain)` | Seeded by the domain as a decimal string, not a `u32`. | +| `deriveLocalToken(tmm, mint)`, `deriveCustodyTokenAccount(tmm, mint)` | Keyed by the local USDC mint. | +| `deriveTokenPair(tmm, sourceDomain, sourceTokenBytes32)` | Maps a source token to the local mint. | +| `deriveDenylistAccount(tmm, owner)` | The burn fails if this PDA holds data. | +| `deriveMessageTransmitter(mt)`, `deriveMessageTransmitterAuthority(mt, receiver)` | PDAs on `MessageTransmitterV2`. | +| `deriveUsedNonce(mt, messageBytes)` | The nonce PDA, from `message[12..44]`. Its existence means the message was received. | +| `deriveEventAuthority(programId)` | Anchor's `__event_authority` PDA. | +| `SOLANA_CCTP_PDA_SEEDS` | The seed prefixes as bytes. | +| `anchorDiscriminator(name)` | First 8 bytes of `sha256("global:" + name)`. | +| `DISCRIMINATOR_DEPOSIT_FOR_BURN`, `DISCRIMINATOR_DEPOSIT_FOR_BURN_WITH_HOOK`, `DISCRIMINATOR_RECEIVE_MESSAGE` | Precomputed discriminators. | +| `SOLANA_ANY_DESTINATION_CALLER` | The all-zero `PublicKey`. | + +Every `derive*` function takes `PublicKey`s and returns the PDA `PublicKey`. + +## Stellar + +Stellar USDC has 7 decimals and CCTP messages carry 6. The Stellar builders take 7-decimal amounts; the contract drops the seventh decimal when it writes the message. + +### Stellar precision + +| Function | | +| ------------------------------- | ----------------------------------------------------------------------------- | +| `canonicalToStellarSubunits(x)` | 6-decimal to 7-decimal: times 10. What a mint to Stellar delivers. | +| `stellarSubunitsToCanonical(x)` | 7-decimal to 6-decimal, rounding toward zero. What a burn from Stellar sends. | +| `stellarBurnDust(x)` | The seventh decimal a burn leaves in the sender's account. | + +So a burn of `12_345_678n` Stellar subunits (1.2345678 USDC) sends `1_234_567n` and leaves `8n` behind. Negative input throws `RangeError`. + +### `buildStellarBurnIntent` + +`buildStellarBurnIntent(input: BuildStellarBurnIntentInput): StellarBurnIntent` + +```ts +import { + StellarTestnet, + BaseSepolia, + FINALITY_STANDARD, + buildStellarApproveInvocation, + buildStellarBurnIntent, + canonicalToStellarSubunits, + toBytes32, +} from "@usewhisk/cctp"; + +const amount = canonicalToStellarSubunits(5_000_000n); +const maxFee = canonicalToStellarSubunits(5_000n); + +const approve = buildStellarApproveInvocation({ + source: StellarTestnet, + owner: caller, + spender: StellarTestnet.tokenMessengerMinter, + amount, + expirationLedger: latestLedger + 100, +}); + +const burn = buildStellarBurnIntent({ + source: StellarTestnet, + destinationDomain: BaseSepolia.cctpDomain, + mintRecipientBytes32: Buffer.from( + toBytes32("0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e").slice(2), + "hex", + ), + destinationCallerBytes32: new Uint8Array(32), + amount, + maxFee, + caller, + minFinalityThreshold: FINALITY_STANDARD, +}); +``` + +The token messenger pulls USDC with `transfer_from`, so the approve runs first. `buildStellarApproveInvocation` takes `source`, `owner` (strkey), `spender` (usually `tokenMessengerMinter`), `amount` in 7-decimal subunits and `expirationLedger`. The SAC rejects an allowance that expires before the current ledger, so pass the latest ledger plus a short window. + +`buildStellarBurnIntent` targets `deposit_for_burn`, or `deposit_for_burn_with_hook` when `hookData` is non-empty: + +| Param | Type | | +| -------------------------- | -------------- | --------------------------------------------------------- | +| `source` | `StellarChain` | | +| `destinationDomain` | `number` | | +| `mintRecipientBytes32` | `Uint8Array` | 32 bytes. For Solana, the recipient's USDC token account. | +| `destinationCallerBytes32` | `Uint8Array` | 32 bytes. All zeros lets anyone mint. Required here. | +| `amount`, `maxFee` | `bigint` | 7-decimal Stellar subunits. | +| `caller` | `string` | G or C strkey that authorizes the burn. | +| `minFinalityThreshold` | `1000 \| 2000` | Always `FINALITY_STANDARD`: Stellar has no Fast Transfer. | +| `hookData` | `Uint8Array` | Optional. | + +Both return a `StellarInvocation`: `{ ecosystem: "stellar", contractId, functionName, args, operation }`, where `operation` is a ready `xdr.Operation` to wrap in a Soroban transaction. You assemble, simulate and sign the transaction. The burn intent is `{ source, destinationDomain, amount, maxFee, invocation, withHook }`. + +### `buildStellarMintIntent` + +`buildStellarMintIntent(input: BuildStellarMintIntentInput): StellarMintIntent` + +```ts +import { + StellarTestnet, + buildStellarMintIntent, + type IrisMessage, +} from "@usewhisk/cctp"; + +const hex = (h: string) => Buffer.from(h.slice(2), "hex"); + +const { invocation } = buildStellarMintIntent({ + destination: StellarTestnet, + message: hex(msg.message), + attestation: hex(msg.attestation), +}); +``` + +Builds `mint_and_forward(message, attestation)` on the destination's `CctpForwarder`, which mints and passes the USDC to the recipient named in the hook data in one atomic call. Returns `{ destination, invocation }`. + +### Strkey helpers + +| Export | | +| ------------------------------------------------ | -------------------------------------------------------------------------------- | +| `isValidStellarStrkey(s)` | `true` for a valid G, M or C strkey. | +| `strkeyType(s)` | `"G" \| "M" \| "C"` (`StellarStrkeyType`). Throws on anything else. | +| `decodeStrkeyToBytes32(s)`, `strkeyTo32Bytes(s)` | The 32-byte payload CCTP carries. For an M address, the underlying account key. | +| `contractStrkeyToBytes32Hex(s)` | A C strkey as `0x` 32-byte hex, for EVM `mintRecipient` and `destinationCaller`. | +| `encodeContractStrkey(bytes)` | 32 bytes back to a C strkey. | + +## Starknet + +### `buildStarknetBurnIntent` + +`buildStarknetBurnIntent(input: BuildStarknetBurnIntentInput): StarknetBurnIntent` + +```ts +import { + StarknetSepolia, + BaseSepolia, + FINALITY_FAST, + buildStarknetApproveCall, + buildStarknetBurnIntent, + toBytes32, +} from "@usewhisk/cctp"; + +const amount = 5_000_000n; + +const approve = buildStarknetApproveCall({ + source: StarknetSepolia, + spender: StarknetSepolia.tokenMessengerMinter, + amount, +}); + +const burn = buildStarknetBurnIntent({ + source: StarknetSepolia, + destinationDomain: BaseSepolia.cctpDomain, + amount, + maxFee: 10_000n, + mintRecipient: BigInt( + toBytes32("0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e"), + ), + destinationCaller: 0n, + minFinalityThreshold: FINALITY_FAST, +}); + +const calls = [approve, burn.call]; +``` + +Starknet USDC is ERC-20 style, so `buildStarknetApproveCall({ source, spender, amount })` comes first. Send both calls in one multicall. + +| Param | Type | | +| ---------------------- | --------------- | ------------------------------------------------------------------------------- | +| `source` | `StarknetChain` | | +| `destinationDomain` | `number` | | +| `amount`, `maxFee` | `bigint` | 6-decimal subunits. | +| `mintRecipient` | `bigint` | The 32-byte recipient as a `u256`. | +| `destinationCaller` | `bigint` | `0n` lets anyone mint. | +| `minFinalityThreshold` | `1000 \| 2000` | From the fee tier. | +| `hookData` | `Uint8Array` | Optional. Selects `deposit_for_burn_with_hook`, encoded as a Cairo `ByteArray`. | + +Returns `{ source, destinationDomain, amount, maxFee, call, withHook }`. A `StarknetCall` is `{ contractAddress, entrypoint, calldata }` with calldata as decimal felt strings, ready for `account.execute`. + +### `buildStarknetReceiveIntent` + +`buildStarknetReceiveIntent(input: BuildStarknetReceiveIntentInput): StarknetReceiveIntent` + +```ts +import { + StarknetSepolia, + buildStarknetReceiveIntent, + type IrisMessage, +} from "@usewhisk/cctp"; + +const { call } = buildStarknetReceiveIntent({ + destination: StarknetSepolia, + message: msg.message, + attestation: msg.attestation, +}); +console.log(call.entrypoint, call.calldata.length); +``` + +`receive_message(message: ByteArray, attestation: ByteArray)` on the destination's `MessageTransmitter`. Takes the `0x` hex straight from Iris. Returns `{ destination, call }`. Starknet is not a Forwarding Service destination, so every transfer to Starknet ends with this call. + +### Felt and calldata helpers + +| Export | | +| ---------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `isValidStarknetFelt(s)`, `assertStarknetFelt(s)` | Check a `0x` felt of up to 64 hex digits; the second throws and returns it typed. | +| `feltToBytes32Hex(felt)` | Zero-pads to 32-byte hex, for `mintRecipient` from other chains. | +| `bytes32HexToFelt(hex)` | Back to a felt, leading zeros stripped. | +| `feltToBigInt(felt)` | For `u256` arguments. | +| `u256ToFelts(value)` | `[low, high]` as decimal strings. | +| `starknetFeltToString(value)` | A number, bigint or hex string as one decimal felt string. | +| `bytesToByteArrayFelts(bytes)`, `hexToByteArrayFelts(hex)` | Raw bytes as Cairo `ByteArray` calldata. | + +## Hook data and destination caller + +| Export | | +| ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `CCTP_FORWARD_HOOK_DATA` | The 32 bytes that ask Circle's relayer to mint: `"cctp-forward"`, zero padding, version `0`, payload length `0`. | +| `CCTP_FORWARD_HOOK_DATA_LENGTH` | `32`. | +| `buildForwarderHookData()` | Encodes the same bytes field by field. | +| `isForwarderHookData(hex)` | `true` when `hex` starts with those 32 bytes. | +| `ANY_DESTINATION_CALLER` | `bytes32(0)`: anyone may submit the mint. | + +The forwarder fee is not in the hook data. Circle takes it, with the protocol fee, out of the burned amount, capped by `maxFee`. Size `maxFee` with [`computeMaxFee`](/reference/cctp/fees#computemaxfee) so it covers both: a cap one subunit short of the Fast fee turns a Fast transfer into a Standard one. + +## Address encoding + +```ts +import { + toBytes32, + fromBytes32, + tryFromBytes32, + isAddress, + feltToBytes32Hex, + bytes32HexToFelt, + strkeyType, + strkeyTo32Bytes, + stellarSubunitsToCanonical, + stellarBurnDust, +} from "@usewhisk/cctp"; + +const evm = toBytes32("0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e"); +console.log(fromBytes32(evm), tryFromBytes32("0x01"), isAddress("0x12")); + +const starknet = feltToBytes32Hex( + "0x4bdde1e09a4b09a2f95d893d94a967b7717eb85a3f6deca8c080ee01fbc3370", +); +console.log(bytes32HexToFelt(starknet)); + +const g = "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H"; +console.log(strkeyType(g), strkeyTo32Bytes(g).length); + +console.log( + stellarSubunitsToCanonical(12_345_678n), + stellarBurnDust(12_345_678n), +); +``` + +- `toBytes32(address)` left-pads a 20-byte EVM address to 32 bytes, lowercase. Throws `InvalidAddressError`. +- `fromBytes32(value)` strips the padding and returns the lowercase address. Throws `InvalidBytes32Error` when the value is not 32 bytes or the top 12 bytes are not zero. `tryFromBytes32` returns `undefined` instead. +- `isAddress(value)` checks for `0x` and 40 hex digits. It does not check the checksum. + +## Decoding a message + +`decodeBurnMessage(message)` splits the attested bytes into the header and burn body. Use it to check what a message will mint before you pay gas for it. + +```ts +import { + ArbitrumSepolia, + decodeBurnMessage, + fromBytes32, + isNonceUsed, + getTransactionStatus, + type IrisMessage, +} from "@usewhisk/cctp"; + +const decoded = decodeBurnMessage(msg.message); +console.log( + decoded.sourceDomain, + decoded.body.amount, + decoded.body.feeExecuted, + fromBytes32(decoded.body.mintRecipient), +); + +const minted = await isNonceUsed(ArbitrumSepolia, decoded.nonce); +if (!minted) { + console.log("Still needs a mint"); +} + +const status = await getTransactionStatus(ArbitrumSepolia, mintTxHash, { + rpcUrls: ["https://my-node.example/arbitrum-sepolia"], +}); +``` + +`DecodedBurnMessage` has `version`, `sourceDomain`, `destinationDomain`, `nonce`, `sender`, `recipient`, `destinationCaller`, `minFinalityThreshold`, `finalityThresholdExecuted` and a `body` with `version`, `burnToken`, `mintRecipient`, `amount`, `messageSender`, `maxFee`, `feeExecuted`, `expirationBlock` and `hookData`. Addresses are the 32-byte form; amounts are 6-decimal `bigint` subunits. The recipient gets `amount - feeExecuted`. `expirationBlock` is a destination block height, `0n` once the message is final; past it, ask Iris to [reattest](/reference/cctp/iris#reattest). Non-hex or short input throws `InvalidInputError`. + +## Reading chain state + +A few JSON-RPC reads cover what a recovery flow or a recipient check needs. Each tries `options.rpcUrls` first, then the chain's `defaultRpcUrls`, moving on after a failed or malformed answer, and throws `ProtocolError("rpc_unavailable")` when every URL fails. `RpcOptions` is `{ rpcUrls?: readonly string[]; fetch?: typeof fetch }`. + +```ts +import { + StarknetSepolia, + StellarTestnet, + BaseSepolia, + getUsdcBalance, + getGasPrice, + getBlockNumber, + isStarknetNonceUsed, + isStellarNonceUsed, + getStarknetTransactionStatus, + getStarknetClassHashAt, +} from "@usewhisk/cctp"; + +const balance = await getUsdcBalance( + BaseSepolia, + "0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e", +); +const gasPrice = await getGasPrice(BaseSepolia); +const head = await getBlockNumber(BaseSepolia); +const onStarknet = await isStarknetNonceUsed(StarknetSepolia, nonce); +const onStellar = await isStellarNonceUsed(StellarTestnet, nonce); +const tx = await getStarknetTransactionStatus(StarknetSepolia, "0x1234"); +if (tx.state !== "pending") console.log(tx.blockNumber); +const classHash = await getStarknetClassHashAt( + StarknetSepolia, + "0x04a3f9c2b7d1e8a6c5f0b3d9e2a7c1f6b8d4e0a5c3f7b2d9e6a1c8f4b0d3e7a2", +); +if (classHash === null) console.log("no account deployed there"); +``` + +| Function | Returns | +| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `getUsdcBalance(evmChain, owner)` | USDC balance in 6-decimal subunits. | +| `getGasPrice(evmChain)` | `eth_gasPrice` in wei (on Arc, 18-decimal USDC units). | +| `getBlockNumber(evmChain)` | Latest block as `bigint`. | +| `getTransactionStatus(evmChain, hash)` | `TransactionStatus`: `"success"`, `"reverted"`, or `"unknown"` until mined. | +| `isNonceUsed(evmChain, nonce)` | `true` once the message was received on that chain. A second mint would revert. | +| `isStarknetNonceUsed(starknetChain, nonce)` | The same on Starknet. | +| `isStellarNonceUsed(stellarChain, nonce)` | The same on Stellar, read by simulating the call. | +| `getStarknetTransactionStatus(starknetChain, hash)` | `StarknetTransactionStatus`: `{ state: "pending" }` or `{ state: "success" \| "reverted", blockNumber }`. | +| `getStarknetClassHashAt(starknetChain, address)` | The class hash of the contract at `address` (`starknet_getClassHashAt` at `latest`), or `null` when nothing is deployed there (RPC error 20). `@usewhisk/core` uses it to refuse undeployed Starknet recipients. | + +`nonce` is the 32-byte `0x` nonce from the message (`decodeBurnMessage(msg).nonce`). For Solana, check whether the `deriveUsedNonce` account exists. + +The public RPCs in the registry are rate-limited and sometimes wrong. Pass your own `rpcUrls` for anything that decides whether to move money. diff --git a/reference/cctp/chains.mdx b/reference/cctp/chains.mdx new file mode 100644 index 0000000..0d4a618 --- /dev/null +++ b/reference/cctp/chains.mdx @@ -0,0 +1,369 @@ +--- +title: Chain registry +description: Every CCTP V2 chain Whisk supports, with its domain, contracts, USDC address and capabilities, and the lookups over them. +--- + +The registry is a typed table of every chain CCTP V2 serves on EVM, Solana, Stellar and Starknet, mainnet and testnet. Builders and Iris calls take entries from it. + +```ts +import { + getChain, + chainByEvmChainId, + chainByDomain, + chainsByNetwork, + isChainId, + attestationSeconds, +} from "@usewhisk/cctp"; + +const base = getChain("Base_Sepolia"); +console.log(base.cctpDomain, base.usdc, base.capabilities.fastSource); + +const fromWallet = chainByEvmChainId(84_532); +const fromIris = chainByDomain(6, "testnet"); +const testnets = chainsByNetwork("testnet"); + +const input: string = "Arc_Testnet"; +if (isChainId(input)) { + const { min, max } = attestationSeconds(getChain(input), "standard"); + console.log(min, max); +} +``` + +The registry is also published on its own as `@usewhisk/cctp/chains`, and `@usewhisk/core` and `@usewhisk/react` re-export it. + +## Lookups + +| Function | Returns | When nothing matches | +| ------------------------------------------------- | ----------------------- | -------------------------- | +| `getChain(id: ChainId)` | `CctpChain` | throws `UnknownChainError` | +| `chainByEvmChainId(evmChainId: number)` | `EvmChain` | throws `UnknownChainError` | +| `tryChainByEvmChainId(evmChainId: number)` | `EvmChain \| undefined` | `undefined` | +| `chainByDomain(domain: number, network: Network)` | `CctpChain` | throws `UnknownChainError` | +| `chainsByNetwork(network: Network)` | `readonly CctpChain[]` | empty array | +| `isChainId(value: string)` | `value is ChainId` | `false` | + +`ChainId` is the union of every `id` string in `CHAINS` (`"Ethereum"`, `"Base_Sepolia"`, `"Solana_Devnet"` and so on), so `getChain("Base_Sepoila")` fails to compile. Use `isChainId` to narrow a string from user input or a URL first. + +Mainnet and testnet share a CCTP domain (Base and Base Sepolia are both domain 6), so `chainByDomain` needs the network. Iris tells the two apart by host, not by domain. Use `tryChainByEvmChainId` for a wallet's current chain, which can be any chain the wallet knows. + +`UnknownChainError` extends `InvalidInputError` with code `invalid_chain`. + +### Type guards and explorer links + +```ts +import { + getChain, + isEvmChain, + tryChainByEvmChainId, + explorerTxUrl, + explorerAddressUrl, + UnknownChainError, + chainByDomain, +} from "@usewhisk/cctp"; + +const supported = tryChainByEvmChainId(walletChainId); +if (!supported) console.log("Switch to a CCTP chain"); + +const devnet = getChain("Solana_Devnet"); +console.log(explorerTxUrl(devnet, "5Uf...sig")); +console.log( + explorerAddressUrl( + getChain("Stellar"), + "CBZL2IH7F6BIDAA3WBNXYKIXSATJGMSW7K5P5MJ6STX5RXN47TZJDF5T", + ), +); + +const arc = getChain("Arc"); +if (isEvmChain(arc)) console.log(arc.evmChainId); + +try { + chainByDomain(4, "mainnet"); +} catch (err) { + if (err instanceof UnknownChainError) console.log(err.code); +} +``` + +`isEvmChain`, `isSolanaChain`, `isStellarChain` and `isStarknetChain` narrow a `CctpChain` to its ecosystem type. Switching on `chain.ecosystem` does the same. + +`explorerTxUrl(chain, txHash)` and `explorerAddressUrl(chain, address)` build links on the chain's explorer and append `explorerQuery` (Solana Devnet's `?cluster=devnet`). Address links use `/contract/` on Starknet, `/contract/` or `/account/` on Stellar depending on the strkey, and `/address/` elsewhere. + +## The `CctpChain` shape + +`CctpChain` is a union of four types, told apart by `ecosystem`. Every entry is `as const`, so `Base.cctpDomain` has the literal type `6`. + +```ts +import { getChain, type CctpChain } from "@usewhisk/cctp"; + +function describe(chain: CctpChain): string { + switch (chain.ecosystem) { + case "evm": + return `EVM chain ${chain.evmChainId}, TokenMessengerV2 ${chain.tokenMessenger}`; + case "solana": + return `Solana ${chain.cluster}, program ${chain.tokenMessengerMinter}`; + case "stellar": + return `Stellar ${chain.stellarNetwork}, forwarder ${chain.cctpForwarder}`; + case "starknet": + return `Starknet ${chain.starknetNetwork}, chain id ${chain.chainId}`; + } +} + +console.log(describe(getChain("Stellar_Testnet"))); +``` + +### Fields on every chain + ++ Stable string id, such as `"Arc"` or `"Base_Sepolia"`. These are the same ids + Whisk 0.1 used. + ++ Display name, such as `"OP Mainnet"`. + ++ The discriminant (`Ecosystem`). + ++ The `Network`. Pass it to every Iris call for a transfer from this chain. + ++ Circle's domain id (`CctpDomain`). Shared by a mainnet and its testnet. + ++ `7` on Stellar, `6` everywhere else. + ++ The gas token. On Arc it is USDC with 18 decimals. + ++ Public RPCs, tried in order by the [RPC + helpers](/reference/cctp/builders#reading-chain-state). Use your own in + production. + ++ Explorer base URL, without a trailing slash. + ++ Optional. Appended to explorer links for explorers that serve several + networks. + ++ What Circle offers on this chain. See [Capabilities](#capabilities). + + +### `EvmChain` + +| Field | Type | Notes | +| ------------------------ | ------------------- | ----------------------------------------------------------------------------------- | +| `evmChainId` | `number` | The EIP-155 chain id (`EvmChainId`). | +| `usdc` | `` `0x${string}` `` | USDC ERC-20 address (`Address`). | +| `tokenMessenger` | `Address` | `TokenMessengerV2`. One address on every testnet, and on every mainnet except EDGE. | +| `messageTransmitter` | `Address` | `MessageTransmitterV2`. Same rule. | +| `tokenMessengerWithFees` | `Address` | Optional. Present exactly when `capabilities.upfrontFeeSource` is true. | + +### `SolanaChain` + +| Field | Type | Notes | +| ---------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------ | +| `cluster` | `"mainnet-beta" \| "devnet"` | `SolanaCluster`. | +| `usdc` | `string` | USDC SPL mint, base58 (`SolanaPubkey`). | +| `tokenMessengerMinter` | `SolanaPubkey` | `TokenMessengerMinterV2` program. Solana merges TokenMessenger and TokenMinter into one program. | +| `messageTransmitter` | `SolanaPubkey` | `MessageTransmitterV2` program. | + +The program ids are the same on mainnet-beta and devnet; only the USDC mint differs. + +### `StellarChain` + +| Field | Type | Notes | +| ---------------------- | ----------------------- | ----------------------------------------------------------------------------------- | +| `stellarNetwork` | `"public" \| "testnet"` | `StellarNetwork`. | +| `networkPassphrase` | `string` | Needed to sign Soroban transactions. | +| `usdcIssuer` | `string` | Circle's USDC issuer account, a G strkey (`StellarStrkey`). | +| `usdc` | `StellarStrkey` | The USDC Stellar Asset Contract (C strkey), derived from the issuer and passphrase. | +| `tokenMessengerMinter` | `StellarStrkey` | Burn contract. | +| `messageTransmitter` | `StellarStrkey` | Receive contract. | +| `cctpForwarder` | `StellarStrkey` | Circle's `CctpForwarder` contract. | + ++ A burn to Stellar must name `cctpForwarder` as both `mintRecipient` and + `destinationCaller`, with the real recipient in the hook data. A user account + as `mintRecipient` loses the funds for good. See [burns to + Stellar](/reference/cctp/builders#burns-to-stellar). + + +### `StarknetChain` + +| Field | Type | Notes | +| ---------------------- | ------------------------ | ------------------------------------------------------------------------------------------------ | +| `starknetNetwork` | `"mainnet" \| "sepolia"` | `StarknetNetwork`. | +| `chainId` | `` `0x${string}` `` | `SN_MAIN` or `SN_SEPOLIA` as a shortstring felt (`StarknetFelt`). Wallets check it when signing. | +| `usdc` | `StarknetFelt` | USDC contract. | +| `tokenMessengerMinter` | `StarknetFelt` | Burn contract. | +| `messageTransmitter` | `StarknetFelt` | Receive contract. | + +## Capabilities + +`ChainCapabilities` comes from Circle's CCTP tables, per chain. Mainnet and testnet can differ. + ++ Circle offers Fast Transfer for burns from this chain. On the others, Standard + (hard finality) is the only option, and `buildBurnIntent` refuses a Fast fee + tier with `ProtocolError("no_route")`. + ++ Circle's Forwarding Service can mint on this chain. When it is false, burn + with `withForwarder: false` and submit the mint yourself. + ++ Iris quotes an upfront fee for burns from this chain, paid through + `TokenMessengerWithFees`. See + [`buildBurnWithFeesIntent`](/reference/cctp/builders#buildburnwithfeesintent). + ++ `TokenMessengerV2` has `getMinFeeAmount`, which can make a Standard burn cost + more than Iris says. Read it with + [`getStandardMinFee`](/reference/cctp/fees#getstandardminfee). On the other + chains the call reverts. + + +## Attestation times + +`attestationSeconds(chain, speed)` returns Circle's published average time to attest a burn from `chain`, as a `SecondsRange` (`{ min, max }`, in seconds). `speed` is `"fast"` or `"standard"` (`TransferSpeed`). The mint comes after the attestation, so the payer waits a little longer than this. + +Circle publishes mainnet figures only; testnets share the domain and use the same numbers. Asking for `"fast"` on a chain without Fast throws `ProtocolError("no_route")`. + +| Domain | Chains | Fast | Standard | +| --------------------------- | ---------------------------------------------------------------- | ---- | -------------- | +| 0 | Ethereum | 20 s | 900 to 1140 s | +| 1 | Avalanche | | 8 s | +| 2, 3, 6, 10, 12, 14, 22, 37 | OP, Arbitrum, Base, Unichain, Codex, World Chain, Plume, X Layer | 8 s | 900 to 1140 s | +| 5 | Solana | 8 s | 25 s | +| 7 | Polygon PoS | | 8 s | +| 11 | Linea | 8 s | 6 to 32 hours | +| 13 | Sonic | | 8 s | +| 15, 16, 19 | Monad, Sei, HyperEVM | | 5 s | +| 18 | XDC | | 10 s | +| 21 | Ink | 8 s | 1800 s | +| 25 | Starknet | 20 s | 2 to 4 hours | +| 26 | Arc | | 0.5 s | +| 27 | Stellar | | 5 s | +| 28 | EDGE | 8 s | 960 to 1260 s | +| 29 | Injective | | 0.65 s | +| 30 | Morph | 8 s | 1200 to 1800 s | +| 31 | Pharos | | 7 s | +| 32 | Cronos | | 0.5 s | +| 33 | Plasma | | 1 s | + +[`pollBudget`](/reference/cctp/iris#pollbudget) turns a `SecondsRange` into a polling interval and timeout. + +## Every chain + +`CHAINS` is the full list, as a readonly tuple: the EVM mainnets, the EVM testnets, then Solana, Solana Devnet, Stellar, Stellar Testnet, Starknet and Starknet Sepolia. `EVM_MAINNET_CHAINS` and `EVM_TESTNET_CHAINS` hold the EVM halves. + +This table is printed from the published registry by `scripts/gen-chains-table.mjs` in the docs repo (`npx -y -p @usewhisk/cctp@0.1.1 node scripts/gen-chains-table.mjs`). + +| Id | Label | Ecosystem | Network | Domain | Fast source | USDC | Explorer | +| ---------------------- | ------------------- | --------- | ------- | ------ | ----------- | -------------------------------------------------------------------- | ----------------------------------------------- | +| `Ethereum` | Ethereum | evm | mainnet | 0 | yes | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | https://etherscan.io | +| `Avalanche` | Avalanche | evm | mainnet | 1 | no | `0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E` | https://explorer.avax.network/c-chain | +| `Optimism` | OP Mainnet | evm | mainnet | 2 | yes | `0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85` | https://explorer.optimism.io | +| `Arbitrum` | Arbitrum | evm | mainnet | 3 | yes | `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | https://arbiscan.io | +| `Base` | Base | evm | mainnet | 6 | yes | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | https://basescan.org | +| `Polygon` | Polygon PoS | evm | mainnet | 7 | no | `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | https://polygonscan.com | +| `Unichain` | Unichain | evm | mainnet | 10 | yes | `0x078D782b760474a361dDA0AF3839290b0EF57AD6` | https://uniscan.xyz | +| `Linea` | Linea | evm | mainnet | 11 | yes | `0x176211869cA2b568f2A7D4EE941E073a821EE1ff` | https://lineascan.build | +| `Codex` | Codex | evm | mainnet | 12 | yes | `0xd996633a415985DBd7D6D12f4A4343E31f5037cf` | https://explorer.codex.xyz | +| `Sonic` | Sonic | evm | mainnet | 13 | no | `0x29219dd400f2Bf60E5a23d13Be72B486D4038894` | https://sonicscan.org | +| `World_Chain` | World Chain | evm | mainnet | 14 | yes | `0x79A02482A880bCE3F13e09Da970dC34db4CD24d1` | https://worldscan.org | +| `Monad` | Monad | evm | mainnet | 15 | no | `0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | https://monadvision.com | +| `Sei` | Sei | evm | mainnet | 16 | no | `0xe15fC38F6D8c56aF07bbCBe3BAf5708A2Bf42392` | https://seiscan.io | +| `XDC` | XDC | evm | mainnet | 18 | no | `0xfA2958CB79b0491CC627c1557F441eF849Ca8eb1` | https://xdcscan.io | +| `HyperEVM` | HyperEVM | evm | mainnet | 19 | no | `0xb88339CB7199b77E23DB6E890353E22632Ba630f` | https://hyperevmscan.io | +| `Ink` | Ink | evm | mainnet | 21 | yes | `0x2D270e6886d130D724215A266106e6832161EAEd` | https://explorer.inkonchain.com | +| `Plume` | Plume | evm | mainnet | 22 | yes | `0x222365EF19F7947e5484218551B56bb3965Aa7aF` | https://explorer.plume.org | +| `Arc` | Arc | evm | mainnet | 26 | no | `0x3600000000000000000000000000000000000000` | https://explorer.arc.io | +| `Edge` | EDGE | evm | mainnet | 28 | yes | `0x98d2919b9A214E6Fa5384AC81E6864bA686Ad74c` | https://pro.edgex.exchange/en-US/explorer | +| `Injective` | Injective | evm | mainnet | 29 | no | `0xa00C59fF5a080D2b954d0c75e46E22a0c371235a` | https://blockscout.injective.network | +| `Morph` | Morph | evm | mainnet | 30 | yes | `0xCfb1186F4e93D60E60a8bDd997427D1F33bc372B` | https://explorer.morph.network | +| `Pharos` | Pharos | evm | mainnet | 31 | no | `0xC879C018dB60520F4355C26eD1a6D572cdAC1815` | https://www.pharosscan.xyz | +| `Cronos` | Cronos | evm | mainnet | 32 | no | `0x3D7F2C478aAfdB65542BCB44bCeeC05849999d2D` | https://explorer.cronos.com | +| `Plasma` | Plasma | evm | mainnet | 33 | no | `0x2d661C89D812261039AF9764eceaAee884f5F67F` | https://plasmascan.to | +| `X_Layer` | X Layer | evm | mainnet | 37 | yes | `0xB6CEceAB302E2E4948951eE7843FC24E92933061` | https://www.okx.com/web3/explorer/xlayer | +| `Ethereum_Sepolia` | Ethereum Sepolia | evm | testnet | 0 | yes | `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238` | https://sepolia.etherscan.io | +| `Avalanche_Fuji` | Avalanche Fuji | evm | testnet | 1 | no | `0x5425890298aed601595a70AB815c96711a31Bc65` | https://explorer-test.avax.network/c-chain | +| `Optimism_Sepolia` | OP Sepolia | evm | testnet | 2 | yes | `0x5fd84259d66Cd46123540766Be93DFE6D43130D7` | https://testnet-explorer.optimism.io | +| `Arbitrum_Sepolia` | Arbitrum Sepolia | evm | testnet | 3 | yes | `0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d` | https://sepolia.arbiscan.io | +| `Base_Sepolia` | Base Sepolia | evm | testnet | 6 | yes | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | https://sepolia.basescan.org | +| `Polygon_Amoy_Testnet` | Polygon PoS Amoy | evm | testnet | 7 | no | `0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582` | https://amoy.polygonscan.com | +| `Unichain_Sepolia` | Unichain Sepolia | evm | testnet | 10 | yes | `0x31d0220469e10c4E71834a79b1f276d740d3768F` | https://sepolia.uniscan.xyz | +| `Linea_Sepolia` | Linea Sepolia | evm | testnet | 11 | yes | `0xFEce4462D57bD51A6A552365A011b95f0E16d9B7` | https://sepolia.lineascan.build | +| `Codex_Testnet` | Codex Testnet | evm | testnet | 12 | yes | `0x6d7f141b6819C2c9CC2f818e6ad549E7Ca090F8f` | https://explorer.codex-stg.xyz | +| `Sonic_Testnet` | Sonic Testnet | evm | testnet | 13 | no | `0x0BA304580ee7c9a980CF72e55f5Ed2E9fd30Bc51` | https://testnet.sonicscan.org | +| `World_Chain_Sepolia` | World Chain Sepolia | evm | testnet | 14 | yes | `0x66145f38cBAC35Ca6F1Dfb4914dF98F1614aeA88` | https://worldchain-sepolia.explorer.alchemy.com | +| `Monad_Testnet` | Monad Testnet | evm | testnet | 15 | no | `0x534b2f3A21130d7a60830c2Df862319e593943A3` | https://testnet.monadvision.com | +| `Sei_Testnet` | Sei Testnet | evm | testnet | 16 | no | `0x4fCF1784B31630811181f670Aea7A7bEF803eaED` | https://testnet.seiscan.io | +| `XDC_Apothem` | XDC Apothem | evm | testnet | 18 | no | `0xb5AB69F7bBada22B28e79C8FFAECe55eF1c771D4` | https://testnet.xdcscan.com | +| `HyperEVM_Testnet` | HyperEVM Testnet | evm | testnet | 19 | no | `0x2B3370eE501B4a559b57D449569354196457D8Ab` | https://app.hyperliquid-testnet.xyz/explorer | +| `Ink_Testnet` | Ink Testnet | evm | testnet | 21 | yes | `0xFabab97dCE620294D2B0b0e46C68964e326300Ac` | https://explorer-sepolia.inkonchain.com | +| `Plume_Testnet` | Plume Testnet | evm | testnet | 22 | yes | `0xcB5f30e335672893c7eb944B374c196392C19D18` | https://testnet-explorer.plume.org | +| `Arc_Testnet` | Arc Testnet | evm | testnet | 26 | no | `0x3600000000000000000000000000000000000000` | https://explorer.testnet.arc.io | +| `Edge_Testnet` | EDGE Testnet | evm | testnet | 28 | yes | `0x2d9F7CAD728051AA35Ecdc472a14cf8cDF5CFD6B` | https://edge-testnet.explorer.alchemy.com | +| `Injective_Testnet` | Injective Testnet | evm | testnet | 29 | no | `0x0C382e685bbeeFE5d3d9C29e29E341fEE8E84C5d` | https://testnet.blockscout.injective.network | +| `Morph_Testnet` | Morph Hoodi Testnet | evm | testnet | 30 | yes | `0x7433b41C6c5e1d58D4Da99483609520255ab661B` | https://explorer-hoodi.morph.network | +| `Pharos_Testnet` | Pharos Testnet | evm | testnet | 31 | no | `0xcfC8330f4BCAB529c625D12781b1C19466A9Fc8B` | https://atlantic.pharosscan.xyz | +| `Cronos_Testnet` | Cronos Testnet | evm | testnet | 32 | no | `0xEb33dc5fac03833e132593659e1dE7256aB59794` | https://explorer.cronos.com/testnet | +| `Plasma_Testnet` | Plasma Testnet | evm | testnet | 33 | no | `0xE67Fb267022cBA8064Dd388CC2FED724F3120D9D` | https://testnet.plasmascan.to | +| `X_Layer_Testnet` | X Layer Testnet | evm | testnet | 37 | yes | `0xDec90b78111Ba2fc6FC6d84d8B9ec159A2d4b9B3` | https://www.okx.com/web3/explorer/xlayer-test | +| `Solana` | Solana | solana | mainnet | 5 | yes | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | https://explorer.solana.com | +| `Solana_Devnet` | Solana Devnet | solana | testnet | 5 | yes | `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU` | https://explorer.solana.com?cluster=devnet | +| `Stellar` | Stellar | stellar | mainnet | 27 | no | `CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75` | https://stellar.expert/explorer/public | +| `Stellar_Testnet` | Stellar Testnet | stellar | testnet | 27 | no | `CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA` | https://stellar.expert/explorer/testnet | +| `Starknet` | Starknet | starknet | mainnet | 25 | yes | `0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb` | https://voyager.online | +| `Starknet_Sepolia` | Starknet Sepolia | starknet | testnet | 25 | yes | `0x0512feAc6339Ff7889822cb5aA2a86C848e9D392bB0E3E237C008674feeD8343` | https://sepolia.voyager.online | + +Each entry is also exported as a constant, in the same order: `Ethereum`, `Avalanche`, `Optimism`, `Arbitrum`, `Base`, `Polygon`, `Unichain`, `Linea`, `Codex`, `Sonic`, `WorldChain`, `Monad`, `Sei`, `XDC`, `HyperEVM`, `Ink`, `Plume`, `Arc`, `Edge`, `Injective`, `Morph`, `Pharos`, `Cronos`, `Plasma`, `XLayer`, `EthereumSepolia`, `AvalancheFuji`, `OptimismSepolia`, `ArbitrumSepolia`, `BaseSepolia`, `PolygonAmoyTestnet`, `UnichainSepolia`, `LineaSepolia`, `CodexTestnet`, `SonicTestnet`, `WorldChainSepolia`, `MonadTestnet`, `SeiTestnet`, `XDCApothem`, `HyperEVMTestnet`, `InkTestnet`, `PlumeTestnet`, `ArcTestnet`, `EdgeTestnet`, `InjectiveTestnet`, `MorphTestnet`, `PharosTestnet`, `CronosTestnet`, `PlasmaTestnet`, `XLayerTestnet`, `Solana`, `SolanaDevnet`, `Stellar`, `StellarTestnet`, `Starknet`, `StarknetSepolia`. + +## Contract and network constants + +The addresses inside the entries are exported on their own too. EDGE mainnet has its own `TokenMessengerV2` and `MessageTransmitterV2`, so read those from the `Edge` entry rather than the EVM constants. + +| Constant | Value | +| -------------------------------------------- | -------------------------------------------------------------------- | +| `TOKEN_MESSENGER_V2_EVM_MAINNET` | `0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d` | +| `MESSAGE_TRANSMITTER_V2_EVM_MAINNET` | `0x81D40F21F12A8F0E3252Bccb954D722d4c464B64` | +| `TOKEN_MESSENGER_WITH_FEES_EVM_MAINNET` | `0x71f54F818671cD0D7ea140Da213e5C8b5C92a408` | +| `TOKEN_MESSENGER_V2_EVM_TESTNET` | `0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA` | +| `MESSAGE_TRANSMITTER_V2_EVM_TESTNET` | `0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275` | +| `TOKEN_MESSENGER_WITH_FEES_EVM_TESTNET` | `0x8745D906D67C346E5eb1aEEED38Eb87F34DF0C0A` | +| `TOKEN_MESSENGER_MINTER_V2_SOLANA` | `CCTPV2vPZJS2u2BBsUoscuikbYjnpFmbFsvVuJdgUMQe` | +| `MESSAGE_TRANSMITTER_V2_SOLANA` | `CCTPV2Sm4AdWt5296sk4P66VBZ7bEhcARwFaaS9YPbeC` | +| `USDC_SPL_MAINNET` | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` | +| `USDC_SPL_DEVNET` | `4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU` | +| `TOKEN_MESSENGER_MINTER_STELLAR_MAINNET` | `CAE2G5Z77UP7GYPYGFOWFGW7C7J6I4YP2AFGSADRKQY62SYUFLPNFTXL` | +| `MESSAGE_TRANSMITTER_STELLAR_MAINNET` | `CACMENFFJPJMSDAJQLX4R7K3SFZIW2LJSE3R2UMLGSWHFHS353FVXAZV` | +| `CCTP_FORWARDER_STELLAR_MAINNET` | `CBZL2IH7F6BIDAA3WBNXYKIXSATJGMSW7K5P5MJ6STX5RXN47TZJDF5T` | +| `TOKEN_MESSENGER_MINTER_STELLAR_TESTNET` | `CDNG7HXAPBWICI2E3AUBP3YZWZELJLYSB6F5CC7WLDTLTHVM74SLRTHP` | +| `MESSAGE_TRANSMITTER_STELLAR_TESTNET` | `CBJ6MTCKKZG73PMDZCJMSFRD7DQEMI4FKDH7CGDSV4W6FHCRBCQAVVJY` | +| `CCTP_FORWARDER_STELLAR_TESTNET` | `CA66Q2WFBND6V4UEB7RD4SAXSVIWMD6RA4X3U32ELVFGXV5PJK4T4VSZ` | +| `USDC_ISSUER_STELLAR_MAINNET` | `GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN` | +| `USDC_ISSUER_STELLAR_TESTNET` | `GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5` | +| `STELLAR_NETWORK_PASSPHRASE_MAINNET` | `"Public Global Stellar Network ; September 2015"` | +| `STELLAR_NETWORK_PASSPHRASE_TESTNET` | `"Test SDF Network ; September 2015"` | +| `TOKEN_MESSENGER_MINTER_V2_STARKNET_MAINNET` | `0x07d421B9cA8aA32DF259965cDA8ACb93F7599F69209A41872AE84638B2A20F2a` | +| `MESSAGE_TRANSMITTER_V2_STARKNET_MAINNET` | `0x02EBB5777B6dD8B26ea11D68Fdf1D2c85cD2099335328Be845a28c77A8AEf183` | +| `USDC_STARKNET_MAINNET` | `0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb` | +| `TOKEN_MESSENGER_MINTER_V2_STARKNET_SEPOLIA` | `0x04bDdE1E09a4B09a2F95d893D94a967b7717eB85A3f6dEcA8c080Ee01fBc3370` | +| `MESSAGE_TRANSMITTER_V2_STARKNET_SEPOLIA` | `0x04db7926C64f1f32a840F3Fa95cB551f3801a3600Bae87aF87807A54DCE12Fe8` | +| `USDC_STARKNET_SEPOLIA` | `0x0512feAc6339Ff7889822cb5aA2a86C848e9D392bB0E3E237C008674feeD8343` | +| `STARKNET_CHAIN_ID_MAINNET` | `0x534e5f4d41494e` (`SN_MAIN`) | +| `STARKNET_CHAIN_ID_SEPOLIA` | `0x534e5f5345504f4c4941` (`SN_SEPOLIA`) | +| `SOLANA_CCTP_DOMAIN` | `5` | +| `STARKNET_CCTP_DOMAIN` | `25` | +| `STELLAR_CCTP_DOMAIN` | `27` | +| `CCTP_USDC_DECIMALS` | `6`, the precision of every CCTP message | +| `STELLAR_USDC_DECIMALS` | `7`, the precision of USDC on Stellar | diff --git a/reference/cctp/fees.mdx b/reference/cctp/fees.mdx new file mode 100644 index 0000000..ec84f5d --- /dev/null +++ b/reference/cctp/fees.mdx @@ -0,0 +1,224 @@ +--- +title: Fees +description: Fetch CCTP V2 fee tiers from Iris and compute the protocol fee, forwarder fee and maxFee for a burn, in USDC subunits. +--- + +A CCTP V2 burn pays two fees out of the burned amount: Circle's protocol fee, a rate on the amount, and, when Circle's relayer mints, a flat forwarder fee. The burn caps both with `maxFee`. + +```ts +import { + Base, + Ethereum, + getBurnFees, + pickFeeTier, + pickForwarderFee, + computeMaxFee, +} from "@usewhisk/cctp"; + +const tiers = await getBurnFees( + "mainnet", + Base.cctpDomain, + Ethereum.cctpDomain, +); +const fast = pickFeeTier(tiers, "fast"); + +console.log( + fast.finalityThreshold, + fast.minimumFee, + pickForwarderFee(fast, "high"), +); + +const { burnFee, forwarderFee, maxFee } = computeMaxFee({ + amount: 250_000_000n, + tier: fast, + forwarderLevel: "med", + burnFeeBufferBps: 1_000, +}); +console.log(burnFee, forwarderFee, maxFee); +``` + +Circle deducts the fees it actually executes, which can be less than `maxFee`. The recipient gets at least `amount - maxFee`. For how Whisk's engine turns this into a quote the payer sees, and who bears the fee, see [quotes and fees](/concepts/quotes-and-fees). + +## Units + +| Value | Unit | Example | +| -------------------------------------------------- | ------------------------------------- | ------------------------------------------- | +| Amounts, `burnFee`, `forwarderFee`, `maxFee` | USDC subunits, 6 decimals, `bigint` | `250_000_000n` is 250 USDC | +| `BurnFeeTier.minimumFee` | Hundredths of a basis point, `bigint` | Iris's `1.3` bps is `130n`, which is 0.013% | +| Buffers (`burnFeeBufferBps`, `forwarderBufferBps`) | Whole basis points, `number` | `1_000` is 10% | + +Every step rounds up, because a `maxFee` one subunit short of the Fast fee turns a Fast transfer into a Standard one. + +## Finality thresholds + +| Export | Value | | +| ------------------- | ------ | ----------------------------------------------------------------- | +| `FINALITY_FAST` | `1000` | Attested after a block or two, before hard finality. Costs a fee. | +| `FINALITY_STANDARD` | `2000` | Attested after hard finality. Cheaper than Fast. | + +`FinalityThreshold` is `1000 | 2000`. `TransferSpeed` is `"fast" | "standard"`, the name the helpers take. + +## `getBurnFees` + +`getBurnFees(network, sourceDomain, destinationDomain, options?): Promise` + +Reads `GET /v2/burn/USDC/fees/{src}/{dst}` from Iris, with `?forward=true` unless you turn it off. Returns one `BurnFeeTier` per finality Iris offers on the route; rows for other thresholds are dropped. + + + The source chain's `network`. + ++ The source chain's `cctpDomain`. + ++ The destination chain's `cctpDomain`. + ++ Defaults to `true`. Set `false` when the burn will not use Circle's forwarder, + for example to Stellar, Starknet or any chain whose `forwardingDestination` is + false. + + +`GetBurnFeesOptions` also takes the Iris [request options](/reference/cctp/iris#request-options) (`timeoutMs`, `maxRetries`, `baseDelayMs`, `signal`, `fetch`, `limiter`). + +### `BurnFeeTier` + ++ Which speed this row prices. + ++ The protocol fee rate, in hundredths of a basis point. + ++ Present when fetched with `includeForwarderFee`. `{ low, med, high }`, each + a flat fee in USDC subunits. Circle recommends `med` or higher; `high` + already carries a buffer. + + +## `pickFeeTier` + +`pickFeeTier(tiers: readonly BurnFeeTier[], speed: TransferSpeed): BurnFeeTier` + +The row for `"fast"` or `"standard"`. Throws `ProtocolError("tier_not_found")` when Iris returned none for that speed on this route. Check the source's `capabilities.fastSource` before offering Fast. + +## `pickForwarderFee` + +`pickForwarderFee(tier: BurnFeeTier, level?: "low" | "med" | "high"): bigint` + +The forwarder fee at `level` (default `"med"`), in USDC subunits. Throws `ProtocolError("fee_unavailable")` if the tier was fetched without forwarder fees. `selectForwarderFee` is the same function under its fee-maths name. + +## `computeMaxFee` + +`computeMaxFee(input: ComputeMaxFeeInput): ComputeMaxFeeResult` + +```text +burnFee = max(ceil(amount × minimumFee / 1,000,000), minBurnFee) +forwarderFee = ceil(forwardFee[level] × (10,000 + forwarderBufferBps) / 10,000) +maxFee = ceil(burnFee × (10,000 + burnFeeBufferBps) / 10,000) + forwarderFee +``` + +`buildBurnIntent` calls this for you unless you pass `fee.maxFee`. + ++ The burn amount in USDC subunits. + ++ From `pickFeeTier`. + ++ Defaults to `"med"`. + ++ Defaults to `true`. Set `false` for a burn without the forwarder; then + `forwarderFee` is `0n` and the tier needs no `forwardFee`. + ++ Whole basis points added to the forwarder fee, 0 to 10,000. Defaults to `0`. + ++ Whole basis points added to the protocol fee inside `maxFee` only. Circle + takes the fee it executes, so this raises the ceiling, not the charge. + Defaults to `0`. Whisk's engine uses `1_000` (10%) on Fast burns, so a rate + change between quote and burn does not drop the transfer to Standard. + ++ The on-chain minimum from [`getStandardMinFee`](#getstandardminfee), in USDC + subunits. The protocol fee is raised to it if lower. Defaults to `0n`. + + +Returns `{ burnFee, forwarderFee, maxFee }`, all `bigint` subunits. `burnFee` is before any buffer; `forwarderFee` includes its buffer. A negative amount or buffer throws `InvalidInputError`. + +## `getStandardMinFee` + +`getStandardMinFee(chain: EvmChain, amount: bigint, options?: GetStandardMinFeeOptions): Promise` + +On chains with `capabilities.standardFeeSwitch`, `TokenMessengerV2.getMinFeeAmount(amount)` sets the least `maxFee` a Standard burn may carry, which can be more than Iris quotes. This reads it over JSON-RPC, in USDC subunits. Pass it to `computeMaxFee` as `minBurnFee`. On other chains the contract call reverts, so the function throws `InvalidInputError("invalid_chain")` without calling. `GetStandardMinFeeOptions` is `RpcOptions` (`rpcUrls`, `fetch`). + +```ts +import { + Monad, + Ethereum, + getBurnFees, + pickFeeTier, + getStandardMinFee, + computeMaxFee, + buildBurnIntent, +} from "@usewhisk/cctp"; + +const amount = 1_000_000_000n; +const tier = pickFeeTier( + await getBurnFees("mainnet", Monad.cctpDomain, Ethereum.cctpDomain), + "standard", +); + +const minBurnFee = Monad.capabilities.standardFeeSwitch + ? await getStandardMinFee(Monad, amount) + : 0n; + +const fees = computeMaxFee({ amount, tier, minBurnFee }); + +const intent = buildBurnIntent({ + source: Monad, + destination: Ethereum, + amount, + mintRecipient: "0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e", + fee: { tier, maxFee: fees.maxFee }, +}); +``` + +## Lower level helpers + +```ts +import { + computeBurnFee, + parseFeeBps, + parseForwarderFee, + selectForwarderFee, + FINALITY_FAST, + type BurnFeeTier, +} from "@usewhisk/cctp"; + +const tier: BurnFeeTier = { + finalityThreshold: FINALITY_FAST, + minimumFee: parseFeeBps(1.3), + forwardFee: { + low: parseForwarderFee(150_000), + med: parseForwarderFee(200_000), + high: parseForwarderFee(300_000), + }, +}; + +console.log(computeBurnFee(25_000_000n, tier.minimumFee)); +console.log(selectForwarderFee(tier, "med")); +``` + +| Function | | +| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `computeBurnFee(amount, feeCentiBps)` | `ceil(amount × feeCentiBps / 1,000,000)`. 25 USDC at 1.3 bps is `3250n` (0.00325 USDC). | +| `parseFeeBps(raw)` | An Iris `minimumFee` (number or string) to hundredths of a basis point, rounded up. Exponent forms throw `IrisParseError`. | +| `parseForwarderFee(raw)` | An Iris forwarder fee to a `bigint` of subunits, rounded up. | +| `selectForwarderFee(tier, level?)` | Same as `pickForwarderFee`. | + +## Upfront fees + +On chains with `capabilities.upfrontFeeSource`, the Fast and forwarding fees can instead be paid on top of the amount from a signed Iris quote, so the recipient gets the whole amount. See [`getSignedBurnQuote`](/reference/cctp/iris#signed-upfront-fee-quotes) and [`buildBurnWithFeesIntent`](/reference/cctp/builders#buildburnwithfeesintent). diff --git a/reference/cctp/iris.mdx b/reference/cctp/iris.mdx new file mode 100644 index 0000000..6cc6d97 --- /dev/null +++ b/reference/cctp/iris.mdx @@ -0,0 +1,370 @@ +--- +title: Iris client +description: Read attestations and forwarder state from Circle's Iris API, poll within its rate limit, reattest, and fetch quotes and the Fast allowance. +--- + +Iris is Circle's attestation service. After a burn lands, Iris publishes the message, Circle's signature over it, and, for forwarded burns, the state of Circle's relayer. This client reads it with timeouts, retries and a shared rate limiter. + +```ts +import { BaseSepolia, getMessages } from "@usewhisk/cctp"; + +const [msg] = await getMessages( + { sourceDomain: BaseSepolia.cctpDomain, transactionHash: "0x9c1e...burn" }, + { network: "testnet" }, +); +console.log(msg?.status, msg?.forwardState, msg?.forwardTxHash); +``` + +The client is also published on its own as `@usewhisk/cctp/iris`. No API key is needed. + +## Hosts + +| Export | Value | +| ---------------------- | ------------------------------------------------------------- | +| `IRIS_MAINNET_URL` | `https://iris-api.circle.com` | +| `IRIS_SANDBOX_URL` | `https://iris-api-sandbox.circle.com` | +| `irisBaseUrl(network)` | The mainnet URL for `"mainnet"`, the sandbox for `"testnet"`. | + +Every function takes the `network` of the source chain. A testnet burn asked on the mainnet host returns nothing, because mainnet and testnet share domain numbers. + +## `getMessages` + +`getMessages(query: GetMessagesQuery, options: GetMessagesOptions): Promise ` + +One request to `GET /v2/messages/{sourceDomain}`. Returns an empty array while Iris does not know the burn yet, whether it answers with no messages or a 404. + + + The domain of the chain the burn happened on. + ++ The burn transaction hash (a signature on Solana). Pass this or `nonce`. + ++ The message nonce. Use it after a [reattest](#reattest). + ++ Picks the Iris host. + ++ Use another host, such as your own proxy in front of Iris. Defaults to + `irisBaseUrl(network)`. A trailing slash is ignored. + + +`GetMessagesOptions` also takes every [request option](#request-options). + +### `IrisMessage` + ++ The raw CCTP message. Pass it to a mint builder, or read it with + [`decodeBurnMessage`](/reference/cctp/builders#decoding-a-message). + ++ Circle's signature over the message. Only usable once `status` is + `"complete"`. + ++ `IrisAttestationStatus`. Iris never reports a failed attestation; a slow one + stays pending. + ++ The nonce as a decimal string. + ++ Always `2`. + ++ `ForwardState`, present only when the burn carried the forwarder hook. + `PENDING`: Circle's relayer is working. `CONFIRMED`: it submitted the mint and + is waiting for finality. `COMPLETE`: the mint is final. `FAILED`: the relayer + gave up, and the USDC is waiting for someone to mint it with the attestation. + ++ The destination mint transaction, once the relayer submitted it. + ++ `IrisDelayReason`: why the message is slower than asked, for example a Fast + burn whose `maxFee` did not cover the Fast fee. None of these is a failure. + ++ Optional. Iris's own decoding of the message and burn body, with amounts as + decimal strings. Prefer `decodeBurnMessage` on `message` when you need checked + values. + + +`IrisMessagesResponse` is the raw `{ messages: IrisMessage[] }` body. + +## `pollMessages` + +`pollMessages(query: GetMessagesQuery, options: PollMessageOptions): Promise` + +Calls `getMessages` until `isDone` holds or the time runs out. On timeout it returns the latest message it saw, or `null` if Iris never had one. Iris errors other than a rate limit are thrown; a slow attestation only times out. + +```ts +import { + BaseSepolia, + attestationSeconds, + pollBudget, + pollMessages, + isForwardDone, +} from "@usewhisk/cctp"; + +const controller = new AbortController(); + +const msg = await pollMessages( + { sourceDomain: BaseSepolia.cctpDomain, transactionHash: burnTxHash }, + { + network: "testnet", + ...pollBudget(attestationSeconds(BaseSepolia, "fast")), + isDone: (m) => m.status === "complete", + onRateLimited: (retryAt) => + console.warn("Iris rate limit, resuming at", new Date(retryAt)), + signal: controller.signal, + }, +); + +if (msg === null) { + console.log("Iris has not seen the burn yet"); +} else if (isForwardDone(msg)) { + console.log("Minted by Circle in", msg.forwardTxHash); +} +``` + + + Picks the Iris host. + ++ Another Iris host or proxy. + ++ Time between requests. Defaults to `3000`. + ++ Total time to poll. Defaults to 15 minutes. Here it is the whole poll, not the + per-request timeout. + ++ When to stop. By default: for a forwarded burn, once `isForwardDone` holds or + `forwardState` is `"FAILED"`; otherwise once `status` is `"complete"`. + ++ Called when a 429 makes the poll stand down, with the resume time in + milliseconds since the epoch. The wait does not count against `timeoutMs`. + ++ Your own `fetch`, for a proxy, test stub or custom agent. + ++ The rate limiter to share. Defaults to `defaultIrisLimiter`. + ++ Stops the poll with `IrisAbortedError`. + + +`maxRetries` and `baseDelayMs` from the [request options](#request-options) apply to each request. The per-request `timeoutMs` cannot be set through `pollMessages`, because `timeoutMs` there means the whole poll; each request uses the 5 second default. + +### `pollBudget` + +`pollBudget(eta: SecondsRange): { intervalMs: number; timeoutMs: number }` + +Sizes a poll for a route whose attestation takes `eta` seconds, usually from [`attestationSeconds`](/reference/cctp/chains#attestation-times). Fast routes poll often so the payer hears at once; slow ones poll gently so they do not use up the shared rate limit. + +| `eta.max` | `intervalMs` | +| ------------ | ------------ | +| 60 s or less | 2,000 | +| up to 30 min | 10,000 | +| longer | 30,000 | + +`timeoutMs` is twice `eta.max` plus five minutes. A Base Fast transfer (`{ min: 8, max: 8 }`) gets `{ intervalMs: 2000, timeoutMs: 316000 }`. + +### `isForwardDone` + +`isForwardDone(message: IrisMessage): boolean` + +`true` when Circle's relayer has minted: `forwardState` is `"CONFIRMED"` or `"COMPLETE"` and `forwardTxHash` is set. A `PENDING` state can carry a hash that was never mined, so it does not count. + +### Custom host, fetch and limiter + +```ts +import { pollMessages, createIrisLimiter } from "@usewhisk/cctp"; + +const limiter = createIrisLimiter({ ratePerSecond: 10 }); + +await pollMessages( + { sourceDomain: 6, nonce: "0x5e1f...nonce" }, + { + network: "mainnet", + baseUrl: "https://iris-proxy.example.com", + fetch: (input, init) => fetch(input, { ...init, keepalive: true }), + limiter, + timeoutMs: 60_000, + }, +); +``` + +`baseUrl` is honored by `getMessages` and `pollMessages` only. The fee, quote, allowance and reattest calls always use `irisBaseUrl(network)`; give them a custom `fetch` if they need to go through a proxy. + +## `reattest` + +`reattest(nonce: string, options: ReattestOptions): Promise<{ nonce: string } | null>` + +`POST /v2/reattest/{nonce}` asks Circle to sign a message again, for one that expired before anyone minted it or a Fast message you want re-signed at finality. Circle only acknowledges the request; read the new attestation from `getMessages` by nonce. Returns `null` when Iris has no such nonce. + +```ts +import { BaseSepolia, reattest, pollMessages } from "@usewhisk/cctp"; + +const ack = await reattest(nonce, { network: "testnet" }); +if (ack) { + const fresh = await pollMessages( + { sourceDomain: BaseSepolia.cctpDomain, nonce }, + { network: "testnet", isDone: (m) => m.status === "complete" }, + ); + console.log(fresh?.attestation); +} +``` + +`ReattestOptions` is `{ network }` plus the [request options](#request-options). + +## Fees and quotes + +`getBurnFees(network, sourceDomain, destinationDomain, options?)` reads `GET /v2/burn/USDC/fees/{src}/{dst}`. It and `pickFeeTier`, `pickForwarderFee`, `FINALITY_FAST` and `FINALITY_STANDARD` are on the [fees page](/reference/cctp/fees). + +### Signed upfront-fee quotes + +`getSignedBurnQuote(network, sourceDomain, destinationDomain, request, options?): Promise` + +`POST /v2/quote/burn/usdc/{src}/{dst}`. Circle's signed price for paying the Fast fee, the forwarding fee, or both on the source chain, on top of the amount. Only chains with `capabilities.upfrontFeeSource` accept it. Pass the result to [`buildBurnWithFeesIntent`](/reference/cctp/builders#buildburnwithfeesintent). + +`SignedBurnQuoteRequest`: + +| Field | Type | | +| ---------- | --------------------------- | ------------------------------------------------------------------------ | +| `amount` | `bigint` | The burn amount, 6-decimal subunits. The quote is bound to it. | +| `feeToken` | `Address` | The source chain's USDC. | +| `requests` | `readonly UpfrontFeeType[]` | `"PRE_FINALITY"` (the Fast fee) and/or `"FORWARD"` (the forwarding fee). | + +`SignedBurnQuote`: + +| Field | Type | | +| ---------------- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `signedQuote` | `` `0x${string}` `` | Submitted as is to `TokenMessengerWithFees`. | +| `feeTotalAmount` | `bigint` | Total fee in 6-decimal subunits. The payer pays `amount + feeTotalAmount`. | +| `feeToken` | `Address` | The USDC address. | +| `items` | `{ type: UpfrontFeeType; amount: bigint }[]` | One line per requested fee. They add up to `feeTotalAmount`. | +| `issuedAt` | `number` | Circle's clock, Unix seconds. | +| `expiry` | `SignedQuoteExpiry` | `{ mode: "TIMESTAMP"; expiresAt: number }` (Unix seconds) or `{ mode: "BLOCK_NUMBER"; expiresAtBlock: bigint }`. | +| `burnAmount` | `bigint` | Optional; echoed by Circle when present. | + +The client checks the reply before returning it: a quote for another amount, another fee token, a different set of fees, or items that do not add up throws `IrisParseError`. An expired quote reverts on chain, so ask for a fresh one right before the payer signs. + +### Fast Transfer allowance + +`getFastBurnAllowance(network, options?): Promise ` + +`GET /v2/fastBurn/USDC/allowance`: how much Fast Transfer volume Circle can still back right now, in 6-decimal subunits, rounded down. A Fast burn that does not fit shows `delayReason: "insufficient_allowance_available"` on its message until it is attested. + +```ts +import { + getFastBurnAllowance, + irisBaseUrl, + IRIS_MAINNET_URL, + IRIS_SANDBOX_URL, + fetchIrisJson, +} from "@usewhisk/cctp"; + +const allowance = await getFastBurnAllowance("mainnet"); +console.log(`${allowance / 1_000_000n} USDC of Fast Transfer allowance left`); + +console.log(irisBaseUrl("testnet") === IRIS_SANDBOX_URL, IRIS_MAINNET_URL); + +const raw = await fetchIrisJson ( + `${irisBaseUrl("mainnet")}/v2/publicKeys`, + { timeoutMs: 10_000, maxRetries: 1 }, +); +``` + +## Request options + +Every Iris call goes through `fetchIrisJson (url, options?)`, which you can also call for endpoints the client does not wrap. It returns the parsed JSON body unchecked, so validate it before use. `FetchJsonOptions`: + +| Option | Default | | +| ------------- | -------------------- | ----------------------------------------------------------- | +| `timeoutMs` | `5000` | Per request, in ms. | +| `maxRetries` | `3` | Retries after the first attempt. | +| `baseDelayMs` | `300` | Delay before retry `n` is `baseDelayMs * n`. | +| `signal` | | Aborts the request and all retries with `IrisAbortedError`. | +| `fetch` | global `fetch` | | +| `limiter` | `defaultIrisLimiter` | | + +Server errors (5xx), network failures and timeouts are retried. Other 4xx responses, unparseable JSON and 429s are not. + +## Rate limiting + +Circle allows 35 requests a second per IP and blocks the IP for five minutes after a 429. The client keeps a token bucket per host and, after a 429, refuses every request to that host until the block ends instead of extending it. + +`defaultIrisLimiter` is one limiter shared by every Iris call in the process, because Circle counts per IP, not per caller. Make your own with `createIrisLimiter(options?)` only when you need different numbers, and share it across all your calls. + +`IrisLimiterOptions`: + +| Option | Default | | +| --------------- | ------------ | --------------------------------- | +| `ratePerSecond` | `30` | Below Circle's 35, to leave room. | +| `standDownMs` | `300000` | How long to stop after a 429. | +| `now` | `Date.now` | Clock, for tests. | +| `sleep` | `setTimeout` | Wait, for tests. | + +An `IrisLimiter` has `acquire(host)` (waits for a slot, or throws `IrisRateLimitedError` while standing down), `standDown(host)` (records a 429 and returns the resume time), `now()` and `sleep(ms)`. + +If many servers share one outbound IP, they share Circle's limit too. Put a cache or a single poller in front of Iris rather than raising `ratePerSecond`. + +## Errors + +```ts +import { + getMessages, + IrisError, + IrisHttpError, + IrisRateLimitedError, + IrisNetworkError, + IrisParseError, + IrisAbortedError, +} from "@usewhisk/cctp"; + +try { + await getMessages( + { sourceDomain: 0, transactionHash: "0xabc" }, + { network: "mainnet", signal: AbortSignal.timeout(20_000) }, + ); +} catch (err) { + if (err instanceof IrisRateLimitedError) { + console.log(err.host, new Date(err.retryAt)); + } else if (err instanceof IrisHttpError) { + console.log(err.status, err.url, err.bodySnippet); + } else if ( + err instanceof IrisNetworkError || + err instanceof IrisParseError || + err instanceof IrisAbortedError + ) { + console.log(err.code, err.cause); + } else if (err instanceof IrisError) { + console.log(err.code); + } +} +``` + +All extend `IrisError`, which extends `CctpError`. + +| Class | Code | When | +| ---------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `IrisHttpError` | `iris_http` | A 4xx other than 429, or a 5xx after the retries. Carries `status`, `url` and `bodySnippet`. | +| `IrisRateLimitedError` | `iris_rate_limited` | Iris answered 429, or the limiter is still standing down. `retryAt` (ms since the epoch) and `host`. `pollMessages` waits these out itself. | +| `IrisNetworkError` | `iris_network` | The network failed or timed out on every attempt. `cause` holds the last error. | +| `IrisParseError` | `iris_parse` | The body was not JSON, or not the shape expected. | +| `IrisAbortedError` | `iris_aborted` | Your `AbortSignal` fired. | + +An error from Iris says nothing about the payer's money. The burn is on chain either way; retry later, or find the message by transaction hash from another machine. diff --git a/reference/cctp/overview.mdx b/reference/cctp/overview.mdx new file mode 100644 index 0000000..7ca1989 --- /dev/null +++ b/reference/cctp/overview.mdx @@ -0,0 +1,171 @@ +--- +title: "@usewhisk/cctp" +description: The CCTP V2 protocol layer under Whisk, usable on its own to build burns, poll Iris and build recovery mints. +--- + +`@usewhisk/cctp` builds the calldata for Circle's CCTP V2 contracts and talks to Circle's Iris attestation API. It never signs or sends a transaction. This is a Fast Transfer from Base Sepolia to Arbitrum Sepolia, end to end: + +```ts transfer.ts +import { + BaseSepolia, + ArbitrumSepolia, + getBurnFees, + pickFeeTier, + buildBurnIntent, + pollMessages, + buildMintIntent, +} from "@usewhisk/cctp"; + +const tiers = await getBurnFees( + "testnet", + BaseSepolia.cctpDomain, + ArbitrumSepolia.cctpDomain, +); + +const intent = buildBurnIntent({ + source: BaseSepolia, + destination: ArbitrumSepolia, + amount: 25_000_000n, // 25 USDC in 6-decimal subunits + mintRecipient: "0x4f2a1c7e9b3d5a8f6e0c2b4d7a9f1e3c5b8d0a2e", + fee: { tier: pickFeeTier(tiers, "fast") }, +}); + +// Sign and send intent.calls in order with your own wallet: approve, then burn. +for (const call of intent.calls) { + console.log(call.to, call.data); +} + +const msg = await pollMessages( + { sourceDomain: BaseSepolia.cctpDomain, transactionHash: burnTxHash }, + { network: "testnet" }, +); + +if (msg?.forwardState === "FAILED") { + const mint = buildMintIntent({ + destination: ArbitrumSepolia, + message: msg.message, + attestation: msg.attestation, + }); + // Send mint.call on Arbitrum Sepolia. The sender pays the gas. +} +``` + +The burn takes the payer's USDC on the source chain as soon as the second call lands. By default the burn carries Circle's forwarding hook, so Circle's relayer submits the mint on the destination and takes its fee out of the minted amount. You only build a mint yourself when the forwarder fails or you burned without it. + +## Who uses it directly + +Most apps never import this package. `@usewhisk/core` depends on it and `@usewhisk/react` sits on top of core, and both re-export the chain registry. Reach for `@usewhisk/cctp` directly when: + +- You are writing your own CCTP V2 integration and want tested calldata builders and an Iris client, without Whisk's engine, wallet adapters or transfer state. +- You run a backend that watches burns, checks Iris, or mints for stuck transfers. +- You need a lower level piece the engine does not expose, such as the raw fee tiers, a decoded CCTP message or a Solana PDA. + +If you want quotes, approvals, sending, receipts and recovery handled for you, use the engine instead: see [the core engine](/headless/core-engine). + +## Where it sits + +Imports only point down: + +```text +@usewhisk/cctp chain registry, ABIs, Iris client, fee maths, burn and mint builders + ↑ +@usewhisk/core engine: quotes, wallet adapters, transfer state, recovery + ↑ +@usewhisk/react provider, hooks, widget +``` + +The package holds no wallet state and no signer. Every builder returns plain data: EVM `{ to, data, value }` calls, a Solana instruction, a Soroban invocation or a Starknet `Call`. Whoever holds the key submits it. The only network calls are to Iris and, for the few RPC helpers, to the chain's JSON-RPC endpoints. + +## Install + +```bash +pnpm add @usewhisk/cctp +``` + +`viem`, `@solana/web3.js`, `@solana/spl-token`, `@stellar/stellar-sdk` and `starknet` are direct dependencies, so the builders work without extra installs. Node 20 or later. The package ships ESM and CommonJS builds. + +Three subpath entries load less code when you only need one part: + +```ts +import { getChain, Base } from "@usewhisk/cctp/chains"; +import { tokenMessengerV2Abi, usdcAbi } from "@usewhisk/cctp/abi"; +import { getMessages } from "@usewhisk/cctp/iris"; +``` + +`VERSION` is a version string. The published 0.1.1 still sets it to `"0.1.0"`, so read `package.json` when you need the installed version exactly. + +## Main entry points + +| Area | Exports | Page | +| -------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | +| Chain registry | `CHAINS`, `getChain`, `chainByDomain`, `chainByEvmChainId`, one constant per chain | [Chains](/reference/cctp/chains) | +| Burns | `buildBurnIntent`, `buildBurnWithFeesIntent`, `buildSolanaBurnIntent`, `buildStellarBurnIntent`, `buildStarknetBurnIntent` | [Builders](/reference/cctp/builders) | +| Mints | `buildMintIntent`, `buildSolanaReceiveIntent`, `buildStellarMintIntent`, `buildStarknetReceiveIntent` | [Builders](/reference/cctp/builders) | +| Iris | `getMessages`, `pollMessages`, `reattest`, `getSignedBurnQuote`, `getFastBurnAllowance` | [Iris](/reference/cctp/iris) | +| Fees | `getBurnFees`, `pickFeeTier`, `computeMaxFee`, `getStandardMinFee` | [Fees](/reference/cctp/fees) | + +## Units + +- EVM, Solana and Starknet USDC amounts are `bigint` subunits with 6 decimals: `25_000_000n` is 25 USDC. +- Stellar's USDC has 7 decimals. The Stellar builders take 7-decimal subunits; CCTP messages always carry 6. See [Stellar precision](/reference/cctp/builders#stellar-precision). +- Iris's protocol fee comes back in basis points with up to two decimals. The package holds it as hundredths of a basis point, so `1.3` bps is `130n`. See [Fees](/reference/cctp/fees). +- Native gas is not USDC, except on Arc, where it is USDC with 18 decimals. Nothing in this package pays gas. + +Network (mainnet or testnet) is a property of each chain entry. Functions that call Iris take a `network` argument; pass `source.network` so a testnet burn never asks the mainnet host. + +## ABIs + +`tokenMessengerV2Abi`, `tokenMessengerWithFeesAbi`, `messageTransmitterV2Abi` and `usdcAbi` are `as const` arrays, typed for viem. They cover what Whisk calls and decodes: + +| ABI | Functions | Events | +| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------- | +| `tokenMessengerV2Abi` | `depositForBurn`, `depositForBurnWithHook` | `DepositForBurn` | +| `tokenMessengerWithFeesAbi` | `depositForBurnWithFees`, `getFee`, `tokenMessenger` | | +| `messageTransmitterV2Abi` | `receiveMessage`, `usedNonces` | `MessageSent`, `MessageReceived` | +| `usdcAbi` | `balanceOf`, `allowance`, `decimals`, `approve`, `transfer`, `nonces`, `DOMAIN_SEPARATOR`, `permit` | `Transfer`, `Approval` | + +## Errors + +Every failure the package raises is a `CctpError` with a stable `code` (type `CctpErrorCode`). Switch on the subclass or on `code`, not on `message`. + +```ts +import { + buildBurnIntent, + InvalidInputError, + IrisRateLimitedError, + ProtocolError, + isCctpError, +} from "@usewhisk/cctp"; + +try { + buildBurnIntent(input); +} catch (err) { + if (err instanceof InvalidInputError) { + console.error("bad input", err.code, err.message); + } else if (err instanceof ProtocolError) { + console.error("route or amount refused", err.code); + } else if (err instanceof IrisRateLimitedError) { + console.error("Iris blocked until", new Date(err.retryAt)); + } else if (isCctpError(err)) { + console.error(err.code); + } else { + throw err; + } +} +``` + +| Class | Means | Codes | +| ------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `CctpError` | Base class. `code`, `message`, optional `cause`. | any | +| `InvalidInputError` | The caller passed bad data. Fix the calling code. | `invalid_address`, `invalid_bytes32`, `invalid_amount`, `invalid_chain`, `invalid_domain`, `invalid_input`, `no_route` | +| `ProtocolError` | A CCTP rule refused the call, or every RPC failed. | `amount_too_large`, `fee_unavailable`, `tier_not_found`, `no_route`, `rpc_unavailable` | +| `UnsupportedError` | The chain or ecosystem cannot serve this call. | `unsupported_chain`, `unsupported_ecosystem` | +| `IrisError` | Base for every Iris failure. | `iris_*` | + +`UnknownChainError` (from the registry), `InvalidAddressError` and `InvalidBytes32Error` (from the bytes32 helpers) extend `InvalidInputError`. The Iris subclasses (`IrisHttpError`, `IrisRateLimitedError`, `IrisNetworkError`, `IrisParseError`, `IrisAbortedError`) are covered on the [Iris page](/reference/cctp/iris#errors). `isCctpError(value)` is an `instanceof CctpError` type guard. + + + The Solana builder throws `amount_too_large` as an `InvalidInputError`, while + the EVM builder throws it as a `ProtocolError`. Match on `err.code` if you + handle both. + diff --git a/reference/core/create-whisk.mdx b/reference/core/create-whisk.mdx new file mode 100644 index 0000000..c531afe --- /dev/null +++ b/reference/core/create-whisk.mdx @@ -0,0 +1,154 @@ +--- +title: "createWhisk" +description: "Build a Whisk engine from a WhiskConfig, with every option, its type, default and effect." +--- + +`createWhisk` builds the framework-agnostic engine that quotes, sends, bridges and resumes USDC transfers. `` calls it for you; call it yourself in a non-React app or on a server. + +```ts engine.ts +import { createWhisk } from "@usewhisk/core"; + +export const engine = createWhisk({ + chains: ["Base_Sepolia", "Arc_Testnet"], +}); +``` + +```ts +function createWhisk(config: WhiskConfig): WhiskEngine; +``` + +It returns a [WhiskEngine](/reference/core/engine). Nothing touches the network until you call a method. The engine is stateless apart from its `inflightStore`, so one engine can serve many payers. + +It throws `ConfigError` when `chains` is missing or empty, and when `defaultMetadata` fails [validateMetadata](/reference/core/types#metadata). + +`engine.config` holds the config with two defaults filled in: `feeBearer` (`"sender"`) and `useForwarder` (`true`). + +## WhiskConfig + +```ts engine.ts +import { createWhisk, createStorageInflightStore } from "@usewhisk/core"; + +export const engine = createWhisk({ + chains: ["Base", "Arc", "Ethereum"], + feeBearer: "receiver", + feePolicy: { + value: "0.50", + recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + }, + defaultMetadata: { storeId: "eu-1" }, + rpcUrls: { + Base: ["https://base.example-rpc.com", "https://mainnet.base.org"], + Arc: "https://arc.example-rpc.com", + }, + useForwarder: true, + forwarderFeeLevel: "med", + inflightStore: createStorageInflightStore(window.localStorage), + fetch: (input, init) => fetch(input, init), +}); +``` + + + Chain ids such as `"Base"` or `"Arc_Testnet"`. Must not be empty. The engine + only checks that it is non-empty: `quote` and `send` accept any chain id in + the registry, whatever this list says. UIs use it to decide what to offer. See + [Chains](/chains). + + ++ Stored for UIs. The engine does not read it. + + ++ Stored for UIs. The engine does not read it. + + ++ Accepted but unused in 0.3. Quotes take their token from `QuoteParams.token`, + which defaults to `"USDC"`, and CCTP only moves USDC. Tracked in + [usewhisk/whisk#155](https://github.com/usewhisk/whisk/issues/155). + + ++ Used by `engine.resolve`. Defaults to `addressResolver`, which accepts raw + addresses in the destination chain's format. `@usewhisk/react` passes an + address-then-ENS resolver instead. See + [Resolver](/reference/core/types#resolvers). + + ++ A merchant fee charged to the payer on top of every transfer, split 90% to `recipient` and 10% to the Whisk treasury (`WHISK_TREASURY_ADDRESS`). `value` is a decimal USDC string; `recipient` must be an EVM address or `send` throws `ConfigError`. `bps` is ignored. The fee shows in `quote.fees.entries` as two `"custom"` entries and in `quote.amountIn`, whoever bears the bridge fees. + +On an EVM source, the fee goes out as one or two USDC `transfer` calls from the payer's wallet, never before the burn or the same-chain transfer: in one atomic EIP-5792 batch with it when the adapter's `supportsAtomicBatch` says yes, otherwise as separate requests once it has landed. A payer who rejects that later request still gets the transfer. `SendSuccess.customFee` and `SendFailure.customFee` report whether the fee was paid. Solana, Stellar and Starknet sources do not send the fee transfers in 0.3, though their quotes include the fee. See [when the fee is paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + + + ++ Who absorbs the CCTP protocol fee and the Forwarder fee on a bridge. Defaults to `"sender"` (`DEFAULT_FEE_BEARER`). + +- `"sender"`: the burn is grossed up by the fees so the recipient nets at least the requested amount. The payer is debited more than the amount. +- `"receiver"`: the burn is the requested amount and the recipient nets the amount less fees. `quote` throws `ConfigError` when the fees exceed the amount. + +The fee-paid-upfront mode (`quote.feeMode: "upfront"`) is only used with `"sender"`. Same-chain sends have no protocol fees. See [Quotes and fees](/concepts/quotes-and-fees). + + + ++ Correlation data merged into every `send` and `refund` result. Per-call + `metadata` wins on key conflicts. Flat object of `string | number | boolean`, + at most 1024 bytes as JSON, no keys starting with `__`. It travels through the + payer's browser, so keep personal data out. See [Metadata](/flows/metadata). + + ++ RPC endpoints tried in order before each chain's public defaults. Used for + `balance`, `maxSendable`, the pre-send balance check, Arc gas prices, the + Standard-transfer minimum fee read on chains that have one, and the source and + destination reads during `resume`. Wallet transactions go through the wallet, + not these. See [RPC](/rpc). + + ++ Lets Circle's Forwarding Service submit the destination mint. Defaults to + `true`. Circle forwards only burns from EVM or Solana into an EVM chain that + supports forwarding; every other route needs a destination wallet to sign the + mint whatever this says. With `false`, every bridge needs a wallet on the + destination (the source wallet covers EVM to EVM). + + ++ Which of Circle's forwarding fee levels to quote. Defaults to `"high"`, or + `"med"` when the destination is Ethereum, where `"high"` costs about 0.30 USDC + more. At send time the engine only refuses the quote if Circle's current + `"med"` fee no longer fits under the confirmed `maxFee`. Not exposed by the + React config yet + ([usewhisk/whisk#156](https://github.com/usewhisk/whisk/issues/156)). + + ++ Where bridges are recorded from before the burn until the mint, so `inflight` + and `resume` can find them after a reload. Defaults to + `createMemoryInflightStore()`, which lasts as long as the engine. In a + browser, pass `createStorageInflightStore(window.localStorage)`. See [Inflight + records](/reference/core/types#inflight-records). + + ++ Used for every Iris request and every RPC read the engine makes. Defaults to + the global `fetch`. Pass one to route Circle through a proxy or to stub it in + tests. Not exposed by the React config yet + ([usewhisk/whisk#156](https://github.com/usewhisk/whisk/issues/156)). + + ++ Stored on `engine.config`. Nothing in 0.3 reads it. + + +## Network + +There is no network option. Each transfer's network (mainnet or testnet) comes from its source chain id: `"Base"` is mainnet, `"Base_Sepolia"` is testnet. A bridge between a mainnet and a testnet chain throws `NetworkMismatchError`. + +## Related + +- [Engine](/reference/core/engine): the methods on the returned engine. +- [Headless core engine](/headless/core-engine): a walkthrough without React. +- [Server use](/headless/server): running the engine on a server. diff --git a/reference/core/engine.mdx b/reference/core/engine.mdx new file mode 100644 index 0000000..0b9a743 --- /dev/null +++ b/reference/core/engine.mdx @@ -0,0 +1,767 @@ +--- +title: "Engine" +description: "Every WhiskEngine method with its parameters, return type and the errors it throws, plus the wallet adapter interfaces." +--- + +`createWhisk` returns a `WhiskEngine`. Its methods take plain objects and wallet adapters, and never hold a wallet themselves. + +```ts send.ts +import { createWhisk, type EvmAdapter } from "@usewhisk/core"; + +declare const adapter: EvmAdapter; + +const engine = createWhisk({ chains: ["Base_Sepolia", "Arc_Testnet"] }); + +const recipient = await engine.resolve( + "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + "Arc_Testnet", +); +const quote = await engine.quote({ + sourceChain: "Base_Sepolia", + destinationChain: "Arc_Testnet", + recipient, + amount: "25", + adapter, +}); +const result = await engine.send({ quote, adapter }); +console.log(result.kind, result.steps); +``` + +```ts +interface WhiskEngine { + readonly config: WhiskConfig; + resolve(input: string, chain: Chain): Promise; + quote(params: QuoteParams): Promise ; + send(params: SendParams, listeners?: SendListeners): Promise; + balance(params: { chain: Chain; address: string }): Promise ; + maxSendable(params: Omit ): Promise ; + inflight(): Promise ; + dismiss(id: string): Promise ; + resume( + record: InflightRecord, + options?: ResumeOptions, + listeners?: SendListeners, + ): Promise ; + resumeFromTx( + params: ResumeFromTxParams, + listeners?: SendListeners, + ): Promise ; + refund( + params: RefundParams, + listeners?: SendListeners, + ): Promise ; +} +``` + +## Throwing versus returning a failure + +The rule that keeps money safe: **anything thrown happened before a signature**, apart from the `resume` cases listed below. Once the engine asks a wallet to sign, problems come back as a `SendResult` with `kind: "failure"`, its `steps` showing which step failed and whether the burn landed. + +| Outcome | Funds | What to do | +| ----------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------- | +| `send` throws | Nothing signed, nothing moved. | Fix the cause or quote again. | +| `kind: "failure"`, failed step `approve` or `transfer` | No burn, and no merchant fee taken. | Show the error; the payer can try again. | +| `kind: "failure"`, failed step `burn` | The burn may or may not have landed. Check `steps[n].txHash` and the inflight record. | Call `resume` or `resumeFromTx` if a hash exists. | +| `kind: "failure"`, failed step `fetchAttestation` or `mint` | Burned. USDC is in flight. | Call `resume` later. The record stays in the store. | + +The error codes are in [Errors](/reference/core/errors). + +## config + +```ts +readonly config: WhiskConfig; +``` + +The config passed to `createWhisk`, with `feeBearer` and `useForwarder` defaults filled in. + +## resolve + +```ts +resolve(input: string, chain: Chain): Promise ; +``` + +Turns what the payer typed into a recipient on `chain`, with the configured `resolver`. Input is trimmed first. + + + An address, or anything the resolver accepts (such as an ENS name with the + React default resolver). + + ++ The destination chain. Resolvers use it to pick the address format and, for + ENS, the coin type. + + +**Returns** a [ResolvedRecipient](/reference/core/types#recipients). + +**Throws** + +- `ConfigError` when no resolver matches the input, or the matching resolvers return `null`. +- `ResolverError` when a resolver inside `composeResolvers` throws, or an ENS lookup fails. + +## quote + +```ts +quote(params: QuoteParams): Promise; +``` + +Prices a transfer. A same-chain route returns at once with no network calls, except into Starknet, where the recipient's account is read first. A bridge plans the route, checks Circle's Fast allowance, and reads Circle's fees from Iris (and, for Standard burns on chains with a fee switch, the on-chain minimum fee). Every quote expires 60 seconds after `issuedAt`. + ++ Where the payer's USDC is. Its network decides mainnet or testnet. + + ++ Equal to `sourceChain` for a same-chain send. + + ++ From `resolve`, or built by hand as `{ address, chain }`. The address is checked against the destination's format: EVM hex address, Solana public key, Stellar strkey or Starknet felt. + + ++ Decimal USDC, such as `"1.50"`. Digits past the sixth decimal are dropped, + never rounded up. Must be positive. + + ++ The payer's wallet. Its `kind` must match the source chain's ecosystem when + you send. + + ++ The wallet that signs the mint when Circle does not forward it, for a route + into another ecosystem. The plan checks that every wallet the route needs is + present. + + ++ Label for the quote's `token` and fee entries. Defaults to `"USDC"`. Bridges + always move USDC. + + ++ Quote to a Starknet address with no account deployed yet. USDC sent there + waits for whoever deploys the account, so set it only once the payer has + confirmed the address is their own new wallet. Defaults to `false`. + + +Into Starknet, for a bridge or a same-chain send, `quote` refuses an address below `2**160` (almost always an Ethereum address) or at or past `2**251 - 256`, then reads `starknet_getClassHashAt` for it over the destination's `rpcUrls` and the registry's defaults. The connected Starknet wallet's own address, as `adapter` or `destinationAdapter`, skips that read. See [recipients](/concepts/recipients#starknet-felt-addresses). + +**Returns** a [Quote](/reference/core/types#quote). Show `amountIn` as "You pay" and `amountOut` as "Recipient gets". + +**Throws** + +- `InvalidAddressError` when the recipient address does not fit the destination chain, or a Starknet recipient is Ethereum-shaped or out of range. +- `ConfigError` when the amount is not a positive decimal, the chains are missing, or with `feeBearer: "receiver"` the fees exceed the amount. +- `NetworkMismatchError` when one chain is mainnet and the other testnet. +- On a bridge, `RouteUnavailableError` with `reason: "source_adapter_required"` when `adapter` is not a wallet of the source ecosystem, or `"destination_adapter_required"` when the mint needs a wallet you did not pass. +- Into Starknet, `RouteUnavailableError` with `reason: "recipient_not_deployed"` when no account is deployed at the recipient and `allowUndeployedRecipient` is not set, and a `WhiskError` wrapping the RPC error when the class hash cannot be read. +- Errors from `@usewhisk/cctp`, which are not `WhiskError`s: `IrisError` subclasses when Iris is unreachable, rate limited or returns something unexpected, `ProtocolError` when an RPC read fails or a fee tier is missing, `UnknownChainError` for an id outside the registry. Pass them through `toWhiskError` for a uniform shape. + +## send + +```ts +send(params: SendParams, listeners?: SendListeners): Promise; +``` + +Executes the quote the payer confirmed. Chains, recipient and amounts all come from `params.quote`; the engine burns exactly `quote.subunits.burnAmount` and never re-prices silently. Before anything is signed it: + +1. Validates `metadata`. +2. Refuses a quote past `expiresAt`. +3. On an EVM source, reads the payer's USDC and refuses when it cannot cover `quote.subunits.amountIn` plus, on Arc, the USDC gas reserve. +4. For a bridge, plans the route again and checks Circle's current fees still fit under the confirmed `maxFee`. For an upfront-fee quote it fetches Circle's signed fee quote and checks it the same way. + +Into Stellar and Starknet, the route then checks the destination wallet's network, and for a Stellar `G` or `M` recipient its USDC trustline, before the source wallet is asked for anything. A failed check comes back as a failure with nothing signed. See [fund safety](/concepts/fund-safety#checks-before-the-burn). + +With a `feePolicy` on an EVM source, the fee goes in one atomic batch with the burn or transfer when `adapter.supportsAtomicBatch` says yes for the source chain, and otherwise as separate requests once the burn or transfer has landed. See [when the fee is paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + +For a bridge, it writes an inflight record before the wallet is asked (`step: "signing"`), updates it the moment the burn hash comes back (`"burned"`), after attestation (`"attested"`) and after the mint (`"minted"`). A transfer that never burned leaves no record. + +```ts sendConfirmed.ts +import { + QuoteChangedError, + QuoteExpiredError, + type EvmAdapter, + type Quote, + type SendResult, + type WhiskEngine, +} from "@usewhisk/core"; + +declare const engine: WhiskEngine; +declare const adapter: EvmAdapter; +declare function confirmWithPayer(quote: Quote): Promise ; + +export async function sendConfirmed(quote: Quote): Promise { + try { + return await engine.send( + { quote, adapter, metadata: { orderId: "A-1001" } }, + { + onBurnSubmitted: (txHash) => console.log("burn sent", txHash), + onStep: (step) => console.log(step.name, step.state, step.txHash), + }, + ); + } catch (err) { + if (err instanceof QuoteChangedError) { + return (await confirmWithPayer(err.quote)) + ? sendConfirmed(err.quote) + : null; + } + if (err instanceof QuoteExpiredError) return null; + throw err; + } +} +``` + + + The quote the payer confirmed. Not older than 60 seconds. + + ++ The payer's wallet, of the source chain's ecosystem. + + ++ The wallet that signs the mint when Circle does not forward it. Required for + bridges into Solana, Stellar and Starknet, and from Stellar or Starknet into + EVM. + + ++ Correlation data, merged over `config.defaultMetadata` and echoed on the + result. See [Metadata](/flows/metadata). + + ++ Progress callbacks. + + + +**Returns** a [SendResult](/reference/core/types#sendresult): `{ kind: "success", finalTxHash?, steps, customFee?, metadata? }` or `{ kind: "failure", error, steps, raw?, customFee?, metadata? }`. For a forwarded bridge, `finalTxHash` is the forwarder's mint hash. `customFee` is set whenever a `feePolicy` fee applied; see [CustomFeeOutcome](/reference/core/types#sendresult). + +**Throws** (all before any signature) + +- `ConfigError` for invalid metadata, a `feePolicy.recipient` that is not an EVM address, an adapter whose `kind` does not match the chain, or a missing `destinationAdapter` on routes that require one. +- `QuoteExpiredError` when the quote is past `expiresAt`, or Circle's signed upfront fee expired twice in a row. +- `InsufficientBalanceError` when an EVM payer cannot cover the debit and Arc gas. +- `QuoteChangedError` when the route's speed or mint method changed, or Circle's fees rose past `maxFee`. `err.quote` is a fresh quote to show the payer. +- `NetworkMismatchError` and `RouteUnavailableError`, as for `quote`. +- `@usewhisk/cctp` errors from the Iris fee read or the balance read. + +## balance + +```ts +balance(params: { chain: Chain; address: string }): Promise+ ++ Called each time a step changes state. + ++ Called with the burn hash as soon as the wallet returns it, before any receipt wait. If you keep your own records, save the hash here: it is what `resumeFromTx` needs. + +; +``` + +The USDC balance of `address` on `chain`, in 6-decimal subunits. Returns `null` on Solana, Stellar and Starknet, where the engine does not read balances. + +**Throws** `ProtocolError` (from `@usewhisk/cctp`) when every RPC fails. + +## maxSendable + +```ts +maxSendable(params: Omit ): Promise ; +``` + +The largest amount the payer can send on this route: the balance, less the fees the payer covers and, on Arc, the gas paid from the same USDC. It quotes up to six times to converge. Returns `null` when `adapter` is not an EVM wallet. + +```ts max.ts +import type { EvmAdapter, WhiskEngine } from "@usewhisk/core"; + +declare const engine: WhiskEngine; +declare const adapter: EvmAdapter; + +const held = await engine.balance({ + chain: "Arc_Testnet", + address: adapter.address, +}); + +const max = await engine.maxSendable({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient: { address: adapter.address, chain: "Base_Sepolia" }, + adapter, +}); +console.log(held, max?.amount, max?.balance, max?.gasReserve); +``` + +Takes the `QuoteParams` fields except `amount`. Fees do not depend on the recipient, so the payer's own address can stand in before one is entered. The recipient checks `quote` runs are skipped here, so Max works for a bridge into Solana or Starknet before a recipient is entered. + + + Decimal USDC, ready for the amount field and `quote`. `"0"` when nothing fits. + + ++ The payer's USDC, in subunits. + + ++ USDC subunits kept back for gas. Non-zero only on Arc. + + +**Throws** what `quote` and `balance` throw. + +## inflight + +```ts +inflight(): Promise; +``` + +The bridges in the engine's `inflightStore`, oldest first. Includes `minted` records until you `dismiss` them. See [InflightRecord](/reference/core/types#inflight-records). + +**Throws** whatever the store throws. + +## dismiss + +```ts +dismiss(id: string): Promise ; +``` + +Removes a record from the store. Burned records are never removed automatically, so call this once the payer has seen the transfer finish or chose to drop it. Dismissing does not stop or undo a transfer. + +## resume + +```ts +resume(record: InflightRecord, options?: ResumeOptions, listeners?: SendListeners): Promise ; +``` + +Finishes a bridge from its record without signing the burn again. It checks the burn did not revert (EVM sources), waits for the attestation, checks the attested message matches the record's destination and amount, then: + +- For a forwarded record, waits for Circle's relayer. If the relayer reports `FAILED`, it mints with `destinationAdapter` instead. +- Otherwise checks whether the destination already received the message, and if not, mints with `destinationAdapter`. An expired attestation is re-attested and the mint tried once more. + +It updates the record as it goes. A reverted burn removes the record. + +```ts resumeAll.ts +import type { WhiskAdapter, WhiskEngine } from "@usewhisk/core"; + +declare const engine: WhiskEngine; +declare const destinationAdapter: WhiskAdapter | undefined; + +for (const record of await engine.inflight()) { + if (record.step === "minted") { + await engine.dismiss(record.id); + continue; + } + const result = await engine.resume(record, { destinationAdapter }); + if (result.kind === "failure" && result.error.retryable) { + console.log("try again later:", result.error.message); + } +} + +const fromLink = await engine.resumeFromTx({ + sourceChain: "Base_Sepolia", + txHash: "0x5f2c9a1e7b3d4c6f8a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f", + destinationAdapter, +}); +console.log(fromLink.kind); +``` + + + From `inflight()`, or your own copy of one. + + ++ Signs the mint when Circle does not, or when its relayer failed. Not needed + for a transfer Circle forwards. + + ++ `onStep` reports `burn`, `fetchAttestation` and `mint`. + + +**Returns** a `SendResult`. A failure here never means new money moved. When the record has a `customFee`, the result reports it from the record, and `resume` never asks for the fee again. Failures it returns: + +- `ConfigError` (step `burn`) when the record has no `sourceTxHash`: the wallet was asked but never returned a burn hash. Use `resumeFromTx` if the wallet shows one. +- `OnchainRevertError` (step `burn`) when the burn reverted. No USDC left the wallet. +- `BridgeStepError` (retryable) when Circle has not attested yet, or its relayer has not minted yet. Resume again later. +- `ConfigError` (step `fetchAttestation`) when the attested message is for another destination or amount than the record. +- `OnchainRevertError` (step `mint`) when the EVM mint reverted, after one re-attestation if the attestation had expired. +- On Solana, Stellar and Starknet destinations, wallet errors during the mint (`UserRejectedError`, `WrongChainError`, ...). + +**Throws** + +- `RouteUnavailableError` with `reason: "destination_adapter_required"` when the mint needs a wallet and `destinationAdapter` is missing or of the wrong ecosystem. +- On EVM destinations, wallet errors from the mint (`UserRejectedError`, `WrongChainError`, `NetworkError`, ...) and `BridgeStepError` when a needed re-attestation is not ready. +- `@usewhisk/cctp` errors when Iris or an RPC is unreachable. + +In every thrown case the burn has already happened and the record is still in the store, so the payer can try again. + +## resumeFromTx + +```ts +resumeFromTx(params: ResumeFromTxParams, listeners?: SendListeners): Promise; +``` + +As `resume`, from the burn's hash alone, such as from a receipt link or `onBurnSubmitted`. If the store has a record for that hash it is used; otherwise one is built from what Iris decoded and saved to the store. + + + Chain the burn was sent on. + + ++ The burn transaction hash. Matched case-insensitively against stored records. + + ++ As in `resume`. + + +**Throws** what `resume` throws, and `BridgeStepError` (retryable) when Iris has not seen a burn in that transaction yet. + +## refund + +```ts +refund(params: RefundParams, listeners?: SendListeners): Promise; +``` + +Sends funds back to the payer of an earlier transfer. It is an ordinary send from `merchantAdapter` on `originalDestinationChain` to `originalSenderAddress` on `refundDestinationChain`, quoted and executed in one call with the config's fee settings. The result's `metadata` carries `__refundOfTxHash` and, when given, `__refundReason`. See [Refunds](/flows/refunds). + +```ts refund.ts +import type { EvmAdapter, WhiskEngine } from "@usewhisk/core"; + +declare const engine: WhiskEngine; +declare const merchantWallet: EvmAdapter; + +const refund = await engine.refund({ + originalTxHash: + "0x5f2c9a1e7b3d4c6f8a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f", + originalDestinationChain: "Arc_Testnet", + refundDestinationChain: "Base_Sepolia", + originalSenderAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + amount: "10.50", + reason: "Item out of stock", + merchantAdapter: merchantWallet, +}); +console.log(refund.metadata?.__refundOfTxHash); +``` + + + Source-chain hash of the original transfer. Stored as `__refundOfTxHash`. + + ++ Where the merchant received the payment. The refund is sent from here. + + ++ Where the refund lands, usually the chain the payer paid from. + + ++ The refund recipient. + + ++ Decimal USDC. May be less than the original. + + ++ At most 256 characters. Stored as `__refundReason`. + + ++ Extra correlation data. No `__` keys. + + ++ The wallet holding the funds being refunded. + + ++ Signs the mint when Circle does not forward it. + + +**Returns** a `RefundResult`, which is a `SendResult`. + +**Throws** `ConfigError` from [validateRefundInput](/reference/core/types#refunds) before anything else, then what `quote` and `send` throw, except that a refund skips the expiry and balance checks: it quotes and sends at once. + +## Adapters + +The engine builds calls and hands them to an adapter to sign and submit. Each ecosystem has its own shape, told apart by `kind`. `@usewhisk/react` ships one per ecosystem ([wallet adapter hooks](/reference/react/hooks#wallet-adapter-hooks)); write your own for a server wallet or another wallet library. Adapters should throw `WhiskError`s (use `toWhiskError`), because the engine does not reclassify errors. + +```ts +type WhiskAdapter = + EvmAdapter | SolanaAdapter | StellarAdapter | StarknetAdapter; +``` + +`SolanaAdapter`, `StellarAdapter`, `StarknetAdapter`, their receipt types and `StellarTrustline` are exported from `@usewhisk/core` only. + +```ts evmAdapter.ts +import type { EvmAdapter } from "@usewhisk/core"; + +declare function signAndSend(tx: { + to: `0x${string}`; + data: `0x${string}`; + value: bigint; +}): Promise<`0x${string}`>; +declare function waitFor(hash: `0x${string}`): Promise<{ + status: "success" | "reverted"; + blockNumber: bigint; +}>; +declare let currentChainId: number; + +export const adapter: EvmAdapter = { + kind: "evm", + address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + async getChainId() { + return currentChainId; + }, + async switchChain(chainId) { + currentChainId = chainId; + }, + async sendCalls(calls, options) { + const hashes: `0x${string}`[] = []; + for (const [index, call] of calls.entries()) { + const hash = await signAndSend(call); + hashes.push(hash); + options?.onSubmitted?.(hash, index); + await waitFor(hash); + } + return { hashes }; + }, + waitForReceipt: waitFor, +}; +``` + +### EvmAdapter + ++ Discriminant. + + ++ The wallet address. + + ++ The wallet's current chain id. The engine reads it before each write and + switches when it differs. + + ++ Rejects with `WrongChainError` when the user declines or the wallet lacks the + chain. + + ++ Optional. Whether `sendCalls` can land a batch on `chainId` all or nothing. + The engine asks before a transfer that carries a `feePolicy` fee, and sends + the fee in the same batch only when this says yes. Without it, the fee is a + separate request once the burn or transfer has landed. + + ++ Signs and submits `calls`. Without `options.atomic`, submit in array order and + wait for each receipt before the next, or a burn can race its approve. With + `atomic: true`, land every call or none, as one EIP-5792 batch, or throw + `WalletCapabilityError("atomic_unsupported", ...)` before sending anything; + the engine then sends the calls one by one. Throws a `WhiskError`. + + ++ The adapter picks the timeout; the engine treats a timeout as a failure of the + step it was waiting on. + + ++ + ++ ++ Target contract. + ++ Calldata. + ++ Native value in wei. Always `0n` for CCTP calls. + ++ Set by the engine on Arc, which drops transactions under its 20 gwei + floor. Pass it through when set. + ++ Set with `maxFeePerGas`. + ++ Call `onSubmitted` with each hash as soon as the wallet returns it, before + waiting for a receipt. `index` is the call it covers; a batch sharing one hash + reports it once, for the last call. The engine uses it to save the burn hash + early. `atomic` asks for an all-or-nothing batch; the engine sets it only + after `supportsAtomicBatch` said yes. + + ++ Hashes in submission order. An EIP-5792 batch may return a single hash for all + calls. + + ++ What `waitForReceipt` resolves to. + + +### SolanaAdapter + ++ Discriminant. + + ++ Base58 public key. + + +Promise<"mainnet-beta" | "devnet">'} + required +> + Checked against the chain before burns and mints. + + ++ Fetch a recent blockhash, set the wallet as fee payer, partial-sign with each + extra signer, then have the wallet sign and send. + + ++ Wait at the wallet's usual commitment, typically `confirmed`. Resolves to `{ status: "success" | "reverted"; slot: bigint }`. + + ++ `null` when the account does not exist. The engine uses it to check the + recipient's USDC account before burning and to read CCTP state. + + ++ A one-off keypair the engine generates, such as the CCTP burn's + `message_sent_event_data` account. `secretKey` is the 64-byte ed25519 key. + + +### StellarAdapter + ++ Discriminant. + + ++ Usually a `G...` strkey. + + +Promise<"public" | "testnet">'} + required +> + Checked against the chain before a burn into Stellar and before mints. + + ++ Soroban allows one host function per transaction, so submit each invocation on + its own and wait until it lands before the next. Build, simulate, sign and + submit. The engine treats the last hash as the main one. + + ++ Resolves to `{ status: "success" | "reverted"; ledger: number }`. + + ++ The engine sets the USDC approval expiry from it. + + ++ Optional. The account's trustline for `asset`, or `null` when it has none. + Before a burn into Stellar the engine reads the recipient's USDC trustline + through the destination adapter's `getTrustline`, and refuses a classic + account whose trustline is missing, not authorized or full. Throw on an RPC + failure rather than returning `null`. Without this method, a bridge into a `C` + address still works, and a bridge into a `G` or `M` address is refused before + the burn with `ConfigError`. + + ++ `balance` and `limit` in stroops (7 decimals). `authorized` is the issuer's + `AUTHORIZED` flag; without it the account cannot receive. + + +### StarknetAdapter + ++ Discriminant. + + ++ felt252 hex. + + ++ The wallet's chain id felt, checked before each write. + + ++ A single multicall is preferred. The engine treats the last hash as the main + one. + + ++ Resolves to `{ status: "success" | "reverted"; blockNumber: number }`. + + +`SolanaInstruction`, `StellarInvocation` and `StarknetCall` come from `@usewhisk/cctp`. See [Builders](/reference/cctp/builders). diff --git a/reference/core/errors.mdx b/reference/core/errors.mdx new file mode 100644 index 0000000..aaf4c60 --- /dev/null +++ b/reference/core/errors.mdx @@ -0,0 +1,238 @@ +--- +title: "Errors" +description: "Every Whisk error class, code, category and route-unavailable reason: when each happens, whether funds moved, and what the app should do." +--- + +Every error the engine raises is a `WhiskError` with a stable `code`. They are exported from `@usewhisk/core`, from `@usewhisk/core/errors`, and re-exported by `@usewhisk/react`. For the handling patterns, see [Errors](/concepts/errors). + +```ts +import { WhiskError, type SendResult } from "@usewhisk/core"; + +declare function send(): Promise; + +try { + const result = await send(); + if (result.kind === "failure") { + const { code, step, retryable, message } = result.error; + console.log(code, step, retryable, message); + } +} catch (err) { + if (err instanceof WhiskError) console.log(err.code, err.category, err.cause); + else throw err; +} +``` + +Errors reach you two ways. **Thrown** errors come from checks that run before anything is signed (the exceptions are listed under [resume](/reference/core/engine#resume)). **Returned** errors sit on `SendFailure.error`, after a wallet was asked to sign; the failed step in `SendFailure.steps` tells you whether the burn landed. See [Fund safety](/concepts/fund-safety). + +## WhiskError + +```ts +class WhiskError extends Error { + readonly code: WhiskErrorCode; + readonly retryable: boolean; + readonly step?: StepName; + readonly category?: WhiskErrorCategory; + readonly cause?: unknown; + constructor(opts: WhiskErrorOptions); +} +``` + + + Switch on this. Stable across releases. + + ++ Human-readable, safe to show. Wallet and RPC noise is cut down to the first + line; the original stays on `cause`. + + ++ `true` when repeating the same action can succeed (the payer can sign again, + the network can recover, Circle can catch up). Defaults to `false`. + + ++ The step that failed, when the error knows it. On returned failures, the + failed entry in `steps` is the reliable source. + + ++ Finer classification of wallet and chain failures. See + [Categories](#categories). + + ++ The original error from the wallet, RPC or Iris. + + +`WhiskErrorOptions` is `{ code; message; retryable?; step?; category?; cause? }`, for creating your own `WhiskError` in an adapter. + +`instanceof` works for every subclass, including after transpilation. + +## Codes + +"Before burn" means no USDC has left the payer's wallet for the bridge. "After burn" means USDC is in flight and the transfer can be finished with `resume` or `resumeFromTx`. On EVM sources with a `feePolicy`, the merchant fee goes in one atomic batch with the burn or after the burn has landed, never before it, so a failure before the burn never costs the payer the fee. A fee the payer rejects after the burn is reported on `customFee`, not as a failure. + +| Code | Class | Retryable | When it happens | Funds | What the app should do | +| ---------------------- | -------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `NO_ADAPTER` | `NoAdapterError` | no | Not raised by the engine or the React package in 0.3. Exported for your own adapters and UI. | Before burn. | Ask the payer to connect a wallet. | +| `WRONG_CHAIN` | `WrongChainError` | yes | A Solana, Stellar or Starknet destination wallet is on a different network than the destination chain: checked before the burn on routes into Solana, Stellar and Starknet, and again when the wallet signs a mint. Custom EVM adapters throw it from `switchChain` when the wallet refuses to switch. | Before burn on the destination pre-check; after burn when minting. | Ask the payer to switch the wallet to `err.expectedChain`, then send again (before burn) or resume (after burn). | +| `INSUFFICIENT_BALANCE` | `InsufficientBalanceError` | no | Thrown by `send` when an EVM payer's USDC is below `quote.subunits.amountIn` plus, on Arc, the gas reserve. Solana, Stellar and Starknet balances are not checked; the wallet refuses instead. | Before burn. Nothing signed. | Show `err.required` and `err.available` (decimal USDC). Offer `maxSendable`. | +| `INVALID_ADDRESS` | `InvalidAddressError` | no | Thrown by `quote` when the recipient does not fit the destination's address format, including a Starknet address below `2**160` (an Ethereum address pasted by mistake) or past Starknet's address range. Returned by same-chain sends that catch a bad address before the wallet is asked. | Before burn. Nothing signed. | Ask for a correct address. `err.input` holds what was given. | +| `RESOLVER_FAILED` | `ResolverError` | yes | Thrown by `resolve` when a resolver fails, such as an ENS RPC error. | No transfer yet. | Retry, or ask for a raw address. `err.resolverName` names the resolver. | +| `BRIDGE_STEP_FAILED` | `BridgeStepError` | yes by default | From `resume` and `resumeFromTx`: Circle has not attested the burn yet, its relayer has not minted yet, a re-attestation is not ready, or Iris has not seen the burn hash. | After burn. | Wait, then resume again. The record stays in the store. | +| `USER_REJECTED` | `UserRejectedError` | yes | The payer declined a wallet prompt. Category `user_rejected`. Message: "You cancelled the transaction in your wallet." | Depends on the step: at `approve`, `burn` or `transfer`, before burn; at `mint`, after burn. | Let the payer try again. At `mint`, resume when they are ready. | +| `NETWORK_ERROR` | `NetworkError` | yes | A transient network failure in a wallet or RPC call (connection reset, timeout, `fetch failed`, HTTP 5xx). Also returned at step `mint` with category `failed_offchain` when Circle's forwarder reports `FAILED` on a Solana to EVM bridge. | Check the failed step. | Retry. After burn, resume: for a failed forward, with a `destinationAdapter` to mint. | +| `WALLET_CAPABILITY` | `WalletCapabilityError` | no | In 0.3 the engine returns it with category `polling_timeout` when Circle has not attested within the poll window (step `fetchAttestation`) or the forwarder has not minted in time (step `mint`). An adapter throws it with `atomic_unsupported` from `sendCalls({ atomic: true })` when it cannot land the batch all or nothing; `useEvmAdapter` does so on Arc and for wallets that refuse an atomic batch. The other categories come only from adapters that report EIP-5792 batch problems. | `polling_timeout`: after burn. Others: before burn. | `polling_timeout`: the transfer is still in flight; resume later even though `retryable` is `false`. `atomic_unsupported` from a fee batch: nothing to do, the engine sends the calls one by one instead. Others: fall back to sequential calls in the adapter. | +| `ONCHAIN_REVERT` | `OnchainRevertError` | no | A transaction reverted. At step `approve`: the approve, or an atomic batch carrying the merchant fee. At `burn`: the burn. At `mint`: the mint (resume re-attests an expired attestation once before giving up). A merchant fee transfer that reverts after the burn is reported on `customFee.error` and does not fail the transfer. | `approve`, `burn`: before burn, no USDC bridged. `mint`: after burn. | Before burn, check the payer's balance and try again. After burn, resume; if it keeps reverting, see [Recovery](/concepts/recovery). | +| `CONFIG_ERROR` | `ConfigError` | no | Bad setup or input: empty `chains`, invalid amount or metadata, a `feePolicy.recipient` that is not an EVM address, an adapter of the wrong ecosystem, a missing `destinationAdapter` on a route that needs one, `resolve` finding nothing, invalid refund input, a hook used outside `` or without a wallet. Returned before the burn on a bridge to a Stellar `G` or `M` recipient when the destination `StellarAdapter` has no `getTrustline`. From `resume`: a record with no burn hash, or an attested message that does not match the record. | Before burn, except the `resume` cases, which are after burn. | Fix the code or the input. For a record with no burn hash, use `resumeFromTx` with the hash from the wallet. | +| `NETWORK_MISMATCH` | `NetworkMismatchError` | no | `quote` or `send` with one mainnet and one testnet chain. | Before burn. Nothing signed. | Pick both chains on the same network. `err.source` and `err.destination` hold the chain labels. | +| `ROUTE_UNAVAILABLE` | `RouteUnavailableError` | no | The route cannot run as asked. See [reasons](#route-unavailable-reasons). | Depends on the reason. | Read `err.reason` and `err.ecosystem`. | +| `QUOTE_EXPIRED` | `QuoteExpiredError` | yes | Thrown by `send` when the quote is past `expiresAt` (60 seconds after issue), or Circle's signed upfront fee expired twice. | Before burn. Nothing signed. | Quote again and have the payer confirm the new numbers. `err.quote` is the expired quote. | +| `QUOTE_CHANGED` | `QuoteChangedError` | yes | Thrown by `send` when Circle's fees rose past the confirmed `maxFee`, or the route's speed or mint method changed. | Before burn. Nothing signed. | Show `err.quote` (fresh) next to `err.previous`, and send `err.quote` once the payer confirms. | +| `UNKNOWN` | `WhiskError` | no | `toWhiskError` could not classify the error. Also used for "no route" messages from routing APIs. | Check the failed step. | Show the message; log `cause`. | + +## Classes + +Each subclass sets its `code`, `name` and `retryable`, and some carry extra fields. + +| Class | Constructor | Extra fields | +| -------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `NoAdapterError` | `(message?, cause?)` | | +| `WrongChainError` | `(expectedChain: string, cause?)` | `expectedChain`: chain id, cluster, Stellar network or Starknet chain id felt the wallet should be on. | +| `InsufficientBalanceError` | `(required: string, available: string, token: string, cause?)` | `required`, `available` (decimal strings), `token`. | +| `InvalidAddressError` | `(input: string, cause?, message?)` | `input`. `message` defaults to saying the input is not a recognised address. | +| `ResolverError` | `(resolverName: string, message: string, cause?)` | `resolverName`. | +| `BridgeStepError` | `(step: StepName, message: string, opts?: { retryable?; cause? })` | `step` is always set. | +| `UserRejectedError` | `(message?, cause?)` | `category` is `"user_rejected"`. | +| `NetworkError` | `(message: string, cause?, category?)` | | +| `WalletCapabilityError` | `(category, message: string, cause?)` | `category` is one of `atomic_unsupported`, `batch_too_large`, `duplicate_batch_id`, `unknown_bundle`, `polling_timeout`. | +| `OnchainRevertError` | `(category, message: string, cause?, step?)` | `category` is one of `reverted_onchain`, `partial_reverted`, `chain_revert`. | +| `ConfigError` | `(message: string, cause?)` | | +| `NetworkMismatchError` | `(source: string, destination: string)` | `source`, `destination` (chain labels). | +| `RouteUnavailableError` | `(reason: RouteUnavailableReason, message: string, ecosystem?: string)` | `reason`, `ecosystem`. | +| `QuoteExpiredError` | `(quote: Quote)` | `quote`: the expired quote. | +| `QuoteChangedError` | `(previous: Quote, quote: Quote)` | `previous`: what the payer confirmed. `quote`: the fresh quote. | + +```ts explain.ts +import { + InsufficientBalanceError, + NetworkMismatchError, + QuoteChangedError, + QuoteExpiredError, + RouteUnavailableError, + WrongChainError, + InvalidAddressError, + ResolverError, + toWhiskError, + type WhiskErrorCode, +} from "@usewhisk/core/errors"; + +export function explain(err: unknown): string { + if (err instanceof QuoteChangedError) { + return `New price: you pay ${err.quote.amountIn} (was ${err.previous.amountIn}).`; + } + if (err instanceof QuoteExpiredError) + return "The quote expired. Get a new one."; + if (err instanceof InsufficientBalanceError) { + return `Need ${err.required} ${err.token}, have ${err.available}.`; + } + if (err instanceof RouteUnavailableError) { + return err.reason === "destination_adapter_required" + ? `Connect a ${err.ecosystem ?? ""} wallet.` + : err.message; + } + if (err instanceof NetworkMismatchError) + return `${err.source} and ${err.destination} differ.`; + if (err instanceof WrongChainError) return `Switch to ${err.expectedChain}.`; + if (err instanceof InvalidAddressError) return `Bad address: ${err.input}`; + if (err instanceof ResolverError) return `${err.resolverName} failed.`; + const code: WhiskErrorCode = toWhiskError(err).code; + return code; +} +``` + +## Route unavailable reasons + +`RouteUnavailableReason` is the `reason` on a `RouteUnavailableError`. `err.ecosystem` names the wallet ecosystem involved, when there is one. + +| Reason | When it happens | Funds | What the app should do | +| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `same_chain` | `planRoute` called with the same chain as source and destination. `quote` and `send` treat that as a same-chain send instead, so the engine never raises it. | Before burn. | Use a same-chain send. | +| `source_adapter_required` | Thrown by `quote` or `send` on a bridge when `adapter` is not a wallet of the source chain's ecosystem. | Before burn. Nothing signed. | Connect a wallet of `err.ecosystem`. | +| `destination_adapter_required` | Thrown by `quote` or `send` when Circle will not forward the mint and no wallet of the destination ecosystem was passed. Thrown by `resume` and `resumeFromTx` when the mint needs a `destinationAdapter` that is missing or of the wrong ecosystem. | `quote`, `send`: before burn. `resume`: after burn. | Connect a wallet of `err.ecosystem` and call again (or resume). | +| `recipient_account_missing` | Returned as a failure on a bridge into Solana when the recipient has no USDC token account, which Solana's `receive_message` cannot create. Also returned on a bridge into Stellar when a `G` or `M` recipient has no USDC trustline, one the issuer has not authorized, or one without room under its limit for the amount. | Before burn. The message says "Nothing was sent." | Ask the recipient to create their USDC account on Solana (for example by receiving any USDC), or to add or raise their USDC trustline on Stellar, then send again. | +| `recipient_not_deployed` | Thrown by `quote` into Starknet when no account is deployed at the recipient address. Skipped for the connected Starknet wallet's own address and when the quote passes `allowUndeployedRecipient: true`. | Before burn. Nothing signed. | Ask the payer whether the address is their own new wallet. If they confirm, quote again with `allowUndeployedRecipient: true`. | + +## Categories + +`WhiskErrorCategory` uses the same values as Circle App Kit's `BridgeStepErrorCategory`. When `toWhiskError` gets a category, the category decides the class. + +| Category | Class | Produced in 0.3 by | +| -------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `user_rejected` | `UserRejectedError` | Any adapter error whose message says the user rejected or denied the request. | +| `atomic_unsupported` | `WalletCapabilityError` | Adapters, from `sendCalls({ atomic: true })`. `useEvmAdapter` throws it for calls that carry a gas price (Arc) and for a wallet that refuses the batch. The engine then sends the calls one by one. | +| `batch_too_large` | `WalletCapabilityError` | Adapters only. | +| `duplicate_batch_id` | `WalletCapabilityError` | Adapters only. | +| `unknown_bundle` | `WalletCapabilityError` | Adapters only. | +| `polling_timeout` | `WalletCapabilityError` | The engine, after a burn, when Circle's attestation or forwarder misses the poll window. | +| `failed_offchain` | `NetworkError` | The engine, when the forwarder reports `FAILED` on a Solana to EVM bridge. | +| `reverted_onchain` | `OnchainRevertError` | The engine and the React EVM adapter, for a reverted transaction. | +| `partial_reverted` | `OnchainRevertError` | Adapters only. | +| `chain_revert` | `OnchainRevertError` | Adapters only. | +| `unknown` | decided by the message | Passing it is the same as passing no category. | + +## Helpers + +```ts +import { WhiskError, cleanErrorMessage, toWhiskError } from "@usewhisk/core"; + +const fromWallet = toWhiskError(new Error("User rejected the request.")); +const custom = new WhiskError({ + code: "UNKNOWN", + message: cleanErrorMessage("execution reverted\nRequest Arguments: ..."), + retryable: false, +}); +const timedOut = toWhiskError( + new Error("still pending"), + "Timed out", + "polling_timeout", +); +console.log(fromWallet.code, custom.message, timedOut.code); +``` + +### toWhiskError + +```ts +function toWhiskError( + err: unknown, + fallbackMessage?: string, + category?: WhiskErrorCategory, +): WhiskError; +``` + +Turns anything thrown into a `WhiskError`, keeping the original on `cause`. Use it in adapters and around calls to `@usewhisk/cctp`. + +1. A `WhiskError` is returned unchanged. +2. A `category` other than `unknown` picks the class from the table above. +3. Otherwise the message is matched: "user rejected", "user denied" or "rejected by user" gives `UserRejectedError`; "no route" or "route not found" gives an `UNKNOWN` error asking to try another amount; `ECONNRESET`, `ETIMEDOUT`, `ENOTFOUND`, `ECONNREFUSED`, `EAI_AGAIN`, "socket hang up", "network error", "fetch failed" or "status code 5xx" gives `NetworkError`. +4. Anything else is `UNKNOWN`, not retryable. + +`fallbackMessage` (default `"Unknown error"`) is used when `err` is neither an `Error` nor a string. + +### cleanErrorMessage + +```ts +function cleanErrorMessage(message: string): string; +``` + +Keeps the first line of a viem or App Kit error, drops any inline "Request Arguments:" dump and App Kit's "Unknown blockchain error on chain:" prefix. Returns the trimmed original when nothing is left. + +## Errors from @usewhisk/cctp + +Iris and RPC calls inside `quote`, `send`, `balance`, `resume` and the Iris helpers can throw errors from `@usewhisk/cctp`. These are not `WhiskError`s: they extend `CctpError` with their own `code`, such as `IrisNetworkError` (`iris_network`), `IrisRateLimitedError` (`iris_rate_limited`, with `retryAt`), `IrisHttpError` (`iris_http`), `ProtocolError` (`rpc_unavailable`, `fee_unavailable`, `no_route`) and `UnknownChainError` (`invalid_chain`). They are thrown before any signature in `quote` and `send`. Wrap them with `toWhiskError` if you want one shape. See [CCTP overview](/reference/cctp/overview). + + + `@usewhisk/cctp` also has a class named `InvalidAddressError`. It is not the + `@usewhisk/core` one: `instanceof` against the core class does not match it. + diff --git a/reference/core/types.mdx b/reference/core/types.mdx new file mode 100644 index 0000000..885b3cb --- /dev/null +++ b/reference/core/types.mdx @@ -0,0 +1,960 @@ +--- +title: "Types and helpers" +sidebarTitle: "Types" +description: "The public types of @usewhisk/core and its helper functions and constants, grouped by topic." +--- + +Everything here is exported from `@usewhisk/core`. Types without runtime code are also on `@usewhisk/core/types`, together with `DEFAULT_TOKEN`, `DEFAULT_FEE_BEARER`, `isBridgeRoute` and `isSendRoute`, so a type-only import pulls in nothing else. + +```ts summary.ts +import type { Quote, SendResult, Step } from "@usewhisk/core"; +import { formatUsdcAmount, isBridgeRoute } from "@usewhisk/core"; + +export function summary(quote: Quote): string { + const route = isBridgeRoute(quote.route) + ? `${quote.route.sourceChain} to ${quote.route.destinationChain}` + : quote.route.chain; + return `${route}: you pay ${quote.amountIn}, recipient gets ${formatUsdcAmount(quote.subunits.amountOut)} ${quote.token}`; +} + +export function lastTx(result: SendResult): string | undefined { + const done: Step[] = result.steps.filter((s) => s.state === "success"); + return result.kind === "success" ? result.finalTxHash : done.at(-1)?.txHash; +} +``` + +## Amounts + +USDC amounts are decimal strings at the API edge and `bigint` subunits inside, with 6 decimals. Stellar's 7-decimal balances are scaled at the edge. See [Amounts and units](/concepts/amounts-and-units). + +```ts +import { + formatUsdcAmount, + parseUsdcAmount, + USDC_DECIMALS, +} from "@usewhisk/core"; + +const subunits = parseUsdcAmount("12.3456789"); +console.log(subunits, formatUsdcAmount(subunits), USDC_DECIMALS); +``` + +| Export | Signature | Notes | +| ------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `USDC_DECIMALS` | `6` | The decimals CCTP messages carry. | +| `parseUsdcAmount` | `(input: string) => bigint` | Trims, then accepts digits with at most one dot. Digits past the sixth decimal are dropped, never rounded. Throws `ConfigError` for anything else, and for zero. `"12.3456789"` gives `12345678n`. | +| `formatUsdcAmount` | `(subunits: bigint) => string` | Strips trailing zeros: `1500000n` gives `"1.5"`. Throws `ConfigError` for negative input. | + +## Chains + ++ A chain id from the registry, such as `"Ethereum"`, `"Base_Sepolia"`, + `"Arc_Testnet"`, `"Solana_Devnet"`, `"Stellar"` or `"Starknet_Sepolia"`. The + same strings Circle's App Kit uses. Full list: [Chains](/chains). + + ++ The ecosystem of a chain. + + ++ Every transfer stays on the network of its source chain. + + ++ A registry entry: `id`, `label`, `network`, `ecosystem`, `cctpDomain`, + `usdcDecimals`, `nativeCurrency`, `defaultRpcUrls`, `explorerUrl`, + `capabilities` and the ecosystem's contract addresses. Documented in [CCTP + chains](/reference/cctp/chains). + + +```ts +import { + CHAINS, + addressFormat, + chainByDomain, + chainByEvmChainId, + chainsByNetwork, + explorerAddressUrl, + explorerTxUrl, + getChain, + isChainId, + tryChainByEvmChainId, + type CctpChain, +} from "@usewhisk/core"; + +const arc: CctpChain = getChain("Arc_Testnet"); +const testnets = chainsByNetwork("testnet").map((c) => c.id); +const base = chainByEvmChainId(8453); +const maybe = tryChainByEvmChainId(31337); +const solana = chainByDomain(5, "mainnet"); +const input = "Base_Sepolia"; +if (isChainId(input)) console.log(explorerTxUrl(input, "0xabc")); +``` + +| Export | Signature | Notes | +| ------------------------------ | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `CHAINS` | `readonly CctpChain[]` | Every chain in the registry, mainnet and testnet. | +| `getChain` | `(id: Chain) => CctpChain` | Throws `UnknownChainError` (from `@usewhisk/cctp`) for an unknown id. | +| `isChainId` | `(value: string) => value is Chain` | Type guard for untrusted input. | +| `chainsByNetwork` | `(network: ChainNetwork) => readonly CctpChain[]` | | +| `chainByEvmChainId` | `(evmChainId: number) => EvmChain` | Throws `UnknownChainError`. | +| `tryChainByEvmChainId` | `(evmChainId: number) => EvmChain \| undefined` | For a wallet's chain id, which can be any chain. | +| `chainByDomain` | `(domain: number, network: ChainNetwork) => CctpChain` | Mainnet and testnet share CCTP domains. Throws `UnknownChainError`. | +| `explorerTxUrl` | `(chain: Chain, txHash: string) => string` | | +| `explorerAddressUrl` | `(chain: Chain, address: string) => string` | Uses `contract` paths for Starknet and Stellar `C...` addresses. | +| `addressFormat` | `(chain: Chain) => AddressFormat` | `{ pattern: RegExp; hint: string }` for the chain's ecosystem. A shape check for forms; `quote` validates fully. | +| `getStarknetTransactionStatus` | `(chain: StarknetChain, hash: string, options?: RpcOptions) => Promise` | Re-exported from `@usewhisk/cctp`. Returns `{ state: "pending" }` or `{ state: "success" \| "reverted"; blockNumber }`. | + +## Tokens + + + Token symbols, kept from Circle's App Kit. Only `"USDC"` moves through Whisk + in 0.3. + + ++ `"USDC"`. + + +## Recipients + ++ What `resolve` returns and `quote` takes. + + + +## Resolvers + +Also exported from `@usewhisk/core/resolvers` (the functions) and `@usewhisk/core/types` (the types). + +```ts resolver.ts +import { addressResolver, composeResolvers } from "@usewhisk/core/resolvers"; +import type { Resolver } from "@usewhisk/core/types"; + +const handles: Resolver = { + name: "handles", + matches: (input) => input.startsWith("@"), + resolve: async (input, { chain }) => { + const res = await fetch( + `https://api.example.com/handles/${input.slice(1)}`, + ); + if (res.status === 404) return null; + const { address } = (await res.json()) as { address: string }; + return { address, chain, displayName: input }; + }, +}; + +export const resolver = composeResolvers([addressResolver, handles], { + name: "app", +}); +``` + ++ +The address on `chain`. +The destination chain. +A label, such as the ENS name. +For resolvers that create a wallet for an off-platform recipient. The engine does not read it. +Paired with `needsClaimLink`. The engine does not read it. ++ + ++ ++ Shown in `ResolverError` messages. + ++ Synchronous shape check. Only matching resolvers are asked to resolve. + ++ Return `null` to let the next resolver try. Throw `ResolverError` on + unexpected failure. + ++ The destination chain the input should resolve on. + + ++ Matches input shaped like an address of any ecosystem, and resolves it when it + fits the destination chain's format. The engine's default resolver. + + ++ Tries each matching resolver in order and returns the first non-null result. + An error that is not already a `ResolverError` is wrapped in one. Throws a + plain `Error` when `resolvers` is empty. `name` defaults to `"composite"`. + + +## Routes + ++ Same chain is a send; anything else is a bridge. + + ++ Type guards that narrow a `Route`. + + ++ How a bridge will run. Present on bridge quotes as `quote.plan`. + + + +| Export | Signature | Notes | +| --------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `decideRoute` | `(sourceChain: Chain, destinationChain: Chain) => Route` | Throws `ConfigError` when either is missing. | +| `planRoute` | `(input: PlanRouteInput) => RoutePlan` | Throws `RouteUnavailableError` (`same_chain`, `source_adapter_required`, `destination_adapter_required`) and `NetworkMismatchError`. Does not apply the Fast allowance. | +| `connectedEcosystems` | `(...adapters: ({ kind: ChainKind } \| undefined)[]) => ChainKind[]` | The distinct `kind`s of the adapters given. | + +`PlanRouteInput` is `{ source: Chain; destination: Chain; connected?: readonly ChainKind[]; useForwarder: boolean }`. Leave out `connected` to skip the wallet check. + +```ts +import { connectedEcosystems, decideRoute, planRoute } from "@usewhisk/core"; + +const route = decideRoute("Solana_Devnet", "Arc_Testnet"); +const plan = planRoute({ + source: "Solana_Devnet", + destination: "Arc_Testnet", + connected: connectedEcosystems({ kind: "solana" }), + useForwarder: true, +}); +console.log( + route.kind, + plan.speed, + plan.mint, + plan.requiredAdapters, + plan.etaSeconds, +); +``` + +## Quote + +What `engine.quote` returns. Amount strings are decimal USDC; `subunits` holds the same values as 6-decimal `bigint`s, and `send` signs those. + ++ +Source registry entry. +Destination registry entry. +From the source chain. +Fast where the source supports it and the amount fits Circle's remaining Fast allowance; otherwise Standard. +`{ kind: "forwarder" }` when Circle submits the mint, or `{ kind: "adapter"; ecosystem }` when a wallet of that ecosystem must. +The wallet ecosystems the route needs, source first. +Circle's published attestation time for the source at this speed. The mint adds a few seconds. ++ New for every quote, including a refreshed one. Bridges use it as the inflight + record id. + + ++ Milliseconds since the epoch. + + ++ `issuedAt` plus 60 seconds. `send` throws `QuoteExpiredError` after it. + + ++ `"maxFee"`: Circle takes its fee out of the burn, capped by `subunits.maxFee`. + `"upfront"`: the payer pays Circle's signed fee beside the burn, at most + `subunits.maxFee`, and the whole burn mints. Upfront is used only with + `feeBearer: "sender"`, from EVM sources that support it, not into Stellar, and + only when there is a Fast or forwarding fee to pay. + + ++ Send or bridge, with the chains. + + ++ Who receives. + + ++ The most debited from the payer, merchant fee included. Show it as "You pay". + + ++ The least the recipient gets. Show it as "Recipient gets". + + ++ The amount burned on the source chain. Equal to the requested amount on a + same-chain send. + + ++ `"USDC"` unless `QuoteParams.token` says otherwise. + + ++ The fee lines. See [Fees](#fees). + + ++ + ++ ++ The amount the payer entered. + ++ Debited from the payer, merchant fee included. + ++ Burned on the source chain. `0n` on a same-chain send. + ++ Circle's protocol fee, before the Fast buffer. + ++ Circle's forwarding fee, `0n` when not forwarded. + ++ The cap on Circle's fees: `burnFee` plus 10% on Fast, plus `forwarderFee`. + ++ The least the recipient gets. + ++ The merchant fee, `0n` without a `feePolicy`. + ++ 15 seconds for a same-chain send; the plan's `etaSeconds.max` for a bridge. + + ++ Present on bridge quotes. + + +The `subunits` object's type is not exported by name; use `Quote["subunits"]`. + +## Fees + ++ A merchant fee on top of every transfer, split 90/10 with the Whisk treasury. + `bps` is ignored. See [createWhisk](/reference/core/create-whisk). + + ++ Who absorbs Circle's fees on a bridge. + + ++ `"sender"`. + + ++ The engine emits `"custom"` (merchant and treasury shares), `"protocol"` + (Circle's burn fee, buffer included) and `"forwarder"`. `"gas"` and + `"provider"` exist in the type but are not produced in 0.3. + + ++ + ++ ++ What the fee is for. + ++ Decimal amount. + ++ The token it is paid in. + ++ Who gets it, for custom entries. + ++ Display text, such as `"Merchant fee (90%)"` or `"CCTP protocol fee, at + most"`. + ++ `total` sums the entries in `token` only. + + +```ts +import { + BPS_DENOMINATOR, + buildCustomFeeEntries, + splitCustomFee, + sumFees, + sumForwarderFees, + sumProtocolFees, + WHISK_TREASURY_ADDRESS, + WHISK_TREASURY_BPS, + type CustomFeeSplit, +} from "@usewhisk/core"; + +const entries = buildCustomFeeEntries( + { value: "1", recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1" }, + "USDC", +); +const breakdown = sumFees(entries, "USDC"); +const split: CustomFeeSplit = splitCustomFee(1_000_000n); +``` + +| Export | Signature | Notes | +| ------------------------ | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `buildCustomFeeEntries` | `(policy: FeePolicy \| undefined, token: Token) => FeeEntry[]` | The two `"custom"` entries for a policy, or none. | +| `sumFees` | `(entries: FeeEntry[], token: Token) => FeeBreakdown` | Entries in other tokens stay in `entries` but not in `total`. Throws `ConfigError` on a malformed amount. | +| `sumProtocolFees` | `(entries: FeeEntry[], token: Token) => bigint` | Subunits of the `provider`, `forwarder` and `protocol` entries: the fees taken out of the bridged amount. | +| `sumForwarderFees` | `(entries: FeeEntry[], token: Token) => bigint` | Subunits of the `forwarder` entries. | +| `splitCustomFee` | `(total: bigint) => CustomFeeSplit` | `{ merchant, whisk }` in subunits. The treasury gets 10% rounded down; the merchant gets the rest. | +| `WHISK_TREASURY_ADDRESS` | `` `0x${string}` `` | `0x404b07e55c6a4F1eA10e94e3d9404b7685E18238`, the same on every EVM chain. | +| `WHISK_TREASURY_BPS` | `bigint` | `1000n` (10%). | +| `BPS_DENOMINATOR` | `bigint` | `10000n`. | + +## Steps + ++ `approve`: USDC allowance for the burn (`noop` when none is needed). + `transfer`: same-chain transfer. `burn`: CCTP burn on the source. + `fetchAttestation`: waiting for Circle. `mint`: destination mint, by a wallet + or Circle's forwarder. + + ++ `noop` means the step was not needed. + + ++ + +## SendResult + +`send`, `resume`, `resumeFromTx` and `refund` resolve to a `SendResult`. `RefundResult` is the same type. + ++ ++ Which step. + ++ Its state. + ++ The transaction, once submitted. + ++ Set by `deriveReceiptView`. + ++ Set on the failed step. + ++ Set on the failed step when the error has a category. + ++ On `mint`: `true` when Circle's forwarder submitted it. + ++ + ++ ++ Discriminant. + ++ The mint (bridge) or transfer (send) hash, when known. Can be missing on a + resumed transfer the destination had already received. + ++ Every step and its final state. + ++ Whether the payer paid the `feePolicy` fee. Set whenever a fee policy + charged this transfer, which happens on EVM sources only. + ++ Config defaults merged with per-call metadata. Missing when neither was + set. + ++ + ++ ++ Discriminant. + ++ What went wrong. See [Errors](/reference/core/errors). + ++ The failed step has `state: "error"`. A successful `burn` step means USDC + is in flight. + ++ The executor's recovery snapshot (domains, burn hash, message and + attestation when known). Not set by `resume`. + ++ As on success. A failure before the burn or transfer landed reports + `unpaid` with no `error`: the fee was never asked for. + ++ As on success. + ++ Whether the payer paid the `feePolicy` fee. Branch on `status`. `amount` is the + whole fee in USDC, as a decimal string. + + + +```ts +import type { CustomFeeOutcome } from "@usewhisk/core"; + +export function describeFee(fee: CustomFeeOutcome | undefined): string { + if (!fee) return "No merchant fee."; + if (fee.status === "paid") return `Fee of ${fee.amount} USDC paid.`; + return fee.error + ? `Fee of ${fee.amount} USDC not paid: ${fee.error.message}` + : `Fee of ${fee.amount} USDC not charged.`; +} +``` + +`CustomFeeOutcome` is exported from `@usewhisk/core` only. From `@usewhisk/react`, name it as `NonNullable+ ++ `paid` once every fee share landed, in the batch with the burn or after it. + ++ The whole fee, such as `"0.25"`. + ++ Required when `paid`: the fee's transactions, or the one hash of an atomic + batch that shares it. When `unpaid`, the shares that landed before the + payer stopped, if any. + ++ `unpaid` only. Why the fee was not paid after the transfer landed, such as + a `UserRejectedError` or an `OnchainRevertError`. Missing when the fee was + never asked for. + +`. + +The parameter and option types of the engine methods (`QuoteParams`, `SendParams`, `SendListeners`, `SendStepListener`, `MaxSendable`, `ResumeOptions`, `ResumeFromTxParams`, `RefundParams`) are documented with their methods on [Engine](/reference/core/engine). `SendStepListener` is `(step: Step) => void`. + +## Inflight records + +```ts +import { + createMemoryInflightStore, + createStorageInflightStore, + type InflightRecord, + type InflightStore, +} from "@usewhisk/core"; + +const memory: InflightStore = createMemoryInflightStore(); +const persistent: InflightStore = createStorageInflightStore( + window.sessionStorage, +); + +const pending: readonly InflightRecord[] = await persistent.list(); +for (const record of pending) await memory.put(record); +``` + + + `put(record): Promise + +`, `list(): Promise `, `remove(id): Promise `. The engine never removes a burned record by itself. + + The engine's default. Lasts as long as the engine. + + ++ Keeps each record as JSON under `whisk:inflight: + +`. Lists only valid version 2 records, oldest first, and leaves other keys alone. `InflightStorage` is the `getItem`, `setItem`, `removeItem`, `key` and `length` part of the Web Storage API. + + `signing` is written before the wallet is asked, `burned` when the burn hash + comes back, `attested` after Circle signs, `minted` once the recipient has the + USDC. + + ++ JSON-safe. Amounts are subunit strings. + + + +## Widget state + +A reducer for building your own send flow. `@usewhisk/react` components do not use it in 0.3. + ++ +Record format. +The quote id, or `tx: +: ` for a record built by `resumeFromTx`. From the source chain. +Where the burn happened. +Where the mint goes. +Who submits the mint. +The attestation speed. +Burned amount in 6-decimal subunits, as in the CCTP message. +The recipient address (for a record built from a hash, the 32-byte mint recipient from the message). +How far it got. +The burn hash. Missing while `step` is `signing`. +The mint hash, when known. +The `feePolicy` fee this transfer carried, in subunits, and how far it got. A resumed transfer reports it and never asks for it again. +Milliseconds since the epoch. +Milliseconds since the epoch. ++ `{ kind: "disconnected" }`, `{ kind: "idle" }`, `{ kind: "resolving"; input }`, `{ kind: "resolved"; recipient }`, `{ kind: "quoting"; recipient; amount }`, `{ kind: "review"; quote }`, `{ kind: "sending"; quote; steps; currentStep }`, `{ kind: "succeeded"; quote; steps; finalTxHash? }`, `{ kind: "failed"; error; quote?; steps?; raw? }`. `WhiskStateKind` is the union of the `kind`s. + + ++ `CONNECTED`, `DISCONNECTED`, `RESET`, `RESOLVE_START`, `RESOLVE_SUCCESS`, `RESOLVE_FAILURE`, `QUOTE_START`, `QUOTE_SUCCESS`, `QUOTE_FAILURE`, `REVIEW_BACK`, `SEND_START`, `STEP_UPDATE`, `SEND_SUCCESS`, `SEND_FAILURE`, `RETRY_START`, `HYDRATE_FAILED`, each as `{ type, ...payload }`. + + +| Export | Signature | Notes | +| -------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| `reduce` | `(state: WhiskState, action: WhiskAction) => WhiskState` | An action that does not fit the current state returns the state unchanged. | +| `initialState` | `WhiskState` | `{ kind: "disconnected" }`. | +| `initialSteps` | `(routeKind: "send" \| "bridge") => Step[]` | `approve`, `transfer` for a send; `approve`, `burn`, `fetchAttestation`, `mint` for a bridge; all `pending`. | + +```ts +import { + initialState, + initialSteps, + reduce, + type WhiskState, +} from "@usewhisk/core"; + +let state: WhiskState = initialState; +state = reduce(state, { type: "CONNECTED" }); +console.log(state.kind, initialSteps("bridge")); +``` + +## Metadata + ++ Correlation data such as order ids. Flat, at most 1024 bytes as UTF-8 JSON, no + keys starting with `__`. It passes through the payer's browser: keep personal + data and credentials out. See [Metadata](/flows/metadata). + + +| Export | Signature | Notes | +| -------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `validateMetadata` | `(input: unknown) => asserts input is WhiskMetadata` | Throws `ConfigError` for a non-object, an empty key, a `__` key, a nested or non-finite value, or more than 1024 bytes. An empty object passes. | +| `mergeMetadata` | `(defaults?: WhiskMetadata, perCall?: WhiskMetadata) => WhiskMetadata \| undefined` | Per-call keys win. `undefined` when both are empty. | +| `METADATA_MAX_BYTES` | `1024` | | +| `METADATA_RESERVED_PREFIX` | `"__"` | | + +## Refunds + ++ `originalTxHash`, `originalDestinationChain`, `refundDestinationChain`, + `originalSenderAddress`, `amount`, `reason?`, `metadata?`. Field meanings are + on [engine.refund](/reference/core/engine#refund). + + ++ The checked input: the same fields with the hash and address trimmed, and + `reason` and `metadata` always present (possibly `undefined`). + + +| Export | Signature | Notes | +| --------------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `validateRefundInput` | `(input: RefundInput) => RefundPlan` | Throws `ConfigError` unless the hash and address are non-empty, `amount` is a positive decimal, `reason` is at most 256 characters and `metadata` is valid. Chains are checked when the refund is quoted. | +| `buildRefundMetadata` | `(originalTxHash: string, reason: string \| undefined, merchantMetadata: WhiskMetadata \| undefined) => WhiskMetadata` | Adds the reserved keys over the merchant's. Does not merge config defaults. | +| `REFUND_OF_TX_KEY` | `"__refundOfTxHash"` | | +| `REFUND_REASON_KEY` | `"__refundReason"` | | + +```ts +import { + buildRefundMetadata, + mergeMetadata, + REFUND_OF_TX_KEY, + validateMetadata, + validateRefundInput, +} from "@usewhisk/core"; + +const input: unknown = JSON.parse('{"orderId":"A-1001"}'); +validateMetadata(input); +const merged = mergeMetadata({ store: "eu" }, input); +const plan = validateRefundInput({ + originalTxHash: "0xabc", + originalDestinationChain: "Arc", + refundDestinationChain: "Base", + originalSenderAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + amount: "5", +}); +const tagged = buildRefundMetadata(plan.originalTxHash, "Cancelled", merged); +console.log(tagged[REFUND_OF_TX_KEY]); +``` + +## Receipts + +Derive a transfer's status from its hash without running the engine. `useReceipt` and `` are built on these. + +```ts +import { + deriveReceiptView, + describeReceiptChains, + RECEIPT_STAGE_HELP, + RECEIPT_STAGE_LABELS, + type ReceiptInput, +} from "@usewhisk/core"; + +const input: ReceiptInput = { + sourceChain: "Base_Sepolia", + sourceTxHash: + "0x5f2c9a1e7b3d4c6f8a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f", + destinationChain: "Arc_Testnet", + irisStatus: "pending_confirmations", +}; +const view = deriveReceiptView(input); +const { sourceLabel, destinationLabel } = describeReceiptChains(view, input); +console.log( + `${sourceLabel} to ${destinationLabel}: ${RECEIPT_STAGE_LABELS[view.stage]}`, + RECEIPT_STAGE_HELP[view.stage], +); +``` + + + `sourceChain`, `sourceTxHash`, `destinationChain` (equal to `sourceChain` for + a send), `destinationTxHash?`, `irisStatus?` (`undefined` before the first + Iris response), `hasError?` (forces `failed`). + + ++ `submitted`: Iris has not seen the burn. `awaiting_attestation`: Iris waits + for source confirmations. `attested`: attestation ready, no mint hash known. + `settled`: a mint hash is known, or it was a same-chain send. `failed`: + `hasError` was set. + + ++ `{ stage, steps, isCrossChain, sourceExplorerUrl, destinationExplorerUrl? }`. `steps` is a single `transfer` for a send, otherwise `burn`, `fetchAttestation`, `mint`. + + +| Export | Signature | Notes | +| ----------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| `deriveReceiptView` | `(input: ReceiptInput) => ReceiptView` | Pure. Call again with a fresher `irisStatus`. | +| `describeReceiptChains` | `(view: ReceiptView, input: ReceiptInput) => { sourceLabel; destinationLabel; isCrossChain }` | Chain labels for display. | +| `RECEIPT_STAGE_LABELS` | `Record` | English labels, such as `"Confirming on source chain"`. | +| `RECEIPT_STAGE_HELP` | `Record ` | One English sentence per stage. | + +## Iris + +A small wrapper over Circle's Iris attestation API. For the full client see [CCTP Iris](/reference/cctp/iris). + +```ts attestation.ts +import { + buildReceiveMessageCall, + fetchAttestationOnce, + getIrisBaseUrl, + IRIS_SANDBOX_URL, + pollAttestation, +} from "@usewhisk/core"; + +const burnTx = + "0x5f2c9a1e7b3d4c6f8a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f"; + +const once = await fetchAttestationOnce("Base_Sepolia", burnTx); +const done = await pollAttestation("Base_Sepolia", burnTx, { + timeout: 5 * 60_000, + pollingInterval: 5_000, + onUpdate: (m) => console.log(m.status), +}); + +if (done.status === "complete" && done.message && done.attestation) { + const call = buildReceiveMessageCall( + "Arc_Testnet", + done.message, + done.attestation, + ); + console.log(call?.address, call?.functionName, call?.args); +} +console.log(once.status, getIrisBaseUrl("Base_Sepolia") === IRIS_SANDBOX_URL); +``` + + + `not_found` until Iris has seen the burn. + + ++ `message` and `attestation` are `0x` hex, present once complete. + + ++ `baseUrl` defaults to the Iris host for the source chain's network. + + ++ `timeout` defaults to 600000 ms, `pollingInterval` to 3000 ms. + + +| Export | Signature | Notes | +| ---------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `fetchAttestationOnce` | `(sourceChain: Chain, burnTxHash: string, options?: FetchAttestationOptions) => Promise` | One lookup. Throws `@usewhisk/cctp` Iris errors. | +| `pollAttestation` | `(sourceChain: Chain, burnTxHash: string, options?: PollAttestationOptions) => Promise ` | Polls until `complete` or the timeout, then returns the latest status (it does not throw on timeout). Throws an `AbortError` `DOMException` when `signal` aborts. | +| `getIrisBaseUrl` | `(chain: Chain) => string` | `IRIS_MAINNET_URL` or `IRIS_SANDBOX_URL` by the chain's network. | +| `IRIS_MAINNET_URL` | `string` | `https://iris-api.circle.com` | +| `IRIS_SANDBOX_URL` | `string` | `https://iris-api-sandbox.circle.com`, used for testnets. | + +## Manual mint + +For a mint you submit yourself, for example after the forwarder reported `FAILED`. `engine.resume` does this for you; use these when you need to call the contract from your own code. + + + `{ destinationChain; address; abi: typeof RECEIVE_MESSAGE_ABI; functionName: "receiveMessage"; args: [message, attestation] }`, ready for viem's `writeContract` or wagmi's `useWriteContract`. + + +| Export | Signature | Notes | +| --------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| `buildReceiveMessageCall` | `(destinationChain: Chain, message: string, attestation: string) => ReceiveMessageCall \| null` | `null` for non-EVM destinations. Throws `TypeError` unless both inputs start with `0x`. | +| `messageTransmitterAddress` | `(chain: Chain) => string` | The chain's `MessageTransmitterV2`. | +| `manualMintExplorerUrl` | `(destinationChain: Chain, txHash: string) => string \| undefined` | Explorer link for the mint. | +| `RECEIVE_MESSAGE_ABI` | ABI fragment | `MessageTransmitterV2.receiveMessage` only. | +| `EVM_MAINNET_MESSAGE_TRANSMITTER` | `` `0x${string}` `` | Same address on every EVM mainnet. | +| `EVM_TESTNET_MESSAGE_TRANSMITTER` | `` `0x${string}` `` | Same address on every EVM testnet. | +| `SOLANA_MESSAGE_TRANSMITTER` | `string` | The Solana program id, the same on mainnet-beta and devnet. Core only. | + +## Webhook signing + +Server-side HMAC-SHA256 helpers for signing and verifying JSON payloads that your own servers send each other, such as a payment confirmation from your checkout backend. Whisk 0.3 does not send webhooks itself. They use Web Crypto, so they run on Node 18+, Deno, Bun and edge runtimes. Never ship the secret to a browser. + +```ts webhook.ts +import { verifyWebhook, signWebhook } from "@usewhisk/core"; + +declare const secret: string; + +const signed = await signWebhook({ orderId: "A-1001", status: "paid" }, secret); +await fetch("https://merchant.example.com/hooks/whisk", { + method: "POST", + headers: signed.headers, + body: signed.body, +}); + +export async function handle(request: Request): Promise{ + const rawBody = await request.text(); + const verified = await verifyWebhook<{ orderId: string }>( + rawBody, + Object.fromEntries(request.headers), + secret, + ); + if (!verified.ok) return new Response(verified.reason, { status: 401 }); + return new Response(verified.payload.orderId); +} +``` + +| Export | Signature | Notes | +| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `signWebhook` | ` (payload: T, secret: string, options?: SignWebhookOptions) => Promise ` | Wraps the payload in a `WebhookEnvelope` and signs `` `${timestamp}.${body}` ``. Throws `ConfigError` for an empty secret or without Web Crypto. | +| `verifyWebhook` | ` (rawBody: string, headers: Record , secret: string, options?: VerifyWebhookOptions) => Promise >` | Pass the raw body before JSON parsing. Header lookup ignores case. Returns `{ ok: false, reason }` instead of throwing, except for an empty secret. | +| `WHISK_SIGNATURE_HEADER` | `"x-whisk-signature"` | Hex HMAC. | +| `WHISK_TIMESTAMP_HEADER` | `"x-whisk-timestamp"` | Milliseconds since the epoch. | +| `WHISK_WEBHOOK_VERSION` | `"v1"` | | +| `DEFAULT_TIMESTAMP_TOLERANCE_MS` | `300000` | Allowed clock skew (5 minutes). | + + + The signed JSON body. + + ++ Fixed timestamp, for tests. + + ++ POST `body` byte for byte with `headers` (content type, signature and + timestamp). + + ++ `toleranceMs` defaults to `DEFAULT_TIMESTAMP_TOLERANCE_MS`. `now` is for + tests. + + ++ The verification outcome. + + ++ `"missing_signature"`, `"missing_timestamp"`, `"malformed_body"`, + `"malformed_envelope"`, `"unsupported_version"`, `"timestamp_out_of_range"`, + `"signature_mismatch"`. Safe to show. + + +## Config + +`WhiskConfig` is documented on [createWhisk](/reference/core/create-whisk). The error types are on [Errors](/reference/core/errors). diff --git a/reference/react/components.mdx b/reference/react/components.mdx new file mode 100644 index 0000000..226e775 --- /dev/null +++ b/reference/react/components.mdx @@ -0,0 +1,429 @@ +--- +title: "Components" +description: "Every component @usewhisk/react exports, with its full props." +--- + +All components render inside `` and read their engine, config and wallets from it. Import `@usewhisk/react/styles.css` once for their styles. + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; +import "@usewhisk/react/styles.css"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Arc_Testnet", "Base_Sepolia"], +}); + +export function App() { + return ( + + + ); +} +``` + +## WhiskProvider + +Root provider for every Whisk component and hook. It creates the engine once on mount, mounts the wallet contexts for the factories in `config.wallets`, and wraps its children in a `console.log(result.finalTxHash)} + onFailure={(result) => console.error(result.error.code)} + /> + ` that carries the theme. Guide: [WhiskProvider](/widget/whisk-provider). + +```tsx Providers.tsx +import { QueryClient } from "@tanstack/react-query"; +import type { ReactNode } from "react"; +import { WhiskProvider, type WhiskClientConfig } from "@usewhisk/react"; + +declare const config: WhiskClientConfig; +const queryClient = new QueryClient(); + +export function Providers({ children }: { children: ReactNode }) { + return ( ++ {children} + + ); +} +``` + ++ From [createWhiskConfig](/reference/react/config). Read once: the engine is + built on the first render and later changes to `config` do not reach it. + Wallet contexts and `useWhiskContext().config` do follow the new object. + + ++ Defaults to `"light"`. A preset name (`"light"`, `"dark"`, `"wine"`, `"indigo"`, `"emerald"`, `"monochrome"`), `"auto"` to follow `prefers-color-scheme` in CSS, `{ preset, tokens }` to replace some tokens, or a full `WhiskTheme`. See [Theme](/reference/react/config#theme). + + ++ A TanStack Query client to use when none is mounted above. An outer ` + +` is detected and reused, and then this prop is ignored. Without either, the provider creates its own client. + + Your app, or just the part that uses Whisk. + + +Behaviour worth knowing: + +- An outer `` is reused; `evm()`'s wagmi config is then ignored. +- It throws `ConfigError` when `config.wallets` has no factory and no outer ` ` exists. +- The engine gets `config.resolver ?? createDefaultResolver()` and `config.inflightStore ?? createBrowserInflightStore()`. +- Dropdowns and dialogs render into a ` ` inside the themed root, so they keep the theme. + +`WhiskProviderProps` is the type of these props. + +## WhiskSend + +The drop-in widget. The Send tab moves USDC on one chain; the Bridge tab moves it across chains with CCTP. The source chain's ecosystem decides which connected wallet pays, and a bridge into another ecosystem uses the destination ecosystem's wallet for the mint when Circle does not forward it. Guide: [WhiskSend](/widget/whisk-send). + +'}> + Which tabs to show, in order. Defaults to `["send", "bridge"]`. With one entry + the tab bar is hidden. An empty array falls back to both. + + ++ Heading. Defaults to `"Send USDC"`. + + ++ Shown under the title. + + ++ Initial amount, as a decimal USDC string. The payer can edit it. + + ++ Locks the amount to this decimal USDC string. Edits are ignored. + + ++ Initial recipient input: an address, or anything the configured resolver + accepts. + + ++ Locks the recipient input. + + ++ Initial source chain. Wins over `config.defaultSourceChain`. + + ++ Locks the source chain. + + ++ Initial destination for the Bridge tab. Wins over + `config.defaultDestinationChain`. If it is not on the source chain's network, + the widget switches to the first chain in `config.chains` that is. + + ++ Locks the Bridge tab's destination. + + ++ Called once when `engine.send` resolves with `kind: "success"`. For a bridge, + `result.finalTxHash` is the mint transaction when known. With a `feePolicy`, + check `result.customFee.status`: the transfer can succeed with the fee unpaid. + + ++ Called when `engine.send` resolves with `kind: "failure"`. `result.steps` + shows how far it got: if the burn succeeded, the funds are in flight and the + widget's resume list can finish the transfer. Errors that `send` throws before + signing (expired quote, raised fees, low balance) are handled inside the + widget and do not call this. + + +What it does on its own: + +- Resolves the recipient 320 ms after the last keystroke. +- Quotes as soon as it has a recipient, an amount and a connected source wallet, and fetches a new quote 5 seconds before the current one expires. +- On a `QuoteChangedError` it shows the old and new totals and asks the payer to press the button again. On a `QuoteExpiredError` it quotes again. +- Shows the payer's USDC balance and a Max button on EVM sources (`engine.balance` and `engine.maxSendable`). +- On a `RouteUnavailableError` with `reason: "recipient_not_deployed"`, shows a warning that no Starknet account is deployed at the address, with an "It's my wallet, continue" button. Pressing it quotes again with `allowUndeployedRecipient: true` for that address only. +- After a successful transfer whose `customFee` is `unpaid`, the result banner says the fee was not paid, with the reason when there is one. +- Renders ``, ` ` and ` `. + +`WhiskSendProps` is the type of these props. + +## WhiskReceipt + +The status of one transfer, polled from Circle's Iris API with [useReceipt](/reference/react/hooks#usereceipt). A same-chain transfer shows as settled as soon as it has a source hash. A cross-chain transfer that has not settled gets a Finish transfer button, which calls `engine.resumeFromTx` with the connected wallet for the destination chain. Render it inside ` `: in 0.3 it reads the wallet adapters, which need the provider. Guide: [WhiskReceipt](/widget/whisk-receipt). + +```tsx Status.tsx +import { WhiskReceipt } from "@usewhisk/react"; + +export function Status({ txHash }: { txHash: string }) { + return ( + + ); +} +``` + + + Chain the transfer was sent from. + + ++ The burn (or same-chain transfer) hash. While `undefined`, the card asks for + one and does not poll. + + ++ Equal to `sourceChain` for a same-chain send. + + ++ The mint hash, when known. Marks the transfer settled and stops polling. + + ++ Forces the failed stage, for example after a `SendFailure`. Stops polling. + + ++ Defaults to `"Transfer status"`. + + ++ Shown under the chain labels. + + ++ Iris poll interval. Defaults to 3000. + + ++ Stops polling after this long. Defaults to 600000 (10 minutes). + + +`WhiskReceiptProps` is the type of these props. + +## ResumeList + +```tsx ++``` + +No props. Lists the transfers in the engine's `inflightStore` (`engine.inflight()`), each with a Resume button (`engine.resume` with the connected wallet for the destination chain) and a Dismiss button (`engine.dismiss`). Renders nothing when the store is empty. ` ` already includes it. Guide: [ResumeList](/widget/resume-list). + +## ConnectModal + +A dialog to pick an ecosystem, then a wallet in it. Ecosystems without a factory in `config.wallets` are shown disabled. While a wallet is connected it shows the account and a disconnect button. Guide: [ConnectModal](/widget/connect-modal). + + + Controlled open state. + + ++ Called to open or close. The modal closes itself after a successful connect. + + ++ Defaults to a title for the current step. + + ++ Shown under the title. + + +`ConnectModalProps` is the type of these props. + +## Primitives + +The building blocks of the widgets, for custom UIs that keep the Whisk look. Guide: [Primitives](/widget/primitives). + +```tsx CustomWidget.tsx +import { useState } from "react"; +import { + Banner, + Button, + Card, + ChainPicker, + ConnectModal, + FieldBox, + PoweredByWhisk, + ResumeList, + StepRail, + type Chain, + type Step, +} from "@usewhisk/react"; + +const steps: Step[] = [ + { name: "approve", state: "success" }, + { name: "burn", state: "pending" }, +]; + +export function CustomWidget() { + const [open, setOpen] = useState(false); + const [chain, setChain] = useState("Base_Sepolia"); + const [amount, setAmount] = useState(""); + return ( + + + ); +} +``` + +### Card + +Takes every `HTMLAttributes+ + setAmount(e.target.value)} + suffix="USDC" + help="Up to 6 decimals" + /> + + Retry}> + Waiting for Circle. + + ++ + ` prop and forwards its ref. Adds the `whisk-card` class. + +### Button + +`ButtonProps` is `ButtonHTMLAttributes ` plus the props below. Forwards its ref, and defaults `type` to `"button"` so it never submits a surrounding form. + + + `ButtonVariant`. Defaults to `"primary"`. + + ++ `ButtonSize`. Defaults to `"md"`. + + ++ Rendered before `children`. + + ++ Rendered after `children`. + + +### Banner + +`BannerProps` is `HTMLAttributes` plus the props below. The `role` defaults to `"alert"` for errors and `"status"` otherwise. + + + `BannerVariant`. Defaults to `"info"`. + + ++ Rendered before the text. + + ++ Rendered after the text, such as a retry button. + + +### ChainPicker + +A select of chain labels. `ChainPickerProps` is the type of its props. The list renders into the widget's portal, so it must be inside `` to keep the theme. + + + The selected chain. + + ++ Called with the picked chain. + + ++ The options, shown by their labels. + + ++ Defaults to `"Chain"`. + + ++ Disables the picker. + + ++ Added to the trigger. + + +### FieldBox + +A labelled input. `FieldBoxProps` is every `InputHTMLAttributes` prop except `size`, plus the props below. Forwards its ref to the ``. + + + The label, tied to the input. + + ++ Rendered after the input, such as a token tag or paste button. + + ++ Help text under the field. + + ++ Marks the field invalid (`aria-invalid`) and replaces `help`, announced with + `role="alert"`. + + ++ `"amount"` enlarges the input; `"mono"` uses the monospace font. Defaults to + `"default"`. + + +### StepRail + +Renders a `Step[]` from the engine or from `deriveReceiptView`. `StepRailProps` is the type of its props. The first `pending` step is shown as active, and a forwarded mint is labelled "(forwarder)". + ++ The steps to show, in order. + + ++ Replaces the default labels: "Approve USDC", "Transfer", "Burn on source + chain", "Confirm attestation", "Mint on destination". + + +### PoweredByWhisk + +No props. The attribution badge, styled with inline `!important` declarations so host CSS cannot hide it. `` and ` ` already render it. diff --git a/reference/react/config.mdx b/reference/react/config.mdx new file mode 100644 index 0000000..d0e21ba --- /dev/null +++ b/reference/react/config.mdx @@ -0,0 +1,521 @@ +--- +title: "Config" +description: "createWhiskConfig, every WhiskClientConfig field, the wallet factories, resolvers, theme helpers and the Tailwind preset." +--- + +`createWhiskConfig` builds the object you pass to ` `. The wallet factories (`evm`, `solana`, `stellar`, `starknet`) decide which wallet ecosystems the provider mounts. + +```tsx config.ts +import { createWhiskConfig, evm, solana } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + evm({ chains: ["Base_Sepolia", "Arc_Testnet"], appName: "My App" }), + solana({ network: "devnet" }), + ], + chains: ["Base_Sepolia", "Arc_Testnet", "Solana_Devnet"], + defaultSourceChain: "Base_Sepolia", + defaultDestinationChain: "Arc_Testnet", +}); +``` + +## createWhiskConfig + +```ts +function createWhiskConfig( + options: CreateWhiskConfigOptions, +): WhiskClientConfig; +``` + +Checks the options and returns them as a frozen `WhiskClientConfig`. `CreateWhiskConfigOptions` is the same type as `WhiskClientConfig`. + +It throws a `ConfigError` (code `CONFIG_ERROR`) when: + +- `wallets` is missing or empty. +- `chains` is missing or empty. +- `defaultSourceChain` is set and is not in `chains`. +- `defaultDestinationChain` is set and is not in `chains`. + +It does not check that the chains in `chains` belong to the same network, or that each chain has a matching wallet factory. Build the config once, outside your components: ` ` creates its engine on mount and does not pick up a new config afterwards. + +## WhiskClientConfig + +` ` passes most of these fields to `createWhisk` from `@usewhisk/core`. See [createWhisk](/reference/core/create-whisk) for how the engine uses them. + + + One factory per wallet ecosystem: `evm()`, `solana()`, `stellar()`, `starknet()`. The provider mounts an ecosystem's wallet context only when its factory is here, and ` + +` shows the other ecosystems as disabled. If two factories share a `kind`, the first one wins. + + The chains the widget offers, as chain ids such as `"Base"`, `"Arc_Testnet"` or `"Solana_Devnet"`. ` + +` lists them in its chain pickers and only offers destinations on the same network as the source. The engine itself does not restrict quotes to this list. See [Chains](/chains) for every id. + + The source chain ` + +` starts on. Must be in `chains`. Defaults to the first entry of `chains`. A `defaultSourceChain` or `sourceChain` prop on ` ` wins over it. + + The destination chain the Bridge tab starts on. Must be in `chains`. Defaults + to the first chain in `chains` that is not the source. + + ++ Accepted and passed to the engine, but it has no effect in 0.3: quotes default + to `"USDC"`, and CCTP only moves USDC. Tracked in + [usewhisk/whisk#155](https://github.com/usewhisk/whisk/issues/155). + + ++ Turns what the payer types in the recipient field into an address. Defaults to + `createDefaultResolver()`: raw addresses first, then ENS. See + [Resolvers](#resolvers) below and [Recipients](/concepts/recipients). + + ++ A merchant fee the payer pays on top of every transfer, split 90% to `recipient` and 10% to the Whisk treasury. `value` is a decimal USDC string such as `"0.25"`; `recipient` must be an EVM address. `bps` is accepted by the type but ignored. The fee transfers are only sent from EVM source wallets, with the burn in one atomic batch or after it has landed, never before. A payer who rejects a separate fee request still gets the transfer, so read `result.customFee` before you fulfil an order. See [when the fee is paid](/concepts/quotes-and-fees#when-the-fee-is-paid). + + + ++ ++ Total fee in USDC, as a decimal string. Unset, `"0"` or unparseable means no fee. + ++ Not supported. The engine ignores it. + ++ EVM address that receives the merchant's 90%. A non-EVM value makes `send` throw `ConfigError` before anything is signed. + ++ Who absorbs the CCTP protocol and Forwarder fees on a bridge. Defaults to + `"sender"`: the burn is sized up so the recipient gets the full amount. With + `"receiver"`, the payer is debited exactly the amount and the recipient gets + the amount less fees. Same-chain sends have no protocol fees. + + ++ RPC endpoints the engine tries, in order, before each chain's public defaults. + Used for balance reads, gas prices on Arc, the Standard minimum fee read, and + the mint checks during a resume. This does not configure the wallet's own + transport: pass `rpcUrls` to `evm()` for that. See [RPC](/rpc). + + ++ Lets Circle's Forwarding Service submit the destination mint on bridges where + it can. Defaults to `true`. Set it to `false` and a connected wallet signs the + mint on the destination chain (the source wallet for an EVM to EVM bridge). + + ++ Stored on the config and passed to the engine. Nothing in 0.3 reads it. + + ++ Where the engine keeps a bridge between the burn and the mint, so a reload can + resume it. Defaults to `createBrowserInflightStore()`, which uses + `localStorage`. See [InflightStore](/reference/core/types#inflight-records). + + +### Engine options the React config does not expose + +`createWhisk` in `@usewhisk/core` takes three options that `WhiskClientConfig` has no field for yet, so a `` engine always runs with their defaults: + +| Option | Default in the provider | +| ------------------- | ---------------------------------- | +| `forwarderFeeLevel` | `"high"`, or `"med"` into Ethereum | +| `defaultMetadata` | none | +| `fetch` | the global `fetch` | + +Tracked in [usewhisk/whisk#156](https://github.com/usewhisk/whisk/issues/156). Per-call `metadata` still works through `useWhisk().send`. + +## Wallet factories + +Each factory returns a `WalletAdapterFactory` with a `kind` and an opaque `config`. The union is: + +```ts +type WalletAdapterFactory = + | EvmAdapterFactory // { kind: "evm"; config: unknown } + | SolanaAdapterFactory // { kind: "solana"; config?: unknown } + | StellarAdapterFactory // { kind: "stellar"; config: unknown } + | StarknetAdapterFactory; // { kind: "starknet"; config: unknown } +``` + +The `config` of `evm()` is a wagmi `Config`. The others hold the `SolanaConfig`, `StellarConfig` and `StarknetConfig` shapes below. + +```ts config.ts +import { createWhiskConfig, evm, stellar, starknet } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + evm({ + chains: ["Base", "Arc"], + projectId: "your-walletconnect-project-id", + rpcUrls: { + Base: ["https://base.example-rpc.com", "https://mainnet.base.org"], + }, + }), + stellar({ network: "public" }), + starknet({ network: "mainnet" }), + ], + chains: ["Base", "Arc", "Stellar", "Starknet"], + rpcUrls: { Base: "https://base.example-rpc.com" }, + feePolicy: { + value: "0.25", + recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + }, + feeBearer: "sender", +}); +``` + + + The Solana, Stellar and Starknet factories default to their test networks. + Pass `network` for mainnet, or the wallet will be checked against the wrong + network. + + +### evm + +```ts +function evm(options?: EvmFactoryOptions): EvmAdapterFactory; +``` + +Builds a wagmi config with the injected, Coinbase Wallet and (with a `projectId`) WalletConnect connectors, and `ssr: true`. If a `` is already mounted above ` `, the provider uses that one and ignores this config. + + + EVM chains the wallet may connect to and switch between. Defaults to + `["Arc_Testnet", "Ethereum_Sepolia", "Base_Sepolia"]`. Chains the factory has + no wagmi chain for are dropped: in 0.3 that is Edge, Injective, Morph, Pharos, + Cronos, Plasma and X Layer (mainnet and testnet). If nothing is left, it falls + back to Ethereum Sepolia, because wagmi needs at least one chain. + + ++ WalletConnect Cloud project id. Without it the WalletConnect connector is left + out. + + ++ The wallet's RPC transport per chain. A string is a single `http` transport; + an array becomes a viem `fallback` ranked by latency. Chains without an entry + use viem's default public RPC. + + ++ Shown in the WalletConnect and Coinbase Wallet pairing dialogs. Defaults to + `"Whisk"`. + + +### solana + +```ts +function solana(options?: SolanaFactoryOptions): SolanaAdapterFactory; +``` + +Mounts `@solana/wallet-adapter-react` with no bundled wallet adapters; wallets announce themselves through Wallet Standard. + ++ `SolanaNetwork`. Defaults to `"devnet"`. `useSolanaAdapter` reports any value + other than `"mainnet-beta"` as the `devnet` cluster. + + ++ Solana RPC endpoint. Defaults to the public endpoint for the network + (`https://api.mainnet-beta.solana.com`, `https://api.devnet.solana.com` or + `https://api.testnet.solana.com`), which is rate limited. + + ++ Reconnect the last wallet on load. Defaults to `false`. + + +`SolanaConfig` is the resolved shape: `{ network: SolanaNetwork; endpoint: string; autoConnect: boolean }`. + +### stellar + +```ts +function stellar(options?: StellarFactoryOptions): StellarAdapterFactory; +``` + +Stellar wallets come from `@creit.tech/stellar-wallets-kit`. + ++ `StellarNetwork`. Defaults to `"testnet"`. + + ++ Soroban RPC URL. Defaults to `https://mainnet.sorobanrpc.com` on `public` and + `https://soroban-testnet.stellar.org` on `testnet`. + + ++ Defaults to `"Public Global Stellar Network ; September 2015"` or `"Test SDF + Network ; September 2015"`. + + ++ Reserved. Defaults to `false`; ` + +`StellarConfig` is the resolved shape: `{ network: StellarNetwork; networkPassphrase: string; rpcUrl: string; autoConnect: boolean }`. + +### starknet + +```ts +function starknet(options?: StarknetFactoryOptions): StarknetAdapterFactory; +``` + +Starknet wallets come from `@starknet-io/get-starknet-core`. The RPC is polled to confirm transactions. + +` does not read it. + + `StarknetNetwork`. Defaults to `"sepolia"`. + + ++ Starknet RPC. Defaults to the first public RPC of the `Starknet` or + `Starknet_Sepolia` chain entry. + + ++ Chain id felt compared with the wallet's. Defaults to `0x534e5f4d41494e` + (`SN_MAIN`) or `0x534e5f5345504f4c4941` (`SN_SEPOLIA`). + + ++ Reserved. Defaults to `false`; ` + +`StarknetConfig` is the resolved shape: `{ network: StarknetNetwork; chainId: string; rpcUrl: string; autoConnect: boolean }`. + +## createBrowserInflightStore + +```ts +function createBrowserInflightStore(): InflightStore; +``` + +The default `inflightStore`. It returns a store backed by `localStorage` when the page can write to it, and an in-memory store otherwise (server rendering, Safari private browsing). The memory store lasts until the page closes, so a reload in those cases loses the record of a transfer between burn and mint. The burn hash still lets you finish it with `resumeFromTx`. Records are kept under `whisk:inflight:` does not read it. + `. + +Only the main `@usewhisk/react` entry exports it; `@usewhisk/react/headless` does not. + +## Resolvers + +```ts config.ts +import { + composeResolvers, + addressResolver, + createBrowserInflightStore, + createEnsResolver, + createWhiskConfig, + evm, +} from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Arc_Testnet", "Ethereum_Sepolia", "Base_Sepolia"], + resolver: composeResolvers([ + addressResolver, + createEnsResolver({ + chain: "sepolia", + rpcUrl: "https://sepolia.example-rpc.com", + }), + ]), + inflightStore: createBrowserInflightStore(), +}); +``` + +### createDefaultResolver + +```ts +function createDefaultResolver( + options?: CreateDefaultResolverOptions, +): Resolver; +const defaultResolver: Resolver; // createDefaultResolver() +``` + +Raw addresses first, then ENS. For a testnet destination it tries Sepolia ENS, then mainnet ENS; for a mainnet destination, mainnet ENS only. `CreateDefaultResolverOptions` is `EnsResolverOptions` without `chain`, and applies to every ENS resolver inside. + +```ts +import { createDefaultResolver } from "@usewhisk/react"; + +export const resolver = createDefaultResolver({ + rpcUrl: [ + "https://eth.example-rpc.com", + "https://ethereum-rpc.publicnode.com", + ], + fallbackToEthAddress: false, +}); +``` + +### createEnsResolver + +```ts +function createEnsResolver(options?: EnsResolverOptions): Resolver; +const ensResolver: Resolver; // mainnet ENS +const sepoliaEnsResolver: Resolver; // Sepolia ENS +``` + +Matches any input ending in `. ` and looks the name up on Ethereum L1 with ENSIP-11 coin types: 60 for Ethereum, `0x80000000 | chainId` for other EVM chains, 501 for Solana. Stellar and Starknet have no coin type, so the resolver returns `null` for them without a lookup. Returns `null` when the name has no usable address. An RPC failure throws `ResolverError`. + + + Use `@usewhisk/react` 0.3.0 or later. Before 0.3.1 an ENS name resolved to its + Ethereum address for a Starknet destination, which is not the owner's Starknet + account. Up to 0.2.1 it was accepted; from 0.2.2 the quote refuses it, before + the burn. + + ++ `EnsResolverChain`: which ENS deployment to query. Defaults to `"mainnet"`. + + ++ One URL, or several tried through viem's `fallback` ranked by latency. An + empty array uses the defaults. Defaults to `DEFAULT_ENS_RPC_URLS` or + `DEFAULT_ENS_SEPOLIA_RPC_URLS`, public endpoints chosen because they allow + browser CORS. + + ++ A viem public client to reuse. When set, `rpcUrl` is ignored. + + ++ For an EVM destination other than Ethereum, use the name's Ethereum (coin type + 60) address when it has none for the destination chain. Defaults to `true`. + + +`addressResolver` and `composeResolvers` come from `@usewhisk/core` and are documented under [Resolver](/reference/core/types#resolvers). + +## Theme + +`` takes a `WhiskThemeInput`. These helpers are what the provider uses to turn it into CSS variables, exported for palette pickers and server rendering. Only the main `@usewhisk/react` entry exports them. See [Tokens](/theming/tokens) for every variable. + +```ts +import { + getThemePreset, + listThemeNames, + resolveTheme, + themeToCssVars, + tokensToCssVars, + type WhiskTheme, +} from "@usewhisk/react"; + +const names = listThemeNames(); +const wine: WhiskTheme = getThemePreset("wine"); +const vars = themeToCssVars({ ...wine, primary: "#2b3cff" }); +const partial = tokensToCssVars({ radius: "4px", font: "Inter, sans-serif" }); +const resolved = resolveTheme({ + preset: "dark", + tokens: { primary: "#2b3cff" }, +}); +``` + +| Export | Signature | Returns | +| ----------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `themePresets` | `Record ` | The six built-in palettes. | +| `getThemePreset` | `(name: WhiskThemeName) => WhiskTheme` | One preset. | +| `listThemeNames` | `() => WhiskThemeName[]` | `["light", "dark", "wine", "indigo", "emerald", "monochrome"]`. | +| `resolveTheme` | `(input: WhiskThemeInput \| undefined) => ResolvedTheme \| null` | `null` for `undefined` or `"auto"`. For `"light"` and `"dark"`, only the colour mode (their values are in `styles.css`). Otherwise the colour mode and the variables to set inline. | +| `themeToCssVars` | `(theme: WhiskTheme) => Record ` | `--whisk-*` variables for a full theme. `cardFg` defaults to `fg`, `ring` to `primary`; other unset optional tokens are left out. | +| `tokensToCssVars` | `(tokens: WhiskThemeTokens) => Record ` | Variables for whichever tokens are set. | + +### Theme types + + + The built-in palette names. + + ++ Sets the `data-whisk-theme` attribute and, for `"dark"`, the `dark` class on + the root element. + + ++ What ` + +` accepts. `"auto"` follows `prefers-color-scheme` in CSS alone, so it renders the same on the server. + + A preset, or `"auto"`, with some tokens replaced. + + +>'} +> + Any subset of a theme's tokens. + + ++ The output of `resolveTheme`. `colorMode` is absent for `{ preset: "auto" }`. + + ++ A full theme. + + + +## Tailwind preset + +`@usewhisk/react/tailwind` exports `whiskTheme(options?: WhiskThemeOptions)`, also as the default export. It maps the `--whisk-*` variables to Tailwind colours (`whisk-bg`, `whisk-fg`, `whisk-fg-muted`, `whisk-card`, `whisk-card-fg`, `whisk-border`, `whisk-input`, `whisk-ring`, `whisk-primary`, `whisk-primary-fg`, `whisk-success`, `whisk-warning`, `whisk-destructive`, `whisk-destructive-fg`), radii (`whisk`, `whisk-sm`, `whisk-lg`) and fonts (`whisk`, `whisk-mono`). The variables themselves still come from `styles.css`. + +```ts tailwind.config.ts +import { whiskTheme } from "@usewhisk/react/tailwind"; + +export default { + presets: [whiskTheme({ prefix: "whisk" })], + content: ["./src/**/*.{ts,tsx}"], +}; +``` + ++ +Light or dark. +`--whisk-bg`, the widget background. +`--whisk-fg`, primary text. +`--whisk-border`. +`--whisk-input`, input background. +`--whisk-card`. +`--whisk-card-fg`. Defaults to `fg`. +`--whisk-primary`, buttons and accents. +`--whisk-primary-fg`. +`--whisk-success`. +`--whisk-warning`. +`--whisk-destructive`. +`--whisk-destructive-fg`. +`--whisk-fg-muted`. The stylesheet derives it from `fg` when unset. +`--whisk-ring`, the focus ring. Defaults to `primary`. +`--whisk-radius`, fields and buttons. +`--whisk-radius-sm`. +`--whisk-radius-md`. +`--whisk-radius-lg`, cards. +`--whisk-border-w`. +`--whisk-font`. +`--whisk-font-display`. +`--whisk-font-mono`. ++ Prefix for every generated key. Defaults to `"whisk"`. + + +See [Tailwind](/theming/tailwind). + +## Entry points + +| Entry | Contents | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@usewhisk/react` | Everything on the React reference pages, plus the `@usewhisk/core` re-exports below. | +| `@usewhisk/react/headless` | The provider, config builders, wallet factories, hooks, resolvers and core re-exports. No components, no theme helpers, no `createBrowserInflightStore`, no CSS. | +| `@usewhisk/react/tailwind` | `whiskTheme` and `WhiskThemeOptions`. | +| `@usewhisk/react/styles.css` | The widget stylesheet. | + +Both JavaScript entries re-export these from `@usewhisk/core`, documented there: + +- Engine types: `WhiskEngine`, `WhiskAdapter`, `EvmAdapter`, `EvmCall`, `CallReceipt`, `SendCallsOptions`, `SendCallsResult`, `QuoteParams`, `SendParams`, `SendListeners`, `SendStepListener`, `SendResult`, `SendSuccess`, `SendFailure`, `MaxSendable`, `ResumeOptions`, `ResumeFromTxParams`, `RefundParams`, `RefundResult`. See [Engine](/reference/core/engine). +- Errors: every error class, `toWhiskError`, `cleanErrorMessage`, `WhiskErrorCode`, `WhiskErrorCategory`, `WhiskErrorOptions`, `RouteUnavailableReason`. See [Errors](/reference/core/errors). +- Types, helpers and constants: `Chain`, `ChainKind`, `ChainNetwork`, `Token`, `Quote`, `Route`, `RouteMint`, `RoutePlan`, `Step`, `StepName`, `StepState`, `FeeBearer`, `FeeBreakdown`, `FeeEntry`, `FeeEntryKind`, `FeePolicy`, `Resolver`, `ResolvedRecipient`, `WhiskConfig`, `WhiskState`, `WhiskStateKind`, `DEFAULT_FEE_BEARER`, `DEFAULT_TOKEN`, `isBridgeRoute`, `isSendRoute`, `planRoute`, `addressResolver`, `composeResolvers`, the fee, chain, metadata, refund, receipt and Iris helpers, and `formatUsdcAmount`, `parseUsdcAmount`, `USDC_DECIMALS`. See [Types](/reference/core/types). + +`createWhisk`, the inflight store constructors, the state reducer, the non-EVM adapter types, `StellarTrustline`, `CustomFeeOutcome`, `decideRoute`, `connectedEcosystems`, `SOLANA_MESSAGE_TRANSMITTER`, `getStarknetTransactionStatus` and the webhook signing helpers are only in `@usewhisk/core`. diff --git a/reference/react/hooks.mdx b/reference/react/hooks.mdx new file mode 100644 index 0000000..a1f8180 --- /dev/null +++ b/reference/react/hooks.mdx @@ -0,0 +1,400 @@ +--- +title: "Hooks" +description: "Signatures, parameters and return values of every hook @usewhisk/react exports." +--- + +Call these hooks inside ``, which supplies the engine, the wallet contexts and a TanStack Query client. `useWhisk`, `useWhiskEngine`, `useWhiskContext`, `useRefund`, `useSolanaAdapter` and `useAdapterFor` throw `ConfigError` outside it. All of them are also exported from `@usewhisk/react/headless`. + +```tsx PayButton.tsx +import { useWhisk } from "@usewhisk/react"; + +export function PayButton() { + const { isConnected, resolve, quote, send, isSending, lastResult } = + useWhisk(); + + async function pay() { + const recipient = await resolve("vitalik.eth", "Base_Sepolia"); + const q = await quote({ + sourceChain: "Arc_Testnet", + destinationChain: "Base_Sepolia", + recipient, + amount: "10", + }); + const result = await send( + { quote: q }, + { onStep: (step) => console.log(step) }, + ); + if (result.kind === "failure") console.error(result.error.message); + } + + return ( + + ); +} +``` + +## useWhisk + +```ts +function useWhisk(): UseWhiskResult; +``` + +The engine, the connected EVM wallet and send state, for custom widgets. It only knows the EVM wallet: for Solana, Stellar or Starknet sources, call the engine with the adapter from [useAdapterFor](#useadapterfor). Guide: [useWhisk](/hooks/use-whisk). + + + The engine ` + +` created. See [Engine](/reference/core/engine). + + The connected wagmi account as an adapter, or `null` when no EVM wallet is + connected. + + ++ The connected EVM address. + + ++ `true` while an EVM wallet is connected. + + ++ `engine.resolve`. Throws `ConfigError` when no resolver matches the input or + none returns an address, and `ResolverError` when a resolver fails. + + +) => Promise + +'} +> + `engine.quote` with the connected EVM adapter filled in. Throws `ConfigError` + when no EVM wallet is connected, and anything `engine.quote` throws. +, listeners?: SendListeners) => Promise + +' + } +> + `engine.send` with the connected EVM adapter, run as a TanStack Query + mutation. Resolves to the `SendResult`; rejects with `ConfigError` when no + wallet is connected, and with anything `engine.send` throws + (`QuoteExpiredError`, `QuoteChangedError`, `InsufficientBalanceError`, ...). + Pass `destinationAdapter` and `metadata` in `params`. + + `true` while a `send` is running. + + ++ The latest resolved result. Check `kind`: a `"failure"` here is a transfer + that started and stopped. + + ++ Set when `send` rejected. + + ++ Clears `lastResult` and `sendError`. + + +`UseWhiskResult` is the type of the returned object. + +## useReceipt + +```ts +function useReceipt(input: UseReceiptInput): UseReceiptResult; +``` + +Polls Iris for one transfer and returns a [ReceiptView](/reference/core/types#receipts). A same-chain transfer never polls. A cross-chain one polls until Iris reports `complete`, `pollTimeoutMs` passes, or `destinationTxHash` or `hasError` is set. The timeout restarts only when `sourceChain` or `sourceTxHash` changes. Guide: [useReceipt](/hooks/use-receipt). + +```tsx Stage.tsx +import { useReceipt, RECEIPT_STAGE_LABELS } from "@usewhisk/react"; + +export function Stage({ txHash }: { txHash: string }) { + const { view, isLoading, error, irisStatus, message } = useReceipt({ + sourceChain: "Base_Sepolia", + sourceTxHash: txHash, + destinationChain: "Arc_Testnet", + }); + if (error) return{error.message}
; + if (isLoading || !view) returnChecking…
; + return ( ++ {RECEIPT_STAGE_LABELS[view.stage]} +
+ ); +} +``` + ++ Chain the transfer was sent from. + + ++ The burn or transfer hash. While `undefined`, nothing polls and `view` is + `null`. + + ++ Equal to `sourceChain` for a same-chain send. + + ++ The mint hash, when known. The view becomes `settled` and polling stops. + + ++ Forces the `failed` stage and stops polling. + + ++ Defaults to 3000. + + ++ Defaults to 600000 (10 minutes). + + ++ Stage, steps and explorer links. `null` without a `sourceTxHash`. + + ++ The latest Iris status. `undefined` before the first response. + + ++ The latest Iris message, with `message`, `attestation` and `eventNonce` once + available. + + ++ `true` while waiting for the first poll. + + ++ Set when a poll failed, such as on a network error. Iris errors come from + `@usewhisk/cctp` and are not `WhiskError`s. + + +`UseReceiptInput` and `UseReceiptResult` are the types of the argument and the result. + +## useRefund + +```ts +function useRefund(): UseRefundResult; +``` + +Sends a refund from the connected EVM wallet, which acts as the merchant: `engine.refund` with `merchantAdapter` set to it. It cannot pass a `destinationAdapter`, so refunds whose mint Circle does not forward (into Solana, Stellar or Starknet) need `engine.refund` directly. Guide: [useRefund](/hooks/use-refund). + +```tsx RefundButton.tsx +import { useRefund } from "@usewhisk/react"; + +export function RefundButton() { + const { refundAsync, isPending, error } = useRefund(); + + async function onClick() { + const result = await refundAsync({ + originalTxHash: "0xabc123", + originalDestinationChain: "Arc_Testnet", + refundDestinationChain: "Base_Sepolia", + originalSenderAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", + amount: "5", + reason: "Order cancelled", + metadata: { orderId: "A-1001" }, + }); + if (result.kind === "success") console.log(result.metadata); + } + + return ( + <> + + {error ?{error.message}
: null} + > + ); +} +``` + +`UseRefundVariables` is `RefundInput & { listeners?: SendListeners }`. See [RefundInput](/reference/core/types#refunds) for the fields. + ++ Starts a refund without returning a promise. The result lands on `data`, a + thrown error on `error`. + + ++ Resolves to the `RefundResult`. Rejects with `ConfigError` when no wallet is + connected or the input is invalid, and with anything `engine.refund` throws. + + ++ The latest result. Its `metadata` carries `__refundOfTxHash` and, when given, + `__refundReason`. + + ++ Set when the refund rejected. + + ++ `true` while a refund is running. + + ++ Clears `data` and `error`. + + +`UseRefundResult` is the type of the returned object. + +## useWhiskEngine + +```ts +function useWhiskEngine(): WhiskEngine; +``` + +The engine `` created. Stable for the life of the provider. Guide: [useWhiskEngine](/hooks/use-whisk-engine). + +## useWhiskContext + +```ts +function useWhiskContext(): { + engine: WhiskEngine; + config: WhiskClientConfig; + theme: WhiskThemeInput | undefined; +}; +``` + +The provider's engine, the `config` prop and the `theme` prop. Throws `ConfigError` outside ` `. + +## Wallet adapter hooks + +Each returns the connected wallet of one ecosystem as a [WhiskAdapter](/reference/core/engine#adapters), or `null` when none is connected or its factory is missing from `config.wallets`. The adapters turn wallet and RPC failures into `WhiskError`s with `toWhiskError`. Guide: [Wallet adapters](/hooks/wallet-adapters). + +```tsx useSendQuote.ts +import { + useAdapterFor, + useEvmAdapter, + useSolanaAdapter, + useStarknetAdapter, + useStellarAdapter, + useWhiskContext, + useWhiskEngine, + type Quote, +} from "@usewhisk/react"; + +export function useSendQuote() { + const engine = useWhiskEngine(); + const { config, theme } = useWhiskContext(); + const adapterFor = useAdapterFor(); + const evm = useEvmAdapter(); + const solana = useSolanaAdapter(); + const stellar = useStellarAdapter(); + const starknet = useStarknetAdapter(); + + async function send(quote: Quote) { + if (quote.route.kind !== "bridge") return; + const adapter = adapterFor(quote.route.sourceChain); + const destinationAdapter = adapterFor(quote.route.destinationChain); + if (!adapter) throw new Error("Connect a wallet on the source chain."); + return engine.send({ + quote, + adapter, + ...(destinationAdapter && { destinationAdapter }), + }); + } + + return { send, config, theme, connected: [evm, solana, stellar, starknet] }; +} +``` + +### useAdapterFor + +```ts +function useAdapterFor(): (chain: Chain) => WhiskAdapter | null; +``` + +Returns a function that picks the connected adapter for a chain's ecosystem. This is how ` ` and ` ` find the wallet that signs a mint. + +### useEvmAdapter + +```ts +function useEvmAdapter(): EvmAdapter | null; +``` + +The connected wagmi account as an `EvmAdapter`. Built with `createWagmiEvmAdapter`. + +### createWagmiEvmAdapter + +```ts +function createWagmiEvmAdapter( + wagmiConfig: Config, + address: `0x${string}`, +): EvmAdapter; +``` + +The adapter behind `useEvmAdapter`, for a wagmi `Config` you hold outside React. + +```ts +import { createConfig, http } from "wagmi"; +import { baseSepolia } from "wagmi/chains"; +import { createWagmiEvmAdapter } from "@usewhisk/react"; + +const wagmiConfig = createConfig({ + chains: [baseSepolia], + transports: { [baseSepolia.id]: http() }, +}); + +export const adapter = createWagmiEvmAdapter( + wagmiConfig, + "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1", +); +``` + +How it behaves: + +- `sendCalls` sends one transaction per call, in order, through wagmi's `sendTransaction`. It waits for each receipt before the next call (two confirmations between calls, one for the last), so a burn never races its approve. +- `supportsAtomicBatch(chainId)` reads wagmi's `getCapabilities` for the account and chain, and says yes when the wallet reports atomic batching as `supported` or `ready`. A wallet without EIP-5792, whose call fails, counts as no. +- `sendCalls(calls, { atomic: true })` sends one batch through wagmi's `sendCalls` with `forceAtomic`, waits with `waitForCallsStatus`, and reports the batch's last transaction hash as the one hash for every call. Calls that carry their own gas price, as every call on Arc does, and a wallet that refuses the batch with EIP-5792 error 5760, throw `WalletCapabilityError("atomic_unsupported")` before anything is sent, and the engine sends the calls one by one instead. +- `maxFeePerGas` and `maxPriorityFeePerGas` are passed to the wallet when the engine sets them (it does on Arc). +- A reverted transaction throws `OnchainRevertError`; a rejected prompt throws `UserRejectedError`. + +### useSolanaAdapter + +```ts +function useSolanaAdapter(): SolanaAdapter | null; +``` + +The connected Wallet Standard wallet. `getCluster()` returns `"mainnet-beta"` when `solana({ network: "mainnet-beta" })` and `"devnet"` otherwise. `sendTransaction` builds a legacy transaction with a fresh blockhash, partial-signs with the engine's extra signers, then asks the wallet to sign and send. `confirmTransaction` waits at `confirmed` and reports `slot` as `0n`. + +### useStellarAdapter + +```ts +function useStellarAdapter(): StellarAdapter | null; +``` + +The connected Stellar Wallets Kit wallet. Each invocation is simulated, signed and submitted on its own, and the next waits until the previous one succeeds, up to 60 seconds each. `getNetwork()` returns the factory's `network`. `getTrustline(account, asset)` reads the trustline ledger entry over the factory's Soroban RPC, returns `null` when there is none, and throws on an RPC failure, so a failed read never looks like a missing trustline. + +### useStarknetAdapter + +```ts +function useStarknetAdapter(): StarknetAdapter | null; +``` + +The connected Starknet wallet. `submitCalls` sends all calls as one multicall through `wallet_addInvokeTransaction`, so approve and burn land atomically. `confirmTransaction` polls the factory's RPC every 3 seconds for up to 10 minutes. diff --git a/rpc.mdx b/rpc.mdx new file mode 100644 index 0000000..b97e599 --- /dev/null +++ b/rpc.mdx @@ -0,0 +1,154 @@ +--- +title: "RPC endpoints" +description: "Which RPCs Whisk uses by default, how to set your own, and the per-ecosystem settings." +--- + +Whisk works out of the box on public RPC endpoints. For production, pass your own. On EVM chains the same map goes to two places, the engine and the wallet: + +```ts whisk.ts +import { createWhiskConfig, evm } from "@usewhisk/react"; + +const rpcUrls = { + Base: "https://base-mainnet.example.com/YOUR_KEY", + Arc: [ + "https://arc-mainnet.example.com/YOUR_KEY", + "https://arc-backup.example.com/YOUR_KEY", + ], +}; + +export const config = createWhiskConfig({ + wallets: [evm({ chains: ["Base", "Arc"], rpcUrls })], + chains: ["Base", "Arc"], + rpcUrls, +}); +``` + +Each entry is keyed by chain id and takes one URL or an array of URLs. + +## Why set your own + +The defaults are free public endpoints. They are rate limited, they fail more often than paid ones, and every app using them shares the same limits. A failing RPC does not lose funds, but it shows up as slow or failed quotes, a Max button without a balance, a confirmation that hangs, or a resume that cannot see the burn. Use a provider you pay for, or run your own node, for every chain you list on mainnet. + +Anything in your client bundle is visible to your users, RPC keys included. Use keys that your provider lets you restrict to your domain. + +## Two settings for EVM chains + +| Setting | Used by | What it reads | +| -------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `createWhiskConfig({ rpcUrls })` | The engine | USDC balances for the Max button, Arc gas prices, Standard burn minimum fees, block numbers, and burn and mint status when resuming. | +| `evm({ rpcUrls })` | wagmi, through the wallet | Transaction receipts after the wallet submits, and other wagmi reads. | + +The wallet itself broadcasts transactions through its own RPC, which Whisk does not control. + +The two settings fall back differently: + +- **Engine.** Your URLs are tried in order, then the chain's default RPCs from the registry. A URL that errors, returns an HTTP error or returns an unusable answer is skipped, and the next one is tried. The engine reaches the public defaults only when all of yours fail. +- **wagmi.** A single string becomes viem's `http(url)` transport, with no fallback. An array becomes a viem `fallback` transport ranked by latency. A chain with no entry uses viem's default public RPC for that chain. + +If you bring your own wagmi config, `evm({ rpcUrls })` has no effect; set the transports in your wagmi config instead. See [wallets](/wallets#bring-your-own-wagmi-config). + +## Default endpoints + +Every registry entry carries its defaults in `defaultRpcUrls`: + +```ts +import { getChain } from "@usewhisk/react"; + +console.log(getChain("Base").defaultRpcUrls); +console.log(getChain("Solana").defaultRpcUrls); +``` + +The full list per chain is in the [chain reference](/reference/cctp/chains). + +## Solana, Stellar and Starknet + +The non-EVM wallet factories each take their own endpoint. For Stellar and Starknet, the engine also reads the chain directly when it resumes a transfer, so set `rpcUrls` for those chains as well: + +```ts whisk.ts +import { createWhiskConfig, solana, stellar, starknet } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + solana({ + network: "mainnet-beta", + endpoint: "https://solana-mainnet.example.com/YOUR_KEY", + }), + stellar({ + network: "public", + rpcUrl: "https://soroban-mainnet.example.com/YOUR_KEY", + }), + starknet({ + network: "mainnet", + rpcUrl: "https://starknet-mainnet.example.com/YOUR_KEY", + }), + ], + chains: ["Solana", "Stellar", "Starknet", "Base"], + rpcUrls: { + Stellar: "https://soroban-mainnet.example.com/YOUR_KEY", + Starknet: "https://starknet-mainnet.example.com/YOUR_KEY", + }, +}); +``` + + + + +## ENS lookups + +The default recipient resolver looks up ENS names on Ethereum (and on Sepolia first for testnet destinations). It uses its own list of public, CORS-friendly endpoints, exported as `DEFAULT_ENS_RPC_URLS` and `DEFAULT_ENS_SEPOLIA_RPC_URLS`. To use your own, build the resolver with `rpcUrl`: + +```ts whisk.ts +import { createDefaultResolver, createWhiskConfig, evm } from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [evm({ chains: ["Base"] })], + chains: ["Base"], + resolver: createDefaultResolver({ + rpcUrl: "https://eth-mainnet.example.com/YOUR_KEY", + }), +}); +``` + +`rpcUrl` takes one URL or an array. It replaces the endpoints for both the mainnet and the Sepolia lookups, so in an app with testnet destinations it should not be a mainnet-only URL. See [recipients](/concepts/recipients). + +## Without React + +`createWhisk` in `@usewhisk/core` takes the same `rpcUrls` option as `createWhiskConfig`, with the same fallback to the registry defaults: + +```ts server.ts +import { createWhisk } from "@usewhisk/core"; + +export const engine = createWhisk({ + chains: ["Base", "Arc"], + rpcUrls: { + Base: process.env.BASE_RPC_URL, + Arc: process.env.ARC_RPC_URL, + }, +}); +``` + +On a server, your wallet adapters bring their own RPC clients. See [server usage](/headless/server). diff --git a/scripts/gen-chains-table.mjs b/scripts/gen-chains-table.mjs new file mode 100644 index 0000000..07356e1 --- /dev/null +++ b/scripts/gen-chains-table.mjs @@ -0,0 +1,30 @@ +// Prints the chain table on reference/cctp/chains.mdx from the published registry: +// npx -y -p @usewhisk/cctp@0.1.1 node scripts/gen-chains-table.mjs +// Set CCTP_ENTRY to a local build (packages/cctp/dist/index.js) to read that instead. +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; + +async function loadCctp() { + if (process.env.CCTP_ENTRY) { + return import(pathToFileURL(process.env.CCTP_ENTRY).href); + } + // npx -p puts the package on PATH, not on this script's import path. + const bin = process.env.PATH.split(":").find((p) => p.includes("_npx")); + const require = createRequire( + bin ? `${bin}/../package.json` : import.meta.url, + ); + return import(pathToFileURL(require.resolve("@usewhisk/cctp")).href); +} + +const { CHAINS } = await loadCctp(); + +const rows = [ + "| Id | Label | Ecosystem | Network | Domain | Fast source | USDC | Explorer |", + "| --- | --- | --- | --- | --- | --- | --- | --- |", +]; +for (const c of CHAINS) { + rows.push( + `| \`${c.id}\` | ${c.label} | ${c.ecosystem} | ${c.network} | ${c.cctpDomain} | ${c.capabilities.fastSource ? "yes" : "no"} | \`${c.usdc}\` | ${c.explorerUrl}${c.explorerQuery ?? ""} |`, + ); +} +console.log(rows.join("\n")); diff --git a/scripts/preflight.sh b/scripts/preflight.sh index ab8bcbc..9701631 100755 --- a/scripts/preflight.sh +++ b/scripts/preflight.sh @@ -1,5 +1,4 @@ #!/usr/bin/env bash -# Typecheck, test and build gates join when the app scaffold lands. set -euo pipefail export NVM_DIR="${NVM_DIR:-$HOME/.nvm}" @@ -12,9 +11,17 @@ if ! command -v shellcheck >/dev/null 2>&1; then exit 1 fi +# The Mintlify CLI runs through npx, not as a dependency: its own dependency tree +# carries high advisories that would fail the audit, and none of it reaches readers. +MINT="npx -y mint@4.2.993" + echo "=== Preflight ===" -echo "[1/2] Format" +echo "[1/4] Format" pnpm exec prettier --check . -echo "[2/2] Lint" +echo "[2/4] Lint" shellcheck scripts/*.sh scripts/hooks/*.sh +echo "[3/4] Mintlify build" +$MINT validate +echo "[4/4] Links" +$MINT broken-links --check-anchors echo "All preflight gates passed." diff --git a/theming/fonts.mdx b/theming/fonts.mdx new file mode 100644 index 0000000..04269a3 --- /dev/null +++ b/theming/fonts.mdx @@ -0,0 +1,99 @@ +--- +title: Fonts +description: The widget's default font stacks, the optional fonts.css that loads them, and how to use your own fonts. +--- + +The widget ships no font files by default. It names Inter, Familjen Grotesk and Geist Mono in its font stacks and uses them if your page already loads them; otherwise it falls back to system fonts. To load them, import the optional stylesheet next to the main one: + +```ts main.tsx +import "@usewhisk/react/styles.css"; +import "@usewhisk/react/fonts.css"; +``` + +## Default stacks + +From `@usewhisk/react/styles.css`: + +| Variable | Stack | Used for | +| ---------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------- | +| `--whisk-font` | `"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` | All widget text. | +| `--whisk-font-display` | `"Familjen Grotesk", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif` | Not read by any 0.3 component. | +| `--whisk-font-mono` | `"JetBrains Mono", "Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace` | Addresses, transaction hashes, the recipient field. | + +`JetBrains Mono` comes first in the mono stack, so a page that already loads it gets JetBrains Mono, not Geist Mono. + +## `fonts.css` + +`@usewhisk/react/fonts.css` declares `@font-face` rules for the three families, served from jsDelivr from Fontsource's variable-font packages, pinned to version 5.3.0: + +| Family | Package | Weights | Styles | +| ---------------- | --------------------------------------------- | ---------- | -------------- | +| Inter | `@fontsource-variable/inter@5.3.0` | 100 to 900 | normal, italic | +| Familjen Grotesk | `@fontsource-variable/familjen-grotesk@5.3.0` | 400 to 700 | normal | +| Geist Mono | `@fontsource-variable/geist-mono@5.3.0` | 100 to 900 | normal | + +Each face covers one Unicode range (Latin, Latin Extended, Cyrillic, Greek, Vietnamese, depending on the family), so the browser downloads only the files for the scripts on the page. Every face uses `font-display: swap`, so text shows in a fallback font while the file loads. + +It is opt-in because a widget that loads fonts on its own makes every host page send requests to a CDN. Skip it when: + +- your app already loads these fonts, or uses its own (see below), +- your Content Security Policy does not allow `cdn.jsdelivr.net` in `font-src`, +- you would rather self-host the files. + +If a font fails to load, the stack falls back to the next entry and the widget still renders. + +## Your own fonts + +Load your font the way your app already does, then point the variables at it. In a stylesheet loaded after `styles.css`: + +```css app.css +[data-whisk] { + --whisk-font: "Source Sans 3", system-ui, sans-serif; + --whisk-font-mono: "IBM Plex Mono", ui-monospace, monospace; +} +``` + +Or through the `theme` prop, with the `font`, `fontDisplay` and `fontMono` tokens: + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function App() { + return ( ++ `solana({ endpoint })` sets the RPC for the Solana connection, which Whisk uses to fetch blockhashes, confirm transactions, and read accounts (such as the recipient's USDC account before a burn into Solana). The engine reads Solana only through that connection, so `rpcUrls.Solana` is not needed. + + Default: `https://api.devnet.solana.com` for `"devnet"` and `https://api.mainnet-beta.solana.com` for `"mainnet-beta"`. Solana's public endpoints are heavily rate limited; set your own before you go to mainnet. + + ++ `stellar({ rpcUrl })` takes a Soroban RPC URL (Stellar RPC), not a Horizon URL. Whisk uses it to load the payer's account, simulate each contract call, submit it and wait for it to land. + + Default: `https://soroban-testnet.stellar.org` on testnet and `https://mainnet.sorobanrpc.com` on public. The registry's defaults, which the engine falls back to, are `https://soroban-testnet.stellar.org` on testnet and `https://soroban-rpc.mainnet.stellar.gateway.fm` then `https://mainnet.sorobanrpc.com` on mainnet. + + `rpcUrls.Stellar` on the config is what the engine uses to check whether a Stellar mint already happened when it resumes a transfer. + + ++ `starknet({ rpcUrl })` is polled for transaction receipts after the wallet submits. The chain's registry defaults are tried after it. + + Default: `https://starknet-sepolia-rpc.publicnode.com` on Sepolia and `https://starknet-rpc.publicnode.com` on mainnet. + + Whisk reads receipts with plain JSON-RPC (`starknet_getTransactionReceipt`) rather than through starknet.js, so it does not reject a node for running a newer spec version. The fields it reads are the same from Starknet RPC 0.8 to 0.10. Point it at a node that serves one of those versions. + + `rpcUrls.Starknet` on the config is what the engine uses to check whether a Starknet mint already happened when it resumes a transfer. + + ++ + ); +} +``` + +Tokens are written inline, so they win over any stylesheet. A stylesheet rule only works with the `"light"`, `"dark"` and `"auto"` themes; see [how a theme is applied](/theming/overview#how-a-theme-is-applied). + ++ + With `next/font`, pass the font's CSS variable: for example + `--whisk-font: var(--font-inter), system-ui, sans-serif;` in a stylesheet, + where `--font-inter` is the `variable` you gave `next/font`. The variable must + be defined on an element above the widget, such as `` or ``. + + +The [Tailwind preset](/theming/tailwind) exposes `--whisk-font` and `--whisk-font-mono` as `font-whisk` and `font-whisk-mono`. diff --git a/theming/overview.mdx b/theming/overview.mdx new file mode 100644 index 0000000..058856e --- /dev/null +++ b/theming/overview.mdx @@ -0,0 +1,202 @@ +--- +title: Theming +description: Pick a preset, follow the visitor's color scheme, or restyle the widget with tokens and your own CSS. +--- + +The widget's look comes from `--whisk-*` CSS variables. Choose a theme with the `theme` prop on [`WhiskProvider`](/widget/whisk-provider), then adjust it with tokens or a stylesheet. + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; +import "@usewhisk/react/styles.css"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function App() { + return ( ++ + ); +} +``` + +`@usewhisk/react/styles.css` is required. It holds the component styles and the light and dark palettes. Import it once, anywhere in your app. + +## The `theme` prop + +| Value | Result | +| --------------------- | -------------------------------------------------------------------- | +| `"light"` (default) | Cream and wine, terracotta accent. | +| `"dark"` | The same palette on a dark wine background. | +| `"auto"` | Light or dark from the visitor's `prefers-color-scheme`. | +| `"wine"` | Light, deep wine accent on warm white. | +| `"indigo"` | Light, indigo accent. | +| `"emerald"` | Light, emerald accent. | +| `"monochrome"` | Light, black and white. | +| `{ preset, tokens }` | A preset (or `"auto"`) with some [tokens](/theming/tokens) replaced. | +| a `WhiskTheme` object | Your own palette, every required color given. | + +The default is `"light"`, not `"auto"`: the widget does not follow the operating system unless you ask it to. + +`themePresets` holds the six presets as `WhiskTheme` objects, `getThemePreset(name)` returns one, and `listThemeNames()` returns their names (`"light"`, `"dark"`, `"wine"`, `"indigo"`, `"emerald"`, `"monochrome"`). `"auto"` is not a preset, so it is not in that list. + +```tsx ThemePicker.tsx +import { useState } from "react"; +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, + listThemeNames, + type WhiskThemeName, +} from "@usewhisk/react"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function ThemePicker() { + const [theme, setTheme] = useState+ ("light"); + return ( + <> + + + + > + ); +} +``` + +The `theme` prop can change at any time; only `config` is fixed at mount. + +## How a theme is applied + +The provider renders a `+ ` around your components. What it puts on that element depends on the theme: + +| Theme | `data-whisk-theme` | `class` | Inline variables | +| -------------------------------------------------- | ------------------ | --------------- | ------------------------------------- | +| `"light"` | `light` | | none | +| `"dark"` | `dark` | `dark` | none | +| `"auto"` | not set | | none | +| `"wine"`, `"indigo"`, `"emerald"`, `"monochrome"` | `light` | | every color of the preset | +| `{ preset: "light" or "dark", tokens }` | from the preset | `dark` for dark | the tokens you passed | +| `{ preset: "auto", tokens }` | not set | | the tokens you passed | +| `{ preset: "indigo", tokens }` (any named palette) | `light` | | the preset's colors, then your tokens | +| a `WhiskTheme` object | its `colorMode` | `dark` for dark | every token it sets | + +Light and dark live in `styles.css`. The light palette is the default on `[data-whisk]`. The dark palette applies in two ways: under `@media (prefers-color-scheme: dark)` when `data-whisk-theme` is not `light` (this is how `"auto"` works), and whenever `data-whisk-theme="dark"` or the `dark` class is present. Because `"auto"` is plain CSS, the server and the browser render the same markup and nothing flashes on hydration. + +The named palettes are not in the stylesheet, so the provider writes their colors as inline `style` variables. Tokens you pass are written inline too. Inline styles beat any stylesheet rule. + +`resolveTheme(theme)` returns exactly what the provider applies: `{ colorMode, vars }`, or `null` for `"auto"`. + +## Overriding with your own stylesheet + +For `"light"`, `"dark"` and `"auto"`, nothing is inline, so a rule on `[data-whisk]` in a stylesheet loaded after `styles.css` wins. Every palette block in `styles.css` has the specificity of `[data-whisk]` alone, so one plain rule overrides both light and dark: + +```css app.css +[data-whisk] { + --whisk-primary: #2b3cff; + --whisk-primary-fg: #ffffff; + --whisk-radius-lg: 0.75rem; +} +``` + +To give dark mode its own values, add a more specific rule for each way dark can apply: + +```css app.css +[data-whisk] { + --whisk-primary: #2b3cff; +} + +[data-whisk][data-whisk-theme="dark"] { + --whisk-primary: #8b95ff; +} + +@media (prefers-color-scheme: dark) { + [data-whisk]:not([data-whisk-theme="light"]) { + --whisk-primary: #8b95ff; + } +} +``` + +The first rule covers light. The second covers `theme="dark"`. The media query covers `theme="auto"` on a dark system. If you only ever use one of `"light"`, `"dark"` or `"auto"`, keep only the rules it needs. + ++ A stylesheet cannot override a value the provider writes inline. With + `"wine"`, `"indigo"`, `"emerald"` or `"monochrome"`, with a `WhiskTheme` + object, and for any token you pass in `{ preset, tokens }`, change the value + through the `theme` prop instead. + + +## Tokens from the prop + +`{ preset, tokens }` changes a few values and keeps the rest of the preset. With `preset: "auto"` the tokens apply in both light and dark: + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function App() { + return ( ++ + ); +} +``` + +Because tokens are inline, they are the same in light and dark. For a color that should differ between the two, use the stylesheet rules above. See [tokens](/theming/tokens) for every variable. + +## Dark mode in your own markup + +With `theme="dark"`, the widget root carries the `dark` class, so Tailwind's class-based `dark:` variants work inside it. See [Tailwind](/theming/tailwind). + +## Next + ++ + diff --git a/theming/tailwind.mdx b/theming/tailwind.mdx new file mode 100644 index 0000000..3cab1bf --- /dev/null +++ b/theming/tailwind.mdx @@ -0,0 +1,121 @@ +--- +title: Tailwind +description: Map the --whisk-* variables to Tailwind classes such as bg-whisk-primary, so your own markup follows the widget's theme. +--- + +`@usewhisk/react/tailwind` exports `whiskTheme`, a Tailwind preset that maps the widget's CSS variables to color, radius and font utilities. Use it when you build parts of a payment UI yourself and want them to follow the active Whisk theme. + +```ts tailwind.config.ts +import { whiskTheme } from "@usewhisk/react/tailwind"; + +export default { + content: ["./src/**/*.{ts,tsx}"], + presets: [whiskTheme()], +}; +``` + +The preset only adds class names. The values still come from `@usewhisk/react/styles.css` and the `theme` prop, so keep importing the stylesheet. + +## Classes it adds + +Every value is a `var(--whisk-…)` reference, added under `theme.extend`, so your own colors, radii and fonts are untouched. + +| Kind | Classes (with `bg-`, `text-`, `border-`, `ring-` and other color utilities) | Variable | +| ----------- | --------------------------------------------------------------------------- | ---------------------------------------------------------- | +| Colors | `whisk-bg`, `whisk-fg`, `whisk-fg-muted` | `--whisk-bg`, `--whisk-fg`, `--whisk-fg-muted` | +| | `whisk-card`, `whisk-card-fg` | `--whisk-card`, `--whisk-card-fg` | +| | `whisk-border`, `whisk-input`, `whisk-ring` | `--whisk-border`, `--whisk-input`, `--whisk-ring` | +| | `whisk-primary`, `whisk-primary-fg` | `--whisk-primary`, `--whisk-primary-fg` | +| | `whisk-success`, `whisk-warning` | `--whisk-success`, `--whisk-warning` | +| | `whisk-destructive`, `whisk-destructive-fg` | `--whisk-destructive`, `--whisk-destructive-fg` | +| Radius | `rounded-whisk`, `rounded-whisk-sm`, `rounded-whisk-lg` | `--whisk-radius`, `--whisk-radius-sm`, `--whisk-radius-lg` | +| Font family | `font-whisk`, `font-whisk-mono` | `--whisk-font`, `--whisk-font-mono` | + +There is no class for `--whisk-radius-md`, `--whisk-border-w` or `--whisk-font-display`. Use an arbitrary value such as `rounded-[var(--whisk-radius-md)]`. + +```tsx Summary.tsx +import { Card } from "@usewhisk/react"; + +export function Summary({ total }: { total: string }) { + return ( ++ Every `--whisk-*` variable and what it colors. + ++ Use the variables as Tailwind classes. + ++ The default font stack, and using your own. + ++ A full example with a brand palette. + ++ + ); +} +``` + +Total
+{total} USDC
+ + Due today + ++ The variables are defined on the `[data-whisk]` element the provider renders, + not on `:root`. These classes only resolve inside a `WhiskProvider`. Outside + it, `bg-whisk-primary` points at an undefined variable and renders nothing. + + +## A custom prefix + +`whiskTheme({ prefix })` renames every class. The default prefix is `"whisk"`. + +```ts tailwind.config.ts +import { whiskTheme } from "@usewhisk/react/tailwind"; + +export default { + content: ["./src/**/*.{ts,tsx}"], + presets: [whiskTheme({ prefix: "pay" })], +}; +``` + +This gives `bg-pay-primary`, `rounded-pay-lg`, `font-pay-mono` and so on. The CSS variables keep their `--whisk-` names. + +The preset is also the module's default export, so `import whiskTheme from "@usewhisk/react/tailwind"` works too. If you type your config, add `satisfies Config` with `Config` from `tailwindcss`. + +## Opacity + +The variables hold plain colors such as hex values, not separate channels, so Tailwind v3's opacity modifiers (`bg-whisk-primary/20`) do not apply to them. Mix the color instead: + +```html + +``` + +## Tailwind v4 + +`whiskTheme` returns a JavaScript preset in the v3 config format. Tailwind v4 reads a JavaScript config through the `@config` directive, so the same file works: + +```css app.css +@import "tailwindcss"; +@config "../tailwind.config.ts"; +``` + +The path is relative to the CSS file. If you would rather stay CSS-only in v4, declare the same mappings with `@theme inline`, which keeps the `var()` references so the classes follow the widget's theme: + +```css app.css +@import "tailwindcss"; + +@theme inline { + --color-whisk-bg: var(--whisk-bg); + --color-whisk-fg: var(--whisk-fg); + --color-whisk-fg-muted: var(--whisk-fg-muted); + --color-whisk-card: var(--whisk-card); + --color-whisk-border: var(--whisk-border); + --color-whisk-primary: var(--whisk-primary); + --color-whisk-primary-fg: var(--whisk-primary-fg); + --color-whisk-success: var(--whisk-success); + --color-whisk-warning: var(--whisk-warning); + --color-whisk-destructive: var(--whisk-destructive); + --radius-whisk: var(--whisk-radius); + --radius-whisk-lg: var(--whisk-radius-lg); + --font-whisk: var(--whisk-font); + --font-whisk-mono: var(--whisk-font-mono); +} +``` + +Add the remaining variables from the table above the same way if you use them. + +## Dark mode + +With `theme="dark"` the widget root has the `dark` class as well as `data-whisk-theme="dark"`. If your Tailwind dark mode is class-based, `dark:` variants inside the widget follow it. With `theme="auto"` there is no class; the media-query strategy (Tailwind's default) matches the widget, since both follow `prefers-color-scheme`. + +You rarely need `dark:` for Whisk colors, since the variables already switch with the theme. diff --git a/theming/tokens.mdx b/theming/tokens.mdx new file mode 100644 index 0000000..df93c9e --- /dev/null +++ b/theming/tokens.mdx @@ -0,0 +1,169 @@ +--- +title: Tokens +description: Every --whisk-* CSS variable, the theme token that sets it, and what it colors in the widget. +--- + +Each theme token maps to one `--whisk-*` CSS variable on the `[data-whisk]` element. Set tokens through the `theme` prop, or set the variables in your own stylesheet. + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function App() { + return ( ++ + ); +} +``` + +## Colors + +Defaults are the light and dark palettes in `styles.css`. Any CSS color works, since the stylesheet mixes colors with `color-mix(in srgb, …)` rather than splitting them into channels (Safari 16.4+, Chrome 111+, Firefox 113+). + +| Token | CSS variable | Light | Dark | What it colors | +| --------------- | ------------------------ | ----------- | ----------- | ---------------------------------------------------------------------------------- | +| `bg` | `--whisk-bg` | `#cdc3a3` | `#2a1d21` | Field, banner and chip backgrounds; the base the tints are mixed into. | +| `fg` | `--whisk-fg` | `#56363d` | `#e4e2d4` | Body text, values, input text. | +| `fgMuted` | `--whisk-fg-muted` | `fg` at 75% | `fg` at 75% | Labels, help text, placeholders, the attribution line. | +| `card` | `--whisk-card` | `bg` | `#33232a` | The card background. | +| `cardFg` | `--whisk-card-fg` | `fg` | `fg` | Text color set on the card. | +| `border` | `--whisk-border` | `#b09382` | `#5c3f46` | Borders of the card, fields, banners and dividers. | +| `input` | `--whisk-input` | `border` | `#5c3f46` | Border of the `.whisk-input` class. No 0.3 component uses it; fields use `border`. | +| `ring` | `--whisk-ring` | `primary` | `primary` | Focus ring on buttons and fields. | +| `primary` | `--whisk-primary` | `#d65c3c` | `#d65c3c` | Primary buttons, the active step's dot, focus outlines. | +| `primaryFg` | `--whisk-primary-fg` | `#fbf8ee` | `#fbf8ee` | Text on primary buttons, the check in a finished step. | +| `success` | `--whisk-success` | `#6b8e4e` | `#87a468` | Finished steps, the connected-network dot, success badges. | +| `warning` | `--whisk-warning` | `#d69a3c` | `#e1a854` | Warning banners (fee rise, unfinished transfers). | +| `destructive` | `--whisk-destructive` | `#b23a3a` | `#c84a4a` | Error banners, invalid fields, error text, failed steps. | +| `destructiveFg` | `--whisk-destructive-fg` | `#fbf8ee` | `#fbf8ee` | The cross in a failed step. | + +## Shape and type + +These are the same in light and dark. + +| Token | CSS variable | Default | What it sets | +| ------------- | ---------------------- | --------------------------------------- | --------------------------------------------------- | +| `radius` | `--whisk-radius` | `0.625rem` | Fields, buttons, banners. | +| `radiusSm` | `--whisk-radius-sm` | `0.375rem` | Badges. | +| `radiusMd` | `--whisk-radius-md` | `0.625rem` | Tabs, the quote summary, dropdown menus. | +| `radiusLg` | `--whisk-radius-lg` | `1rem` | The card and the connect dialog. | +| `borderWidth` | `--whisk-border-w` | `0.5px` | Card, field and banner borders. | +| `font` | `--whisk-font` | `"Inter", -apple-system, …, sans-serif` | All widget text. | +| `fontDisplay` | `--whisk-font-display` | `"Familjen Grotesk", "Inter", …` | Defined, but not read by any 0.3 component. | +| `fontMono` | `--whisk-font-mono` | `"JetBrains Mono", "Geist Mono", …` | Addresses, transaction hashes, the recipient field. | + +`radiusMd` has the same default as `radius` but is a separate variable: changing `radius` does not change it. See [fonts](/theming/fonts) for the full stacks. + +## In a stylesheet + +Set the variables on `[data-whisk]` in a stylesheet loaded after `@usewhisk/react/styles.css`. This works with `"light"`, `"dark"` and `"auto"`, which write no variables inline. + +```css app.css +[data-whisk] { + --whisk-bg: #ffffff; + --whisk-card: #ffffff; + --whisk-fg: #111827; + --whisk-border: #e5e7eb; + --whisk-primary: #2b3cff; + --whisk-primary-fg: #ffffff; + --whisk-radius: 0.5rem; + --whisk-radius-md: 0.5rem; + --whisk-radius-lg: 0.75rem; + --whisk-border-w: 1px; +} +``` + +Some variables default to another one: `--whisk-card` to `--whisk-bg` in light, `--whisk-card-fg` to `--whisk-fg`, `--whisk-ring` to `--whisk-primary`, and `--whisk-fg-muted` to `--whisk-fg` at 75%. Overriding the source moves those with it unless you set them too. The dark palette sets `--whisk-card` and `--whisk-input` to their own values. + +For separate light and dark values, see [overriding with your own stylesheet](/theming/overview#overriding-with-your-own-stylesheet). + +## Through the `theme` prop + +### `{ preset, tokens }` + +Takes any subset of the tokens above (`WhiskThemeTokens`). `preset` is a preset name or `"auto"`. The tokens are written as inline variables on top of the preset, so they beat any stylesheet, and they apply to light and dark alike. + +### A full `WhiskTheme` + +For a palette of your own, pass a `WhiskTheme`. These fields are required: `colorMode` (`"light"` or `"dark"`), `bg`, `fg`, `border`, `input`, `card`, `primary`, `primaryFg`, `success`, `warning`, `destructive`, `destructiveFg`. The rest are optional; `cardFg` defaults to `fg` and `ring` to `primary`, and the others keep their `styles.css` defaults. + +```tsx App.tsx +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, + type WhiskTheme, +} from "@usewhisk/react"; + +const brand: WhiskTheme = { + colorMode: "dark", + bg: "#0b1020", + fg: "#e6e9f2", + border: "#27304a", + input: "#1a2238", + card: "#11182c", + primary: "#7c9cff", + primaryFg: "#0b1020", + success: "#4ade80", + warning: "#fbbf24", + destructive: "#f87171", + destructiveFg: "#0b1020", + fontMono: '"IBM Plex Mono", ui-monospace, monospace', +}; + +const config = createWhiskConfig({ + wallets: [evm()], + chains: ["Base_Sepolia"], +}); + +export function App() { + return ( ++ + + ); +} +``` + +`colorMode` sets `data-whisk-theme`, and `"dark"` also adds the `dark` class. Every color is written inline, so a full theme looks the same whatever the visitor's system setting. + +## Converting tokens to variables + +`themeToCssVars(theme)` turns a `WhiskTheme` into the variable map the provider writes, filling `cardFg` and `ring` from `fg` and `primary`. `tokensToCssVars(tokens)` does the same for a partial set and leaves out anything unset. + +```ts vars.ts +import { + getThemePreset, + themeToCssVars, + tokensToCssVars, +} from "@usewhisk/react"; + +const all = themeToCssVars(getThemePreset("emerald")); +const some = tokensToCssVars({ primary: "#10b981", radiusLg: "1.25rem" }); + +console.log(all["--whisk-bg"], some); +``` + +Both return a `Record+ ` keyed by variable name, such as `{ "--whisk-primary": "#10b981", "--whisk-radius-lg": "1.25rem" }`. Use them to style your own `[data-whisk]` element, generate a stylesheet at build time, or preview a palette. diff --git a/wallets.mdx b/wallets.mdx new file mode 100644 index 0000000..8831e21 --- /dev/null +++ b/wallets.mdx @@ -0,0 +1,297 @@ +--- +title: "Wallets" +description: "Configure the evm(), solana(), stellar() and starknet() wallet factories, or bring your own wagmi config." +--- + +Each wallet ecosystem is turned on by a factory in `config.wallets`. Pass the factories for the ecosystems you accept and leave the others out: + +```ts whisk.ts +import { + createWhiskConfig, + evm, + solana, + stellar, + starknet, +} from "@usewhisk/react"; + +export const config = createWhiskConfig({ + wallets: [ + evm({ chains: ["Base_Sepolia", "Arc_Testnet"] }), + solana(), + stellar(), + starknet(), + ], + chains: [ + "Base_Sepolia", + "Arc_Testnet", + "Solana_Devnet", + "Stellar_Testnet", + "Starknet_Sepolia", + ], +}); +``` + +`WhiskProvider` mounts an ecosystem's wallet provider only when its factory is present, so an EVM-only app never starts the Solana, Stellar or Starknet code. Any single factory is enough: a config with only `solana()` is valid. `createWhiskConfig` throws a `ConfigError` when `wallets` is empty. + +The connect modal lists all four ecosystems and disables the ones without a factory. + +## Which wallet pays, and which one mints + +The wallet that pays is the one on the source chain's ecosystem. A bridge from Base Sepolia is paid by the EVM wallet; a bridge from Solana Devnet by the Solana wallet. + +The mint on the destination is submitted by Circle's Forwarding Service when the destination is an EVM chain that Circle forwards to and the source is an EVM chain or Solana. Every other route needs a wallet connected on the destination too, which signs the mint: + +- any bridge into Solana, Stellar or Starknet +- any bridge out of Stellar or Starknet +- bridges into the EVM chains Circle does not forward to (see [chains](/chains)) + +The widget tells the payer which wallet to connect. With the engine directly, `quote` throws `RouteUnavailableError` with `reason: "destination_adapter_required"` until you pass a `destinationAdapter`. See [recipients](/concepts/recipients) and [errors](/concepts/errors). + +## EVM: `evm()` + +```ts +import { evm } from "@usewhisk/react"; + +export const wallet = evm({ + chains: ["Base", "Arbitrum", "Arc"], + projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, + appName: "My Store", + rpcUrls: { + Base: "https://base-mainnet.example.com/YOUR_KEY", + Arbitrum: [ + "https://arb-mainnet.example.com/YOUR_KEY", + "https://arb1.arbitrum.io/rpc", + ], + }, +}); +``` + +`evm()` builds a wagmi config for you. Its options (`EvmFactoryOptions`): + + + EVM chains the wallet can switch to. Defaults to `["Arc_Testnet", + "Ethereum_Sepolia", "Base_Sepolia"]`. List every EVM chain in your + `config.chains`, or the widget cannot switch the wallet to it. + + ++ Your WalletConnect Cloud project ID, free at cloud.walletconnect.com. Without + it the WalletConnect connector is left out; browser wallets and Coinbase + Wallet still work. + + ++ Shown in the WalletConnect and Coinbase Wallet pairing dialogs. Defaults to + `"Whisk"`. + + ++ RPC endpoints for wagmi, per chain. An array becomes a viem `fallback` + transport ranked by latency. Chains without an entry use viem's default public + RPC. See [RPC endpoints](/rpc). + + +Wallets offered: browser wallets through wagmi's `injected` connector (MetaMask, Rabby and other EIP-6963 wallets), Coinbase Wallet, and WalletConnect when `projectId` is set. + ++ `evm()` has wallet definitions for 36 of the 50 EVM chain ids. It has none for + `Cronos`, `Edge`, `Injective`, `Morph`, `Pharos`, `Plasma`, `X_Layer` and + their testnets, and drops them from `chains` without an error. The widget + cannot switch a wallet to those chains. To pay from one of them, bring your + own wagmi config that defines it (below). + + +### Bring your own wagmi config + +If your app already has a `WagmiProvider`, put `WhiskProvider` inside it. Whisk detects the outer provider and uses your wagmi config, connectors and transports instead of its own. An outer `QueryClientProvider` is reused the same way. + +```tsx App.tsx +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { WagmiProvider, createConfig, http } from "wagmi"; +import { base, arbitrum } from "wagmi/chains"; +import { injected } from "wagmi/connectors"; +import { + WhiskProvider, + WhiskSend, + createWhiskConfig, + evm, +} from "@usewhisk/react"; + +const wagmiConfig = createConfig({ + chains: [base, arbitrum], + connectors: [injected()], + transports: { [base.id]: http(), [arbitrum.id]: http() }, +}); + +const queryClient = new QueryClient(); + +const whiskConfig = createWhiskConfig({ + wallets: [evm()], + chains: ["Base", "Arbitrum"], +}); + +export function App() { + return ( ++ + ); +} +``` + +Keep `evm()` in `wallets`: it turns on the EVM row in the connect modal. Its own wagmi config is not used when an outer `WagmiProvider` exists, so its options have no effect. Your wagmi config must include every EVM chain in `config.chains`. + +## Solana: `solana()` + +```ts +import { solana } from "@usewhisk/react"; + +export const devnet = solana(); + +export const mainnet = solana({ + network: "mainnet-beta", + endpoint: "https://solana-mainnet.example.com/YOUR_KEY", + autoConnect: true, +}); +``` + ++ ++ ++ + Defaults to `"devnet"`. Use `"devnet"` with `Solana_Devnet` and + `"mainnet-beta"` with `Solana`. CCTP has no Solana testnet cluster in the + registry. + + ++ The RPC the Solana connection uses. Defaults to the public endpoint for the + network (`https://api.devnet.solana.com` or + `https://api.mainnet-beta.solana.com`), which is rate limited. + + ++ Reconnect the last Solana wallet on page load. Defaults to `false`. + + +Wallets offered: any wallet that registers through Wallet Standard, such as Phantom, Solflare and Backpack. Whisk bundles no per-wallet adapters. + +On a bridge into Solana, Whisk checks before the burn that the connected Solana wallet is on the destination's cluster and that the recipient already has a USDC token account. Without one, the route is refused with `RouteUnavailableError` (`reason: "recipient_account_missing"`), because the mint cannot create the account and the USDC would wait until someone did. + +## Stellar: `stellar()` + +```ts +import { stellar } from "@usewhisk/react"; + +export const testnet = stellar(); + +export const pubnet = stellar({ + network: "public", + rpcUrl: "https://soroban-mainnet.example.com", +}); +``` + ++ Defaults to `"testnet"`. Use `"testnet"` with `Stellar_Testnet` and `"public"` + with `Stellar`. + + ++ The Soroban RPC used to simulate and submit the payer's transactions. Defaults + to `https://soroban-testnet.stellar.org` on testnet and + `https://mainnet.sorobanrpc.com` on public. + + ++ Defaults to Stellar's standard passphrase for the network. Change it only for + a custom network. + + ++ Accepted, but `WhiskProvider` does not read it in 0.3. + + +Wallets offered, through Stellar Wallets Kit: Freighter, Albedo, xBull, LOBSTR, Hana, Rabet and HOT Wallet. + +## Starknet: `starknet()` + +```ts +import { starknet } from "@usewhisk/react"; + +export const sepolia = starknet(); + +export const mainnet = starknet({ + network: "mainnet", + rpcUrl: "https://starknet-mainnet.example.com/YOUR_KEY", +}); +``` + ++ Defaults to `"sepolia"`. Use `"sepolia"` with `Starknet_Sepolia` and + `"mainnet"` with `Starknet`. + + ++ Polled for transaction receipts. Defaults to the registry's public endpoint + (`https://starknet-sepolia-rpc.publicnode.com` or + `https://starknet-rpc.publicnode.com`). + + ++ The chain id felt compared with the wallet's. Defaults to `SN_SEPOLIA` or + `SN_MAIN`. + + ++ Accepted, but `WhiskProvider` does not read it in 0.3. + + +Wallets offered, through get-starknet: installed Starknet wallets such as Argent X and Braavos. Wallets in get-starknet's discovery list that are not installed are shown with a link to install them. + +## Match the factory network to your chains + +The Solana, Stellar and Starknet factories each serve one network, fixed when the provider mounts. On a bridge into Solana, Stellar or Starknet, the destination wallet's cluster, network or chain id is checked before the burn. `stellar()` with no options is on testnet, so a config whose chains include `Stellar` (mainnet) needs `stellar({ network: "public" })`. + ++ If the factory is on the wrong network for the destination, a bridge into + Solana, Stellar or Starknet fails with `WrongChainError` before anything is + signed, so the payer cannot complete it at all. Configure the factory for the + network of the chains you list, and test each route on testnet first. + + +On a bridge into Stellar, the destination wallet also reads the recipient's USDC trustline through Soroban RPC before the burn, and a `G` or `M` recipient without an authorized trustline with room for the amount is refused. A quote into Starknet reads the recipient's account over `createWhiskConfig({ rpcUrls })` for that chain and then the registry's defaults, not over the `starknet()` factory's `rpcUrl`. See [recipients](/concepts/recipients). + +## Reading the connected wallets + +Each ecosystem has a hook that returns its connected wallet as an adapter, or `null`. `useAdapterFor()` returns a function that picks the adapter for a chain. + +```tsx Wallets.tsx +import { + useAdapterFor, + useEvmAdapter, + useSolanaAdapter, + useStarknetAdapter, + useStellarAdapter, +} from "@usewhisk/react"; + +export function ConnectedWallets() { + const evm = useEvmAdapter(); + const solana = useSolanaAdapter(); + const stellar = useStellarAdapter(); + const starknet = useStarknetAdapter(); + const adapterFor = useAdapterFor(); + const payer = adapterFor("Base_Sepolia"); + return ( ++
+ ); +} +``` + +See [wallet adapters](/hooks/wallet-adapters) for passing them to the engine, and [ConnectModal](/widget/connect-modal) to open the wallet picker outside the widget. diff --git a/widget/connect-modal.mdx b/widget/connect-modal.mdx new file mode 100644 index 0000000..c5fee2a --- /dev/null +++ b/widget/connect-modal.mdx @@ -0,0 +1,119 @@ +--- +title: ConnectModal +description: The wallet picker from WhiskSend on its own, for connecting EVM, Solana, Stellar and Starknet wallets from your own button. +--- + +`ConnectModal` is the dialog `WhiskSend` opens from its "Connect wallet" button. Render it yourself to connect wallets from anywhere in your app, such as a header button. You control whether it is open. + +```tsx ConnectButton.tsx +import { useState } from "react"; +import { Button, ConnectModal } from "@usewhisk/react"; + +export function ConnectButton() { + const [open, setOpen] = useState(false); + return ( + <> + +- EVM: {evm?.address ?? "not connected"}
+- Solana: {solana?.address ?? "not connected"}
+- Stellar: {stellar?.address ?? "not connected"}
+- Starknet: {starknet?.address ?? "not connected"}
+- Pays on Base Sepolia: {payer?.address ?? "nobody yet"}
++ > + ); +} +``` + +It must be inside a [`WhiskProvider`](/widget/whisk-provider). The dialog renders into the provider's portal element, so it keeps the widget's theme wherever you render the trigger. + +## Props + + + Whether the dialog is open. + + ++ Called with `false` when the payer closes the dialog (close button, Escape, + overlay click) and after a wallet connects or disconnects. + + ++ Replaces the heading. By default it follows the step: "Connect a wallet", then + "EVM wallet" (or "Solana wallet", and so on), or "Connected" while a wallet is + connected. + + ++ Shown under the heading on every step. + + +## How it works + ++ + +Where each list comes from: + +| Ecosystem | Wallets listed | When none are found | +| --------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| EVM | The connectors in your wagmi config (with `evm()`: injected browser wallets, Coinbase Wallet, and WalletConnect when you pass a `projectId`) | Asks the payer to install a browser wallet and reload. | +| Solana | Wallets that announce themselves through Wallet Standard. No per-wallet adapters are bundled. | Suggests Phantom, Solflare or Backpack. | +| Stellar | Freighter, Albedo, xBull, Lobstr, Hana and the other wallets Whisk registers with Stellar Wallets Kit. | "Loading Stellar wallets…", then suggests installing one. | +| Starknet | Wallets found by get-starknet. A wallet that is not installed opens its install page. | "Loading Starknet wallets…", then asks to install Argent X or Braavos. | + +With an outer `WagmiProvider`, the EVM list shows the connectors from your own wagmi config. + +## While a wallet is connected + +If any wallet is connected, in any ecosystem, the dialog skips the pickers. It shows each connected account (short address and the chain or wallet name) and a **Disconnect** button. Disconnect disconnects every connected wallet, then closes the dialog. If one of them fails to disconnect, the error shows and the dialog stays open. + ++ The first screen lists EVM, Solana, Stellar and Starknet. An ecosystem whose + factory (`evm()`, `solana()`, `stellar()`, `starknet()`) is not in + `config.wallets` is shown disabled with a "Coming soon" tag. + ++ The second screen lists the wallets found for that ecosystem, with a back + button to the first screen. + ++ Picking a wallet asks it to connect. On success the dialog closes. On + failure the error shows under the list and the dialog stays open for another + try. + ++ Because of this, the modal cannot add a second ecosystem while one is + connected. Most transfers need only the source wallet. A bridge that Circle + does not forward, such as one into Solana, Stellar or Starknet, also needs a + wallet on the destination; see [cross-ecosystem + bridges](/widget/whisk-send#cross-ecosystem-bridges). + + +## Reflecting the connection + +The modal does not report which wallet connected. Read it from the adapter hooks, which return `null` until a wallet is connected: + +```tsx WalletStatus.tsx +import { useState } from "react"; +import { useAccount } from "wagmi"; +import { Button, ConnectModal, useSolanaAdapter } from "@usewhisk/react"; + +export function WalletStatus() { + const [open, setOpen] = useState(false); + const evm = useAccount(); + const solana = useSolanaAdapter(); + const connected = evm.isConnected || solana !== null; + + return ( + <> + ++ > + ); +} +``` + +`useEvmAdapter`, `useSolanaAdapter`, `useStellarAdapter` and `useStarknetAdapter` each give the connected wallet as a Whisk adapter. See [wallet adapters](/hooks/wallet-adapters) and [wallets](/wallets). diff --git a/widget/primitives.mdx b/widget/primitives.mdx new file mode 100644 index 0000000..96ac149 --- /dev/null +++ b/widget/primitives.mdx @@ -0,0 +1,230 @@ +--- +title: Primitives +description: The building blocks WhiskSend is made of, exported so custom payment UIs can match the widget's look and theme. +--- + +`WhiskSend` and `WhiskReceipt` are built from a handful of small components. They are exported so you can build your own flow, usually on top of [`useWhisk`](/hooks/use-whisk) or the engine, and keep the same styling, theme and attribution. + +```tsx TopUp.tsx +import { useState } from "react"; +import { + Banner, + Button, + Card, + ChainPicker, + FieldBox, + PoweredByWhisk, + type Chain, +} from "@usewhisk/react"; + +const CHAINS: Chain[] = ["Base_Sepolia", "Arc_Testnet", "Ethereum_Sepolia"]; + +export function TopUp() { + const [chain, setChain] = useState ("Base_Sepolia"); + const [amount, setAmount] = useState(""); + return ( + + + ); +} +``` + +Every primitive styles itself with `whisk-*` class names from `@usewhisk/react/styles.css`, which read the `--whisk-*` variables. Two things follow: + +- Import `styles.css` once, and render primitives inside a [`WhiskProvider`](/widget/whisk-provider). The variables are scoped to its `[data-whisk]` element, so outside it the components lose their colors. +- [Theming](/theming/overview) applies to them exactly as it does to `WhiskSend`. + +Each component also takes a `className` (except `PoweredByWhisk` and `StepRail`), which is added after the Whisk classes. + +## Card + +The outer surface: background, border, radius and padding from the theme. + +| Prop | Type | Default | Description | +| ---------- | -------------------------------- | ------- | ---------------------------------------- | +| `...props` | `HTMLAttributessetAmount(e.target.value)} + suffix={ + + } + help="Paid in USDC" + /> + + Testnet only. These funds have no value. + + ++ ` | | Passed to the ` `. Forwards its ref. | + +## Button + +A `