USDC on EVM - Complete Implementation Guide
Private Key Handling (Write Operations Only)
For read operations (balance, allowance, verify): No private key needed.
For write operations (transfer, approve):
Option 1: Environment Variable (Recommended)
export PRIVATE_KEY=0x...import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);Option 2: File Path (Acceptable)
# Store in ~/.ethereum/keys/testnet.key
echo "0x..." > ~/.ethereum/keys/testnet.key
chmod 600 ~/.ethereum/keys/testnet.keyimport fs from "fs";
import path from "path";
import { privateKeyToAccount } from "viem/accounts";
const privateKey = fs.readFileSync(
path.join(process.env.HOME!, ".ethereum/keys/testnet.key"),
"utf-8"
).trim() as `0x${string}`;
const account = privateKeyToAccount(privateKey);Setup
import {
createPublicClient,
createWalletClient,
http,
erc20Abi,
parseUnits,
formatUnits,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { arcTestnet } from "viem/chains";
const chain = arcTestnet;
const rpcUrl = "https://rpc.testnet.arc.io"; // explicit: viem < 2.57.5 points arcTestnet at a retired host
// For read operations only
const publicClient = createPublicClient({
chain,
transport: http(rpcUrl),
});
// For write operations (requires private key)
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain,
transport: http(rpcUrl),
});
const USDC = "0x3600000000000000000000000000000000000000"; // Arc Testnet USDC address1. Check USDC Balance (Read)
const balance = await publicClient.readContract({
address: USDC,
abi: erc20Abi,
functionName: "balanceOf",
args: ["0xYourAddress"],
});
// Format the balance for display
const formattedBalance = formatUnits(balance, 6);
// Display results to user
console.log(`USDC Balance: ${formattedBalance} USDC`);
console.log(`Address: 0xYourAddress`);
console.log(`Chain: Arc Testnet (5042002)`);
console.log(`Contract: ${USDC}`);
console.log(`Explorer: https://explorer.testnet.arc.io/address/0xYourAddress`);Expected output:
USDC Balance: 10.50 USDC
Address: 0xYourAddress
Chain: Arc Testnet (5042002)
Contract: 0x3600000000000000000000000000000000000000
Explorer: https://explorer.testnet.arc.io/address/0xYourAddressAlways format with 6 decimals — never 18.
2. Check Allowance (Read)
const allowance = await publicClient.readContract({
address: USDC,
abi: erc20Abi,
functionName: "allowance",
args: ["0xOwnerAddress", "0xSpenderAddress"],
});
// Format and display the allowance
const formattedAllowance = formatUnits(allowance, 6);
console.log(`Allowance: ${formattedAllowance} USDC`);3. Send USDC (Write)
Step 1: Pre-flight Checks (Autonomous)
import { parseUnits, formatUnits } from "viem";
const amount = "10.00";
const recipient = "0xRecipientAddress";
// Read the USDC (ERC-20) balance and estimate gas up front
const usdcBalance = await publicClient.readContract({
address: USDC,
abi: erc20Abi,
functionName: "balanceOf",
args: [account.address],
});
const gasBalance = await publicClient.getBalance({ address: account.address });
const gasEstimate = await publicClient.estimateContractGas({
address: USDC,
abi: erc20Abi,
functionName: "transfer",
args: [recipient, parseUnits(amount, 6)],
account,
});
const feeData = await publicClient.estimateFeesPerGas();
const gasCost = gasEstimate * (feeData.maxFeePerGas ?? feeData.gasPrice ?? 0n);
// Is the native gas asset USDC? True on Arc. Drive this off chain metadata,
// not a hardcoded chain id, so it generalizes to any stablecoin-gas chain.
const nativeIsUsdc = chain.nativeCurrency.symbol === "USDC";
if (nativeIsUsdc) {
// Arc: the USDC transfer and gas are paid from ONE pool, so require
// balance >= amount + gas, both in 18-decimal native units (Arc's native
// decimals). gasCost is already in those units.
const required = parseUnits(amount, 18) + gasCost;
if (gasBalance < required) {
const have = formatUnits(gasBalance, 18);
const need = formatUnits(required, 18);
throw new Error(
`Insufficient USDC. Have: ${have} USDC, Need: ~${need} USDC (transfer + gas)`
);
}
} else {
// Other EVM chains: USDC (ERC-20) and the native gas token are separate
// balances — check each independently.
if (usdcBalance < parseUnits(amount, 6)) {
const have = formatUnits(usdcBalance, 6);
throw new Error(
`Insufficient USDC balance. Have: ${have} USDC, Need: ${amount} USDC`
);
}
if (gasBalance < gasCost) {
const sym = chain.nativeCurrency.symbol;
const have = formatUnits(gasBalance, 18);
const need = formatUnits(gasCost, 18);
throw new Error(
`Insufficient gas. Have: ${have} ${sym}, Need: ~${need} ${sym}`
);
}
}Step 2: Present Preview
From: 0xYourAddress
To: 0xRecipientAddress
Amount: 10.00 USDC
Chain: Arc Testnet (5042002)
USDC Address: 0x3600000000000000000000000000000000000000
Estimated Gas: 0.00012 USDC
Current Balance: 50.00 USDC
Balance After: 40.00 USDC
WARNING: This transaction will be submitted to the blockchain.
Once confirmed, it CANNOT be reversed.
Confirm transaction? (yes/no)Step 3: Execute (After Confirmation)
// Submit the transaction
const hash = await walletClient.writeContract({
address: USDC,
abi: erc20Abi,
functionName: "transfer",
args: [recipient, parseUnits(amount, 6)],
});
console.log(`Transaction submitted: ${hash}`);
console.log(`Explorer: https://explorer.testnet.arc.io/tx/${hash}`);
// Wait for confirmation
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status === "success") {
console.log(`Transaction confirmed in block ${receipt.blockNumber}`);
console.log(`Transferred ${amount} USDC to ${recipient}`);
} else {
throw new Error(`Transaction failed`);
}4. Approve Contract to Spend USDC (Write)
Any protocol that moves USDC on your behalf needs approval first. Always check current allowance before granting — skipping this causes silent reverts that waste gas.
Step 1: Check Current Allowance (Autonomous)
const SPENDER = "0xProtocolContractAddress";
const required = parseUnits("100.00", 6);
const currentAllowance = await publicClient.readContract({
address: USDC,
abi: erc20Abi,
functionName: "allowance",
args: [account.address, SPENDER],
});
const formattedAllowance = formatUnits(currentAllowance, 6);
console.log(`Current Allowance: ${formattedAllowance} USDC`);Step 2: Present Preview + Confirm
Owner: 0xYourAddress
Spender: 0xProtocolContract
Current Allowance: 0.00 USDC
New Allowance: 100.00 USDC
WARNING: This allows the spender to move USDC on your behalf.
Only approve trusted contracts.
Confirm approval? (yes/no)Step 3: Execute (After Confirmation)
if (currentAllowance < required) {
// Submit approval transaction
const hash = await walletClient.writeContract({
address: USDC,
abi: erc20Abi,
functionName: "approve",
args: [SPENDER, required],
});
console.log(`Approval submitted: ${hash}`);
// Wait for confirmation
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status === "success") {
const formattedAmount = formatUnits(required, 6);
console.log(`Approval confirmed. Spender can now move up to ${formattedAmount} USDC`);
} else {
throw new Error(`Approval failed`);
}
}
// Now call the protocol's deposit/swap/etc. methodNever use transfer() to deposit into protocols — it will revert. Use approve() then the protocol's deposit method.
5. Verify Incoming Transfer (Read)
const latest = await publicClient.getBlockNumber();
const logs = await publicClient.getContractEvents({
address: USDC,
abi: erc20Abi,
eventName: "Transfer",
args: { to: "0xRecipientAddress" },
fromBlock: latest - 9_999n,
toBlock: latest,
});
// Process and display the transfers
for (const log of logs) {
const { from, value } = log.args;
if (value === undefined) continue;
const amount = formatUnits(value, 6);
console.log(`Received ${amount} USDC from ${from}`);
console.log(` Block: ${log.blockNumber}`);
console.log(` Tx: ${log.transactionHash}`);
console.log(` Explorer: https://explorer.testnet.arc.io/tx/${log.transactionHash}`);
}Arc's public RPC rejects eth_getLogs ranges over 10,000 blocks (error -32012); page older history in chunks of at most 9,999 blocks.
Arc: a native-value USDC send (sendTransaction({ value })) emits no log from 0x3600…, only a native system Transfer from 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE (18 decimals). To catch every incoming USDC movement on Arc, query that emitter for the same Transfer event and use formatUnits(value, 18). That emitter also logs ERC-20 transfers, so never sum both streams. See USDC system events.
ERC-20 Method Reference
| Method | Type | Signature | Notes |
|---|---|---|---|
balanceOf |
Read | (owner) → uint256 |
Raw 6-decimal bigint |
allowance |
Read | (owner, spender) → uint256 |
Check before protocol interactions |
totalSupply |
Read | () → uint256 |
Total USDC on this chain |
transfer |
Write | (to, amount) → bool |
Direct send |
approve |
Write | (spender, amount) → bool |
Grant spending permission |
transferFrom |
Write | (from, to, amount) → bool |
Spend on behalf of owner (requires prior approve) |
Common Issues
"Insufficient USDC balance"
- Run balance check first
- Get testnet USDC from https://faucet.circle.com
"Insufficient gas"
- On Arc (this file's example chain), gas is paid in USDC — the native gas asset IS USDC, so just fund the wallet with USDC from https://faucet.circle.com. On other EVM chains, you need the chain's native token (ETH, MATIC, etc.).
- Get testnet gas from chain-specific faucets
"Wrong decimal places" / "Amount too large"
- Use
parseUnits(amount, 6)— never 18 decimals
"Transaction reverted" on protocol interactions
- Did you approve the protocol first? Call
approve()before deposit/swap
"Address not found" / wrong chain
- Verify chain ID and USDC address match (see main SKILL.md Quick Reference)