diff --git a/cctp-non-usdc/.gitignore b/cctp-non-usdc/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/cctp-non-usdc/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/cctp-non-usdc/README.md b/cctp-non-usdc/README.md new file mode 100644 index 0000000..ef48b04 --- /dev/null +++ b/cctp-non-usdc/README.md @@ -0,0 +1,40 @@ +# Non-USDC Crosschain Transfer Sample + +This sample application shows how to transfer non-USDC assets with CCTP, using EURC, cirBTC, or a registered custom token. The recommended path is `@circle-fin/bridge-kit` in `src/main.ts`. If Bridge Kit is not an option, swap to `src/direct.ts` for the same UI against a direct CCTP flow: approve, Iris quote, `crossChainTransfer`, and destination forwarding. + +Developer documentation at: https://developers.circle.com/cctp/expanded-assets + +## Run + +```bash +bun install +bun run dev +``` + +Connect an injected EVM testnet wallet and choose a token. **EURC** and **cirBTC** load source chains from the Iris registry for that token; destinations are the other chains from that same result (one registry read per token). **Custom token ID** waits for a valid bytes32 ID, then loads sources the same way. Source and destination are always different chains. Leave **Recipient** blank to mint to the connected wallet, or enter another EVM address. + +The app submits transactions only after the user presses **Transfer** and approves the wallet prompts. Use a testnet wallet and test tokens while exploring the example. + +## Structure + +```text +src/ + main.ts # Bridge Kit entrypoint + direct.ts # Direct CCTPx entrypoint (no Bridge Kit) + chains.ts # Hardcoded CCTPx testnet catalog (direct path) + ui.ts # Shared form / wallet / Iris registry helper + style.css +vite.config.ts # Local testnet IRIS proxy +``` + +`main.ts` takes its chain list from the CCTPx provider. `direct.ts` uses the hardcoded catalog in `chains.ts` (domain + CCTS + `viem/chains`). Both rely on `ui.ts` for Iris token→chain filtering and destination derivation. + +Swap implementations in `index.html`: + +```html + + + +``` + +The testnet Iris proxy is for local development. A deployed app needs an equivalent same-origin `/iris/testnet` proxy. diff --git a/cctp-non-usdc/index.html b/cctp-non-usdc/index.html new file mode 100644 index 0000000..c11a744 --- /dev/null +++ b/cctp-non-usdc/index.html @@ -0,0 +1,85 @@ + + + + + + + + Non-USDC Crosschain Transfer Sample + + +
+

Non-USDC Crosschain Transfer

+
+
+

+ Transfer non-USDC assets with CCTP, using EURC, cirBTC, or a custom + token. Developer documentation at: + CCTP for non-USDC assets. +

+ + + +
+
+ + + + + +
+ +
+ + + + + +
+ + +
+ +

+    
+ + + + diff --git a/cctp-non-usdc/package.json b/cctp-non-usdc/package.json new file mode 100644 index 0000000..11062da --- /dev/null +++ b/cctp-non-usdc/package.json @@ -0,0 +1,20 @@ +{ + "name": "cctp-non-usdc", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@circle-fin/adapter-viem-v2": "^1.20.1", + "@circle-fin/bridge-kit": "^1.17.1", + "viem": "^2.57.17" + }, + "devDependencies": { + "typescript": "~7.0.2", + "vite": "^8.3.7" + } +} diff --git a/cctp-non-usdc/public/favicon.svg b/cctp-non-usdc/public/favicon.svg new file mode 100644 index 0000000..60e720f --- /dev/null +++ b/cctp-non-usdc/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/cctp-non-usdc/src/chains.ts b/cctp-non-usdc/src/chains.ts new file mode 100644 index 0000000..bb86d51 --- /dev/null +++ b/cctp-non-usdc/src/chains.ts @@ -0,0 +1,60 @@ +import type { Chain } from "viem"; +import { + arbitrumSepolia, + arcTestnet, + avalancheFuji, + baseSepolia, + hyperliquidEvmTestnet, + inkSepolia, + optimismSepolia, + polygonAmoy, + sepolia, + worldchainSepolia, +} from "viem/chains"; + +/** Sandbox CrossChainTokenService — same CREATE3 address on every CCTPx testnet. */ +export const TESTNET_CCTS = + "0x63753E722bd2C2A5DF6EE19C5106662208B81077" as const; + +/** + * Hardcoded CCTPx testnet catalog for the direct (non–Bridge Kit) path. + * Token configuration still comes from Iris — this is chain + CCTS only. + */ +export interface CCTPXChain { + name: string; + chainId: number; + cctp: { domain: number }; + cctpx: { serviceAddress: typeof TESTNET_CCTS }; + viemChain: Chain; +} + +function cctpxChain( + name: string, + domain: number, + viemChain: Chain, +): CCTPXChain { + return { + name, + chainId: viemChain.id, + cctp: { domain }, + cctpx: { serviceAddress: TESTNET_CCTS }, + viemChain, + }; +} + +/** + * CCTPx-enabled EVM testnets — keep in sync with Bridge Kit's + * CCTPXBridgingProvider testnet catalog (`serviceAddress` present). + */ +export const CCTPX_TESTNET_CHAINS: readonly CCTPXChain[] = [ + cctpxChain("Ethereum Sepolia", 0, sepolia), + cctpxChain("Avalanche Fuji", 1, avalancheFuji), + cctpxChain("OP Sepolia", 2, optimismSepolia), + cctpxChain("Arbitrum Sepolia", 3, arbitrumSepolia), + cctpxChain("Base Sepolia", 6, baseSepolia), + cctpxChain("Polygon Amoy", 7, polygonAmoy), + cctpxChain("World Chain Sepolia", 14, worldchainSepolia), + cctpxChain("HyperEVM Testnet", 19, hyperliquidEvmTestnet), + cctpxChain("Ink Sepolia", 21, inkSepolia), + cctpxChain("Arc Testnet", 26, arcTestnet), +]; diff --git a/cctp-non-usdc/src/direct.ts b/cctp-non-usdc/src/direct.ts new file mode 100644 index 0000000..22f2f96 --- /dev/null +++ b/cctp-non-usdc/src/direct.ts @@ -0,0 +1,313 @@ +/* Direct CCTP for non-USDC flow: + * 1. Resolve token + manager addresses on both chains + * 2. Approve the token manager + * 3. Request an Iris FORWARD quote + * 4. Submit CCTS crossChainTransfer + * 5. Poll Iris /v2/messages until forwardTxHash is present + */ +import "./style.css"; +import { + createPublicClient, + createWalletClient, + custom, + encodePacked, + formatUnits, + http, + parseUnits, + zeroAddress, + zeroHash, + type Chain, + type Hex, +} from "viem"; +import { CCTPX_TESTNET_CHAINS, type CCTPXChain } from "./chains"; +import { + startTransferUi, + type ConnectedWallet, + type TransferChain, +} from "./ui"; + +const crossChainTokenServiceAbi = [ + { + name: "resolveTokenAddress", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "bytes32" }], + outputs: [{ type: "address" }], + }, + { + name: "resolveTokenManager", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "bytes32" }], + outputs: [{ type: "address" }], + }, + { + name: "crossChainTransfer", + type: "function", + stateMutability: "payable", + inputs: [ + { name: "tokenId", type: "bytes32" }, + { name: "amount", type: "uint256" }, + { name: "destinationDomain", type: "uint32" }, + { name: "destinationAddress", type: "bytes" }, + { name: "destinationCaller", type: "bytes32" }, + { name: "minFinalityThreshold", type: "uint32" }, + { + name: "claim", + type: "tuple", + components: [ + { name: "signedQuote", type: "bytes" }, + { name: "refundAddress", type: "address" }, + ], + }, + { name: "autoExecuteHookData", type: "bool" }, + { name: "hookData", type: "bytes" }, + ], + outputs: [], + }, +] as const; + +const erc20Abi = [ + { + name: "approve", + type: "function", + stateMutability: "nonpayable", + inputs: [ + { name: "spender", type: "address" }, + { name: "amount", type: "uint256" }, + ], + outputs: [{ type: "bool" }], + }, + { + name: "decimals", + type: "function", + stateMutability: "view", + inputs: [], + outputs: [{ type: "uint8" }], + }, +] as const; + +const FINALITY_THRESHOLD = 2000; +const DESTINATION_TIMEOUT_MS = 15 * 60_000; +const POLL_INTERVAL_MS = 10_000; + +const supportedChains = [...CCTPX_TESTNET_CHAINS]; + +/** + * Approve, quote, crossChainTransfer, and wait for destination forwarding + * without Bridge Kit. Read top to bottom — each step is inline. + */ +async function executeDirectTransfer(args: { + sourceChain: TransferChain; + destinationChain: TransferChain; + tokenId: `0x${string}`; + amount: string; + recipient: `0x${string}`; + wallet: ConnectedWallet; + onStatus: (message: string) => void; +}): Promise { + // Same objects from CCTPX_TESTNET_CHAINS (includes viemChain) — safe to cast. + const sourceChain = args.sourceChain as CCTPXChain; + const destinationChain = args.destinationChain as CCTPXChain; + const { tokenId, amount, recipient, wallet, onStatus } = args; + const account = wallet.address; + + const sourceClient = createPublicClient({ + chain: sourceChain.viemChain, + transport: http(), + }); + const destinationClient = createPublicClient({ + chain: destinationChain.viemChain, + transport: http(), + }); + + // === Step 1: Resolve token deployments and manager === + onStatus("Resolving token deployments and manager…"); + const sourceToken = await sourceClient.readContract({ + address: sourceChain.cctpx.serviceAddress, + abi: crossChainTokenServiceAbi, + functionName: "resolveTokenAddress", + args: [tokenId], + }); + const manager = await sourceClient.readContract({ + address: sourceChain.cctpx.serviceAddress, + abi: crossChainTokenServiceAbi, + functionName: "resolveTokenManager", + args: [tokenId], + }); + const destinationToken = await destinationClient.readContract({ + address: destinationChain.cctpx.serviceAddress, + abi: crossChainTokenServiceAbi, + functionName: "resolveTokenAddress", + args: [tokenId], + }); + if ( + sourceToken === zeroAddress || + manager === zeroAddress || + destinationToken === zeroAddress + ) { + throw new Error("The selected token is not deployed on both chains in this route."); + } + + const decimals = await sourceClient.readContract({ + address: sourceToken, + abi: erc20Abi, + functionName: "decimals", + }); + const fractionalDigits = amount.split(".")[1]?.length ?? 0; + if (fractionalDigits > decimals) { + throw new Error(`This token supports at most ${decimals} decimal places.`); + } + const parsedAmount = parseUnits(amount, decimals); + if (parsedAmount <= 0n) throw new Error("Enter an amount greater than zero."); + + await ensureWalletChain(wallet.provider, sourceChain.viemChain); + const walletClient = createWalletClient({ + account, + chain: sourceChain.viemChain, + transport: custom(wallet.provider), + }); + + // === Step 2: Approve the token manager === + onStatus("Approve the token manager…"); + const approveTx = await walletClient.writeContract({ + address: sourceToken, + abi: erc20Abi, + functionName: "approve", + args: [manager, parsedAmount], + chain: sourceChain.viemChain, + account, + }); + await sourceClient.waitForTransactionReceipt({ hash: approveTx }); + onStatus(`Approval confirmed: ${approveTx}`); + + // === Step 3: Request an Iris FORWARD quote === + onStatus("Request an Iris FORWARD quote…"); + const quoteResponse = await fetch( + `/iris/testnet/v2/quote/cctpx/${tokenId}/${sourceChain.cctp.domain}/${destinationChain.cctp.domain}`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + amount: parsedAmount.toString(), + feeToken: zeroAddress, + requests: [ + { + type: "FORWARD", + params: { msgType: "TransferMessage", destinationAddress: recipient }, + }, + ], + }), + }, + ); + if (!quoteResponse.ok) { + throw new Error( + `Iris quote failed (${quoteResponse.status}): ${await quoteResponse.text()}`, + ); + } + const quote = (await quoteResponse.json()) as { + signedQuote?: Hex; + feeTotalAmount?: string; + }; + if (!quote.signedQuote || !quote.feeTotalAmount) { + throw new Error("Iris returned an incomplete CCTPx quote."); + } + + // === Step 4: Submit CCTS crossChainTransfer === + onStatus("Submit CCTS crossChainTransfer…"); + const transferTx = await walletClient.writeContract({ + address: sourceChain.cctpx.serviceAddress, + abi: crossChainTokenServiceAbi, + functionName: "crossChainTransfer", + args: [ + tokenId, + parsedAmount, + destinationChain.cctp.domain, + encodePacked(["address"], [recipient]), + zeroHash, + FINALITY_THRESHOLD, + { signedQuote: quote.signedQuote, refundAddress: zeroAddress }, + false, + "0x", + ], + value: BigInt(quote.feeTotalAmount), + chain: sourceChain.viemChain, + account, + }); + await sourceClient.waitForTransactionReceipt({ hash: transferTx }); + onStatus(`Source transfer confirmed: ${transferTx}`); + + // === Step 5: Poll Iris until the destination forward tx is reported === + const deadline = Date.now() + DESTINATION_TIMEOUT_MS; + onStatus("Waiting for Iris attestation and destination forwarding…"); + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); + const messagesResponse = await fetch( + `/iris/testnet/v2/messages/${sourceChain.cctp.domain}?transactionHash=${transferTx}`, + ); + if (!messagesResponse.ok) continue; + + const body = (await messagesResponse.json()) as { + messages?: Array<{ + forwardState?: string | null; + forwardTxHash?: string | null; + }>; + }; + const message = body.messages?.[0]; + if (message?.forwardState === "FAILED") { + throw new Error("Iris destination forwarding failed."); + } + if ( + (message?.forwardState === "CONFIRMED" || + message?.forwardState === "COMPLETE") && + message.forwardTxHash + ) { + onStatus( + `Destination received ${formatUnits(parsedAmount, decimals)} tokens: ${message.forwardTxHash}`, + ); + return; + } + onStatus(`Forward state: ${message?.forwardState ?? "pending"}…`); + } + throw new Error("Timed out waiting for the destination forwarding transaction."); +} + +// === Supporting: wallet chain switch === +async function ensureWalletChain( + provider: ConnectedWallet["provider"], + chain: Chain, +) { + const chainId = `0x${chain.id.toString(16)}`; + try { + await provider.request({ + method: "wallet_switchEthereumChain", + params: [{ chainId }], + }); + } catch (error) { + const code = + typeof error === "object" && error !== null && "code" in error + ? (error as { code?: unknown }).code + : undefined; + if (code !== 4902) throw error; + await provider.request({ + method: "wallet_addEthereumChain", + params: [ + { + chainId, + chainName: chain.name, + nativeCurrency: chain.nativeCurrency, + rpcUrls: [...chain.rpcUrls.default.http], + blockExplorerUrls: chain.blockExplorers?.default.url + ? [chain.blockExplorers.default.url] + : undefined, + }, + ], + }); + } +} + +// === Init === +startTransferUi({ + chains: supportedChains, + transfer: executeDirectTransfer, +}); diff --git a/cctp-non-usdc/src/main.ts b/cctp-non-usdc/src/main.ts new file mode 100644 index 0000000..a5932ef --- /dev/null +++ b/cctp-non-usdc/src/main.ts @@ -0,0 +1,100 @@ +import "./style.css"; +import { createViemAdapterFromProvider } from "@circle-fin/adapter-viem-v2"; +import { + BridgeKit, + CCTPXBridgingProvider, + type CCTPXRouteToken, + type EVMChainDefinition, +} from "@circle-fin/bridge-kit"; +import { + startTransferUi, + type ConnectedWallet, + type TransferChain, +} from "./ui"; + +/** Rewrite Iris SDK URL strings through the local Vite testnet proxy. */ +async function irisProxyFetch( + input: RequestInfo | URL, + init?: RequestInit, +): Promise { + // CCTPXBridgingProvider always passes a string URL into fetch(url, init). + const { pathname, search } = new URL(String(input)); + return fetch(`/iris/testnet${pathname}${search}`, init); +} + +const cctpxProvider = new CCTPXBridgingProvider({ fetchImpl: irisProxyFetch }); +const supportedChains = cctpxProvider + .getSupportedChains() + .filter( + (chain) => + chain.type === "evm" && + chain.cctp && + chain.cctpx?.serviceAddress && + chain.isTestnet, + ) + .sort((a, b) => a.name.localeCompare(b.name)) as TransferChain[]; + +const kit = new BridgeKit(); +const kitCctpxProviderIndex = kit.providers.findIndex( + (provider) => provider.name === "CCTPXBridgingProvider", +); +if (kitCctpxProviderIndex !== -1) { + kit.providers[kitCctpxProviderIndex] = cctpxProvider; +} + +/** Bridge EURC / cirBTC / custom CCTPx tokens with Bridge Kit. */ +async function bridgeWithKit(args: { + sourceChain: TransferChain; + destinationChain: TransferChain; + tokenId: `0x${string}`; + amount: string; + recipient: `0x${string}`; + wallet: ConnectedWallet; + onStatus: (message: string) => void; +}): Promise { + // Same objects from supportedChains (full Bridge Kit EVM defs) — safe to cast. + const source = args.sourceChain as EVMChainDefinition; + const destination = args.destinationChain as EVMChainDefinition; + + const decimals = await cctpxProvider.getTokenDecimals( + args.tokenId as CCTPXRouteToken, + source, + ); + if (decimals === undefined) { + throw new Error("Token decimals were not found in the CCTPx registry."); + } + const fractionalDigits = args.amount.split(".")[1]?.length ?? 0; + if (fractionalDigits > decimals) { + throw new Error(`This token supports at most ${decimals} decimal places.`); + } + + const adapter = await createViemAdapterFromProvider({ + provider: args.wallet.provider, + }); + const result = await kit.bridge({ + from: { adapter, chain: source }, + to: { + adapter, + chain: destination, + recipientAddress: args.recipient, + }, + amount: args.amount, + token: args.tokenId, + }); + if (result.state !== "success") { + throw new Error(`Bridge Kit transfer ended in state: ${result.state}`); + } + for (const step of result.steps) { + if (step.txHash) args.onStatus(`${step.name}: ${step.txHash}`); + } + args.onStatus(`Transfer complete: ${args.amount} tokens delivered.`); +} + +const { appendStatus } = startTransferUi({ + chains: supportedChains, + transfer: bridgeWithKit, +}); + +kit.on("*", (payload) => { + appendStatus(payload.method); +}); diff --git a/cctp-non-usdc/src/style.css b/cctp-non-usdc/src/style.css new file mode 100644 index 0000000..97f8526 --- /dev/null +++ b/cctp-non-usdc/src/style.css @@ -0,0 +1,117 @@ +/** + * Copyright 2026 Circle Internet Group, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +* { + box-sizing: border-box; + margin: 0; +} + +body { + max-width: 45rem; + margin-inline: auto; + padding-inline: 1rem; + font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, + helvetica neue, Adwaita Sans, Cantarell, Ubuntu, roboto, noto, helvetica, + arial, sans-serif; +} + +header { + display: flex; + justify-content: space-between; + align-items: center; + margin-block: 2em 1em; +} + +p { + line-height: 1.39; + margin-block-end: 1em; +} + +code { + font-size-adjust: 0.65; + color: darkgreen; +} + +button { + background-color: white; + border: 1px solid lightgray; + color: darkslategrey; + padding: 0.5em 1em; + font-weight: bold; + border-radius: 0.5em; + cursor: pointer; + transition: background-color 0.3s ease; + &:not(:disabled):hover { + background-color: whitesmoke; + } + &:disabled { + opacity: 0.7; + color: lightslategrey; + cursor: not-allowed; + background-color: whitesmoke; + } +} + +main button { + margin-block-end: 1em; + margin-inline-end: 0.5em; +} + +.row { + display: flex; + gap: 1em; +} + +label { + display: block; + margin-block: 1em; +} + +label span { + font-size: smaller; + font-weight: bold; +} + +input, +select { + display: block; + width: 100%; + margin-block-start: 0.35em; + padding: 0.5em 0.75em; + font: inherit; + border: 1px solid lightgray; + border-radius: 0.5em; +} + +.transfer__token-id, +.transfer__recipient { + flex: 1; +} + +pre:not(:empty) { + margin-block-start: 1em; + background-color: ghostwhite; + padding: 1em; + max-width: 100%; + overflow: auto; + border-radius: 0.5em; + max-height: 28em; + word-break: break-all; + white-space: pre-wrap; + line-height: 1.5; +} \ No newline at end of file diff --git a/cctp-non-usdc/src/ui.ts b/cctp-non-usdc/src/ui.ts new file mode 100644 index 0000000..71e9235 --- /dev/null +++ b/cctp-non-usdc/src/ui.ts @@ -0,0 +1,356 @@ +import { isAddress, type EIP1193Provider } from "viem"; + +/** Chain fields the form needs — Bridge Kit defs and the direct catalog both fit. */ +export interface TransferChain { + name: string; + chainId: number; + cctp: { domain: number }; + cctpx: { serviceAddress: string }; +} + +export interface ConnectedWallet { + provider: EIP1193Provider; + address: `0x${string}`; +} + +export const knownTokenIds = { + EURC: "0x2587821a0ee7daa174b95436b5dab1731cfa1844775b010217d3c0dd02a4eecd", + cirBTC: "0x7c27b7b6485f3ea49b7d1a439e288d3c3116f533302afabb7e372dfc0770cc7d", +} as const satisfies Record; + +export type TokenKind = keyof typeof knownTokenIds | "custom"; + +/** Intersect a chain catalog with Iris CCTPx deployments for a token ID. */ +export async function chainsWithTokenDeployment< + T extends { cctp: { domain: number } }, +>(chains: readonly T[], tokenId: `0x${string}`): Promise { + const response = await fetch( + `/iris/testnet/v2/cctpx/tokens?tokenid=${encodeURIComponent(tokenId)}`, + ); + if (!response.ok) { + throw new Error( + `Token registry lookup failed (${response.status}): ${await response.text()}`, + ); + } + + const body = (await response.json()) as { + data?: Array<{ + deployments?: Array<{ domainId: number; enabled?: boolean }>; + }>; + }; + const deployments = body.data?.[0]?.deployments ?? []; + const domains = new Set( + deployments + .filter((deployment) => deployment.enabled !== false) + .map((deployment) => deployment.domainId), + ); + return chains.filter((chain) => domains.has(chain.cctp.domain)); +} + +declare global { + interface Window { + ethereum?: EIP1193Provider; + } +} + +/** + * Wire the shared HTML form. Entrypoints supply the chain catalog + transfer. + * One Iris registry read per token → source options; destinations are that + * same deployment set minus the selected source (no second Iris call). + */ +export function startTransferUi(options: { + chains: TransferChain[]; + transfer: (args: { + sourceChain: TransferChain; + destinationChain: TransferChain; + tokenId: `0x${string}`; + amount: string; + recipient: `0x${string}`; + wallet: ConnectedWallet; + onStatus: (message: string) => void; + }) => Promise; +}): { + appendStatus: (message: string) => void; +} { + const { chains, transfer } = options; + + const connectButton = document.querySelector("#connect-wallet")!; + const sourceSelect = document.querySelector("#source-chain")!; + const destinationSelect = document.querySelector("#destination-chain")!; + const tokenSelect = document.querySelector("#token-kind")!; + const tokenIdInput = document.querySelector("#token-id")!; + const amountInput = document.querySelector("#amount")!; + const recipientInput = document.querySelector("#recipient")!; + const transferButton = document.querySelector("#transfer-button")!; + const form = document.querySelector("#transfer-form")!; + const status = document.querySelector("#transfer-status")!; + const recipientPlaceholder = recipientInput.placeholder; + + const chainsById = new Map( + chains.map((chain) => [String(chain.chainId), chain] as const), + ); + + let wallet: ConnectedWallet | null = null; + /** Last Iris deployment set for the current token — destinations filter this. */ + let configuredForToken: TransferChain[] = []; + let transferInProgress = false; + let lookupTimeout: ReturnType | undefined; + let previousTokenKind = tokenSelect.value; + + function appendStatus(message: string) { + const time = new Date().toLocaleTimeString(); + status.textContent = `${status.textContent?.trim() ? `${status.textContent.trim()}\n` : ""}[${time}] ${message}`; + status.scrollTop = status.scrollHeight; + } + + function isBytes32(value: string): value is `0x${string}` { + return /^0x[0-9a-fA-F]{64}$/.test(value); + } + + function getTokenKind(): TokenKind { + if (tokenSelect.value === "EURC" || tokenSelect.value === "cirBTC") { + return tokenSelect.value; + } + return "custom"; + } + + function getTokenId(): `0x${string}` | undefined { + const tokenId = tokenIdInput.value.trim(); + return isBytes32(tokenId) ? tokenId : undefined; + } + + /** Empty input → connected wallet; otherwise a validated EVM address. */ + function getRecipient(): `0x${string}` | undefined { + const value = recipientInput.value.trim(); + if (!value) return wallet?.address; + return isAddress(value) ? value : undefined; + } + + function isValidAmount(value: string): boolean { + const amount = value.trim(); + return /^\d+(?:\.\d+)?$/.test(amount) && /[1-9]/.test(amount); + } + + function updateTokenId() { + const kind = getTokenKind(); + const isCustom = kind === "custom"; + tokenIdInput.readOnly = !isCustom; + tokenIdInput.required = isCustom; + + if (isCustom) { + if (previousTokenKind !== "custom") tokenIdInput.value = ""; + tokenIdInput.placeholder = "Enter bytes32 token ID (0x…)"; + previousTokenKind = tokenSelect.value; + return; + } + + tokenIdInput.value = knownTokenIds[kind]; + tokenIdInput.placeholder = ""; + previousTokenKind = tokenSelect.value; + } + + function updateTransferButton() { + transferButton.disabled = + transferInProgress || + !wallet || + !sourceSelect.value || + !destinationSelect.value || + !getTokenId() || + !getRecipient() || + !isValidAmount(amountInput.value); + } + + function fillSelect( + select: HTMLSelectElement, + placeholder: string, + items: TransferChain[], + ) { + select.replaceChildren(new Option(placeholder, "")); + for (const chain of items) { + select.add(new Option(chain.name, String(chain.chainId))); + } + } + + function refreshDestinations() { + const sourceId = sourceSelect.value; + if (!sourceId) { + fillSelect(destinationSelect, "Choose a destination", []); + updateTransferButton(); + return; + } + + const destinations = configuredForToken.filter( + (chain) => String(chain.chainId) !== sourceId, + ); + const previousDestination = destinationSelect.value; + fillSelect(destinationSelect, "Choose a destination", destinations); + if ( + previousDestination && + destinations.some((chain) => String(chain.chainId) === previousDestination) + ) { + destinationSelect.value = previousDestination; + } + updateTransferButton(); + } + + async function refreshSourceChains() { + const kind = getTokenKind(); + const tokenId = getTokenId(); + const previousSource = sourceSelect.value; + configuredForToken = []; + fillSelect(destinationSelect, "Choose a destination", []); + updateTransferButton(); + + // Custom tokens: wait for a valid bytes32 id before asking Iris for chains. + if (kind === "custom" && !tokenId) { + fillSelect(sourceSelect, "Enter a token ID first", []); + appendStatus("Enter a bytes32 token ID to load configured chains."); + updateTransferButton(); + return; + } + + // Known tokens always have a tokenId from updateTokenId(); custom is gated above. + if (!tokenId) { + fillSelect(sourceSelect, "Choose a source", []); + updateTransferButton(); + return; + } + + fillSelect(sourceSelect, "Loading…", []); + try { + configuredForToken = await chainsWithTokenDeployment(chains, tokenId); + fillSelect(sourceSelect, "Choose a source", configuredForToken); + if ( + previousSource && + configuredForToken.some((chain) => String(chain.chainId) === previousSource) + ) { + sourceSelect.value = previousSource; + } + appendStatus( + configuredForToken.length + ? `${configuredForToken.length} source chain(s) for ${kind === "custom" ? "this token" : kind}.` + : `No source chains for ${kind === "custom" ? "this token" : kind}.`, + ); + refreshDestinations(); + } catch (error) { + configuredForToken = []; + fillSelect(sourceSelect, "Chain lookup failed", []); + appendStatus(error instanceof Error ? error.message : String(error)); + } + updateTransferButton(); + } + + function setDisconnected() { + wallet = null; + recipientInput.placeholder = recipientPlaceholder; + connectButton.textContent = "Connect wallet"; + updateTransferButton(); + } + + async function handleWalletButton() { + if (wallet) { + setDisconnected(); + appendStatus("Wallet disconnected."); + return; + } + + connectButton.disabled = true; + try { + const provider = window.ethereum; + if (!provider) throw new Error("No injected EVM wallet was found."); + + const accounts = await provider.request({ method: "eth_requestAccounts" }); + if (!Array.isArray(accounts) || typeof accounts[0] !== "string") { + throw new Error("The wallet did not return an account."); + } + const address = accounts[0] as `0x${string}`; + wallet = { provider, address }; + recipientInput.placeholder = address; + connectButton.textContent = `Disconnect ${address.slice(0, 6)}…${address.slice(-4)}`; + appendStatus(`Wallet connected: ${address}`); + } catch (error) { + appendStatus(error instanceof Error ? error.message : String(error)); + } finally { + connectButton.disabled = false; + updateTransferButton(); + } + } + + async function handleTransfer(event: SubmitEvent) { + event.preventDefault(); + if (!form.reportValidity() || !wallet) return; + + const sourceChain = chainsById.get(sourceSelect.value); + const destinationChain = chainsById.get(destinationSelect.value); + const tokenId = getTokenId(); + const recipient = getRecipient(); + if ( + !sourceChain || + !destinationChain || + !tokenId || + !recipient || + !isValidAmount(amountInput.value) + ) { + appendStatus("Select a supported route and token before transferring."); + return; + } + if (sourceChain.chainId === destinationChain.chainId) { + appendStatus("Source and destination must be different chains."); + return; + } + + transferInProgress = true; + updateTransferButton(); + try { + const amount = amountInput.value.trim(); + const tokenLabel = + tokenSelect.value === "custom" ? "custom token" : tokenSelect.value; + appendStatus(`Starting ${amount} ${tokenLabel} transfer…`); + await transfer({ + sourceChain, + destinationChain, + tokenId, + amount, + recipient, + wallet, + onStatus: appendStatus, + }); + } catch (error) { + appendStatus(error instanceof Error ? error.message : String(error)); + } finally { + transferInProgress = false; + updateTransferButton(); + } + } + + connectButton.addEventListener("click", () => void handleWalletButton()); + sourceSelect.addEventListener("change", refreshDestinations); + tokenSelect.addEventListener("change", () => { + updateTokenId(); + void refreshSourceChains(); + }); + tokenIdInput.addEventListener("input", () => { + updateTransferButton(); + if (getTokenKind() !== "custom") return; + clearTimeout(lookupTimeout); + lookupTimeout = setTimeout(() => { + void refreshSourceChains(); + }, 350); + }); + destinationSelect.addEventListener("change", updateTransferButton); + amountInput.addEventListener("input", updateTransferButton); + recipientInput.addEventListener("input", updateTransferButton); + form.addEventListener("submit", (event) => void handleTransfer(event)); + + appendStatus( + chains.length + ? "Testnet only. Connect a wallet, choose a token and route, then Transfer." + : "No CCTPx testnet chains were found.", + ); + + updateTokenId(); + void refreshSourceChains(); + updateTransferButton(); + + return { appendStatus }; +} diff --git a/cctp-non-usdc/tsconfig.json b/cctp-non-usdc/tsconfig.json new file mode 100644 index 0000000..206b5e0 --- /dev/null +++ b/cctp-non-usdc/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "es2023", + "module": "esnext", + "lib": ["ES2023", "DOM"], + "types": ["vite/client"], + "allowArbitraryExtensions": true, + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/cctp-non-usdc/vite.config.ts b/cctp-non-usdc/vite.config.ts new file mode 100644 index 0000000..ddcde6e --- /dev/null +++ b/cctp-non-usdc/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from "vite"; + +export default defineConfig({ + server: { + proxy: { + "/iris/testnet": { + target: "https://iris-api-sandbox.circle.com", + changeOrigin: true, + rewrite: (path) => path.replace(/^\/iris\/testnet/, ""), + timeout: 60_000, + proxyTimeout: 60_000, + }, + }, + }, +});