Circle USYC 백서

Circle USYC

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 47쪽

You should be comfortable using a terminal and Node.js. Familiarity with Starknet account contracts and basic EVM usage helps you follow and adapt the script. Examples use Arc Testnet as the destination, but you can use any [supported EVM blockchain](/cctp/concepts/supported-chains-and-domains). ## Prerequisites Before you begin this tutorial, ensure you have: * Installed [Node.js v22.18+](https://nodejs.org/) * Prepared a Starknet Sepolia account with the address and private key available * Funded your account with testnet STRK from the [Starknet faucet](https://faucet.starknet.io/) for transaction fees * Funded your account with Starknet Sepolia USDC from the [Circle Faucet](https://faucet.circle.com) * Prepared an EVM wallet with the private key available for Arc Testnet * Added the Arc Testnet network to your wallet ([network details](https://docs.arc.io/arc/references/connect-to-arc#wallet-setup)) * Funded your wallet with Arc Testnet ETH for gas fees ## Step 1: Set up the project This step shows you how to prepare your project and environment. ### 1.1. Set up your development environment Create a new directory, initialize and set up a new Node.js project, and install the required dependencies: ```bash Shell theme={null} mkdir cctp-starknet-to-arc cd cctp-starknet-to-arc npm init -y npm pkg set type=module npm pkg set scripts.start="node --env-file=.env --import=tsx index.ts" npm install starknet viem npm install --save-dev tsx typescript @types/node ``` ### 1.2. Initialize and configure the project <Tip> This step is optional. It helps prevent missing types in your IDE or editor. </Tip> Create a `tsconfig.json` file: ```shell theme={null} npx tsc --init ``` Then, update the `tsconfig.json` file: ```shell theme={null} cat <<'EOF' > tsconfig.json { "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "types": ["node"] } } EOF ``` ### 1.3. Configure environment variables Open `.env` in your editor and add: ```text theme={null} EVM_PRIVATE_KEY=YOUR_EVM_PRIVATE_KEY STARKNET_PRIVATE_KEY=YOUR_STARKNET_PRIVATE_KEY # STARKNET_RPC_URL=https://starknet-sepolia-rpc.publicnode.com ``` * `EVM_PRIVATE_KEY` is the private key for the EVM wallet used to receive USDC on Arc Testnet. * `STARKNET_PRIVATE_KEY` is the private key for the Starknet Sepolia account used to sign the burn transaction. * `STARKNET_RPC_URL` is optional. The script defaults to a public Starknet Sepolia RPC endpoint. <Tip> Open `.env` in your editor rather than writing values with shell commands, and add `.env` to your `.gitignore`. This prevents credentials from leaking into your shell history or version control. </Tip> The `npm run start` command loads variables from `.env` using Node.js native env-file support. <Warning> This example uses one or more private keys for local testing. In production, use a secure key management solution and never expose or share private keys. </Warning> ## Step 2: Configure the script Define the Starknet and Arc Testnet parameters, then configure the wallet clients for each chain. ### 2.1. Define configuration constants The script predefines the USDC and CCTP contract addresses, transfer amount, and CCTP domain IDs. Replace `STARKNET_ACCOUNT_ADDRESS` with your Starknet Sepolia account address. Starknet account addresses are not derived from the private key alone, so you set the address as a constant. ```ts TypeScript theme={null} import { Account, Contract, RpcProvider } from "starknet"; import { createPublicClient, createWalletClient, http, parseAbi, type Address, type Hex, } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { arcTestnet } from "viem/chains"; type Attestation = { message: string; attestation: string; }; const STARKNET_DOMAIN = 25; // Source domain ID for Starknet const ARC_TESTNET_DOMAIN = 26; // Destination domain ID for Arc Testnet const STARKNET_ACCOUNT_ADDRESS = "0xYOUR_STARKNET_ACCOUNT_ADDRESS"; const STARKNET_USDC = "0x0512feAc6339Ff7889822cb5aA2a86C848e9D392bB0E3E237C008674feeD8343"; const STARKNET_TOKEN_MESSENGER_MINTER = "0x04bDdE1E09a4B09a2F95d893D94a967b7717eB85A3f6dEcA8c080Ee01fBc3370"; const ARC_MESSAGE_TRANSMITTER_V2 = "0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275" as Address; const AMOUNT = 1_000_000n; // 1 USDC, 6 decimals const DESTINATION_CALLER = "0x0000000000000000000000000000000000000000000000000000000000000000"; ``` `STARKNET_DOMAIN` is the source domain used when requesting the attestation. The destination domain for Arc Testnet is 26. Starknet Sepolia USDC uses 6 decimals, so `1_000_000` represents 1 USDC. ### 2.2. Set up wallet clients The EVM clients connect to Arc Testnet with `viem`. The Starknet client uses `starknet.js` with your account address and private key. The script loads the contract ABI from the network with `getClassAt`. ```ts TypeScript theme={null} const evmPrivateKey = process.env.EVM_PRIVATE_KEY; const starknetPrivateKey = process.env.STARKNET_PRIVATE_KEY; const starknetRpcUrl = process.env.STARKNET_RPC_URL ?? "https://starknet-sepolia-rpc.publicnode.com"; if (!evmPrivateKey || !starknetPrivateKey) { throw new Error("Set EVM_PRIVATE_KEY and STARKNET_PRIVATE_KEY in .env"); } const evmAccount = privateKeyToAccount(evmPrivateKey as Hex); const arcWalletClient = createWalletClient({ account: evmAccount, chain: arcTestnet, transport: http(), }); const arcPublicClient = createPublicClient({ chain: arcTestnet, transport: http(), }); const starknetProvider = new RpcProvider({ nodeUrl: starknetRpcUrl }); const starknetAccount = new Account({ provider: starknetProvider, address: STARKNET_ACCOUNT_ADDRESS, signer: starknetPrivateKey, }); const messageTransmitterAbi = parseAbi([ "function receiveMessage(bytes message, bytes attestation) returns (bool success)", ]); async function getStarknetContract(address: string) { const { abi } = await starknetProvider.getClassAt(address); if (!abi) { throw new Error(`Failed to load ABI for ${address}`); } return new Contract({ abi, address, providerOrAccount: starknetAccount, }); } ``` ### 2.3. Format the Arc recipient for Starknet `deposit_for_burn` accepts the mint recipient as a 32-byte felt. An EVM address is left-padded with zeros to 32 bytes. ```ts TypeScript theme={null} function toBytes32Address(address: string): string { return `0x${address.replace(/^0x/i, "").padStart(64, "0")}`; } function sanitizeTransactionHash(txHash: string): string { const hash = txHash.trim().toLowerCase(); if (hash.length < 66) { return `0x${hash.replace(/^0x/i, "").padStart(64, "0")}`; } return hash; } ``` ## Step 3: Implement the transfer logic This step implements the core transfer logic: approve and burn on Starknet, poll for an attestation, then mint on Arc. ### 3.1. Approve USDC on Starknet Grant approval for the [`TokenMessengerMinterV2` contract](/cctp/references/starknet-contracts) to withdraw USDC from your Starknet account. This allows the contract to burn USDC when you initiate the transfer. ```ts TypeScript theme={null} async function approveUSDC() { console.log("Approving Starknet USDC transfer..."); const usdcContract = await getStarknetContract(STARKNET_USDC); const approveTx = await usdcContract.approve( STARKNET_TOKEN_MESSENGER_MINTER, AMOUNT, ); const approveReceipt = await starknetProvider.waitForTransaction( approveTx.transaction_hash, ); if (!approveReceipt.isSuccess()) { throw new Error(`USDC approval failed: ${approveTx.transaction_hash}`); } console.log(`Approval confirmed: ${approveTx.transaction_hash}`); } ``` ### 3.2. Burn USDC on Starknet Call `deposit_for_burn` to burn USDC on Starknet. You specify the following parameters: * **Burn amount**: The amount of USDC to burn in Starknet subunits (6 decimals) * **Destination domain**: The target blockchain for minting USDC (26 for Arc Testnet) * **Mint recipient**: The EVM wallet address that receives minted USDC on Arc, left-padded to 32 bytes * **Burn token**: The Starknet Sepolia USDC address * **Destination caller**: The zero address, allowing any caller to submit the receive transaction on Arc * **Max fee** / **finality threshold**: This example uses Fast Transfer. For live fee values and allowance checks, see [Get the fee for your transfer](/cctp/howtos/get-transfer-fee) and [Get the fast transfer allowance](/cctp/howtos/get-fast-transfer-allowance). ```ts TypeScript theme={null} async function burnUSDC() { console.log(`Burning ${Number(AMOUNT) / 1_000_000} USDC on Starknet...`); const tokenMessengerMinter = await getStarknetContract( STARKNET_TOKEN_MESSENGER_MINTER, ); const mintRecipient = toBytes32Address(evmAccount.address); const depositTx = await tokenMessengerMinter.invoke("deposit_for_burn", [ AMOUNT, ARC_TESTNET_DOMAIN, mintRecipient, STARKNET_USDC, DESTINATION_CALLER, 1500n, // maxFee — see Get the fee for your transfer 1000, // minFinalityThreshold — Fast Transfer ]); const receipt = await starknetProvider.waitForTransaction( depositTx.transaction_hash, ); if (!receipt.isSuccess()) { throw new Error(`Deposit-for-burn failed: ${depositTx.transaction_hash}`); } const txHash = sanitizeTransactionHash(depositTx.transaction_hash); console.log(`Deposit-for-burn confirmed: ${txHash}`); return txHash; } ``` ### 3.3. Retrieve attestation Retrieve the attestation required to complete the CCTP transfer by calling Circle's attestation API. * Call Circle's [`GET /v2/messages`](/api-reference/cctp/all/get-messages-v2) API endpoint to retrieve the attestation. * Pass `STARKNET_DOMAIN` for the `sourceDomain` path parameter, using the [CCTP domain](/cctp/concepts/supported-chains-and-domains#domain-identifiers) for Starknet (25). * Pass the Starknet transaction hash returned by `burnUSDC` as `transactionHash`. ```ts TypeScript theme={null} async function retrieveAttestation( transactionHash: string, ): Promise<Attestation> { const url = `https://iris-api-sandbox.circle.com/v2/messages/${STARKNET_DOMAIN}?transactionHash=${transactionHash}`; console.log(`Polling Iris V2 for attestation: ${url}`); while (true) { const response = await fetch(url); if (!response.ok && response.status !== 404) { throw new Error(`Iris V2 returned HTTP ${response.status}`); } if (response.ok) { const data = (await response.json()) as { messages?: Array<{ message?: string; attestation?: string }>; }; const result = data.messages?.[0]; if ( result?.message && result.attestation && result.attestation !== "PENDING" ) { console.log("Attestation retrieved successfully!"); return { message: result.message, attestation: result.attestation, }; } } console.log("Waiting for attestation..."); await new Promise((resolve) => setTimeout(resolve, 2_000)); } } ``` ### 3.4. Mint USDC on Arc Call the [`receiveMessage` function](/cctp/references/contract-interfaces#receivemessage) from the [`MessageTransmitterV2` contract](/cctp/references/contract-addresses) deployed on Arc Testnet. * Pass the signed attestation and message bytes as parameters. * The contract verifies the attestation and mints USDC to the recipient encoded in the CCTP message. ```ts TypeScript theme={null} async function mintUSDC({ message, attestation }: Attestation) { console.log("Minting USDC on Arc..."); const receiveTransactionHash = await arcWalletClient.writeContract({ account: evmAccount, chain: arcTestnet, address: ARC_MESSAGE_TRANSMITTER_V2, abi: messageTransmitterAbi, functionName: "receiveMessage", args: [message as Hex, attestation as Hex], }); const receiveReceipt = await arcPublicClient.waitForTransactionReceipt({ hash: receiveTransactionHash, }); if (receiveReceipt.status !== "success") { throw new Error(`Arc receiveMessage reverted: ${receiveTransactionHash}`); } console.log(`Mint confirmed: ${receiveTransactionHash}`); return receiveTransactionHash; } ``` ## Step 4: Full script Create an `index.ts` file in your project directory and paste the full script following. ```ts index.ts expandable theme={null} import { resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { Account, Contract, RpcProvider } from "starknet"; import { createPublicClient, createWalletClient, http, parseAbi, type Address, type Hex, } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { arcTestnet } from "viem/chains"; type Attestation = { message: string; attestation: string; }; const evmPrivateKey = process.env.EVM_PRIVATE_KEY; const starknetPrivateKey = process.env.STARKNET_PRIVATE_KEY; const starknetRpcUrl = process.env.STARKNET_RPC_URL ?? "https://starknet-sepolia-rpc.publicnode.com"; if (!evmPrivateKey || !starknetPrivateKey) { throw new Error("Set EVM_PRIVATE_KEY and STARKNET_PRIVATE_KEY in .env"); } const STARKNET_DOMAIN = 25; const ARC_TESTNET_DOMAIN = 26; const STARKNET_ACCOUNT_ADDRESS = "0xYOUR_STARKNET_ACCOUNT_ADDRESS"; const STARKNET_USDC = "0x0512feAc6339Ff7889822cb5aA2a86C848e9D392bB0E3E237C008674feeD8343"; const STARKNET_TOKEN_MESSENGER_MINTER = "0x04bDdE1E09a4B09a2F95d893D94a967b7717eB85A3f6dEcA8c080Ee01fBc3370"; const ARC_MESSAGE_TRANSMITTER_V2 = "0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275" as Address; const AMOUNT = 1_000_000n; // 1 USDC, 6 decimals const DESTINATION_CALLER = "0x0000000000000000000000000000000000000000000000000000000000000000"; const evmAccount = privateKeyToAccount(evmPrivateKey as Hex); const arcWalletClient = createWalletClient({ account: evmAccount, chain: arcTestnet, transport: http(), }); const arcPublicClient = createPublicClient({ chain: arcTestnet, transport: http(), }); const starknetProvider = new RpcProvider({ nodeUrl: starknetRpcUrl }); const starknetAccount = new Account({ provider: starknetProvider, address: STARKNET_ACCOUNT_ADDRESS, signer: starknetPrivateKey, }); const messageTransmitterAbi = parseAbi([ "function receiveMessage(bytes message, bytes attestation) returns (bool success)", ]); function toBytes32Address(address: string): string { return `0x${address.replace(/^0x/i, "").padStart(64, "0")}`; } function sanitizeTransactionHash(txHash: string): string { const hash = txHash.trim().toLowerCase(); if (hash.length < 66) { return `0x${hash.replace(/^0x/i, "").padStart(64, "0")}`; } return hash; } async function getStarknetContract(address: string) { const { abi } = await starknetProvider.getClassAt(address); if (!abi) { throw new Error(`Failed to load ABI for ${address}`); } return new Contract({ abi, address, providerOrAccount: starknetAccount, }); } async function approveUSDC() { console.log("Approving Starknet USDC transfer..."); const usdcContract = await getStarknetContract(STARKNET_USDC); const approveTx = await usdcContract.approve( STARKNET_TOKEN_MESSENGER_MINTER, AMOUNT, ); const approveReceipt = await starknetProvider.waitForTransaction( approveTx.transaction_hash, ); if (!approveReceipt.isSuccess()) { throw new Error(`USDC approval failed: ${approveTx.transaction_hash}`); } console.log(`Approval confirmed: ${approveTx.transaction_hash}`); } async function burnUSDC() { console.log(`Burning ${Number(AMOUNT) / 1_000_000} USDC on Starknet...`); const tokenMessengerMinter = await getStarknetContract( STARKNET_TOKEN_MESSENGER_MINTER, ); const mintRecipient = toBytes32Address(evmAccount.address); const depositTx = await tokenMessengerMinter.invoke("deposit_for_burn", [ AMOUNT, ARC_TESTNET_DOMAIN, mintRecipient, STARKNET_USDC, DESTINATION_CALLER, 1500n, // maxFee — see Get the fee for your transfer 1000, // minFinalityThreshold — Fast Transfer ]); const receipt = await starknetProvider.waitForTransaction( depositTx.transaction_hash, ); if (!receipt.isSuccess()) { throw new Error(`Deposit-for-burn failed: ${depositTx.transaction_hash}`); } const txHash = sanitizeTransactionHash(depositTx.transaction_hash); console.log(`Deposit-for-burn confirmed: ${txHash}`); return txHash; } async function retrieveAttestation( transactionHash: string, ): Promise<Attestation> { const url = `https://iris-api-sandbox.circle.com/v2/messages/${STARKNET_DOMAIN}?transactionHash=${transactionHash}`; console.log(`Polling Iris V2 for attestation: ${url}`); while (true) { const response = await fetch(url); if (!response.ok && response.status !== 404) { throw new Error(`Iris V2 returned HTTP ${response.status}`); } if (response.ok) { const data = (await response.json()) as { messages?: Array<{ message?: string; attestation?: string }>; }; const result = data.messages?.[0]; if ( result?.message && result.attestation && result.attestation !== "PENDING" ) { console.log("Attestation retrieved successfully!"); return { message: result.message, attestation: result.attestation, }; } } console.log("Waiting for attestation..."); await new Promise((resolve) => setTimeout(resolve, 2_000)); } } async function mintUSDC({ message, attestation }: Attestation) { console.log("Minting USDC on Arc..."); const receiveTransactionHash = await arcWalletClient.writeContract({ account: evmAccount, chain: arcTestnet, address: ARC_MESSAGE_TRANSMITTER_V2, abi: messageTransmitterAbi, functionName: "receiveMessage", args: [message as Hex, attestation as Hex], }); const receiveReceipt = await arcPublicClient.waitForTransactionReceipt({ hash: receiveTransactionHash, }); if (receiveReceipt.status !== "success") { throw new Error(`Arc receiveMessage reverted: ${receiveTransactionHash}`); } console.log(`Mint confirmed: ${receiveTransactionHash}`); return receiveTransactionHash; } export default async function main() { await approveUSDC(); const burnTransactionHash = await burnUSDC(); const attestation = await retrieveAttestation(burnTransactionHash); const mintTransactionHash = await mintUSDC(attestation); console.log("USDC transfer from Starknet to Arc completed."); return { starknetTransactionHash: burnTransactionHash, evmTransactionHash: mintTransactionHash, }; } if ( process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href ) { console.log("Starting CCTP Starknet → Arc flow..."); main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; }); } ``` ## Step 5: Test the script Replace `STARKNET_ACCOUNT_ADDRESS` in `index.ts` with your Starknet Sepolia account address, then run: ```shell Shell theme={null} npm run start ``` When the transfer finishes, the console logs a completion message and the relevant transaction hashes. Successful output looks similar to the following: ```bash Shell theme={null} Starting CCTP Starknet → Arc flow... Approving Starknet USDC transfer... Approval confirmed: 0x... Burning 1 USDC on Starknet... Deposit-for-burn confirmed: 0x... Polling Iris V2 for attestation: https://iris-api-sandbox.circle.com/v2/messages/25?transactionHash=<starknet-transaction-hash> Attestation retrieved successfully! Minting USDC on Arc... Mint confirmed: 0x... USDC transfer from Starknet to Arc completed. ``` Attestation polling can take several minutes depending on network conditions and the finality threshold you chose. The script retries every 2 seconds with no timeout, so allow the process to continue while Iris prepares the attestation. <Note> **Rate limit:** The attestation service rate limit is 40 requests per second. If you exceed this limit, the service blocks all API requests for the next five minutes and returns an HTTP 429 (Too Many Requests) response. </Note> </Tab> <Tab title="Arc to Starknet"> This quickstart demonstrates how to transfer USDC from Arc Testnet to Starknet Sepolia using CCTP. You use [`vi
프로젝트로 돌아가기