Day 4: Developer-Controlled Wallets

What You Will Learn Today

Time needed: 25-35 minutes

Why Are We Doing This?

What is a developer-controlled wallet?

A developer-controlled wallet is a wallet where you (the developer) control the private keys through Circle's API. Think of it like a bank account for your app - your backend server controls it, you decide when to send or receive money, and users don't need to deal with private keys.

Reference: https://developers.circle.com/wallets/dev-controlled

Why do we need this?

For our P2P payment app, developer-controlled wallets let us create wallets for users automatically (no MetaMask needed), handle transactions for them, build a treasury wallet for platform fees, and pay gas fees so users don't have to.

Important: With great power comes great responsibility. You control the funds, so security is critical. Never expose your entity secret or API key.

Developer-controlled vs user-controlled

Reference: https://developers.circle.com/wallets

Prerequisites

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#prerequisites


Step 1: Get Your Circle API Key

Reference: https://developers.circle.com/w3s/circle-developer-account

Important: API key format

Your API key must be in this exact format - three parts separated by colons:

TEST_API_KEY:your_key_id:your_secret

Example:

TEST_API_KEY:ebb3ad72232624921abc4b162148bb84:019ef3358ef9cd6d08fc32csfe89a68d

Copy the whole thing including both colons when you generate it.

Create a Circle developer account

  1. Go to https://console.circle.com
  2. Click Sign up
  3. Fill in registration and verify your email
  4. Log in to Circle Console

Generate your API key

  1. In Circle Console, go to Settings then API keys
  2. Click Create a key
  3. Give it a name: P2P App Development
  4. Choose Standard key
  5. Click Create
  6. Copy the entire API key immediately - you can only see it once

Save your API key to the .env file

  1. Open VS Code
  2. Open your arc-project folder
  3. Open or create the .env file
  4. Add this line, replacing the placeholder with your actual key:
CIRCLE_API_KEY=TEST_API_KEY:your_key_id:your_secret

Your .env file should look like this:

CIRCLE_API_KEY=TEST_API_KEY:ebb3ad72232624921abc4b162148bb84:019ef3358ef9cd6d08fc32csfe89a68d

Step 2: Install the Circle SDK

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#1-1-create-the-project-and-install-dependencies

Open the terminal in VS Code and run:

npm install @circle-fin/developer-controlled-wallets typescript tsx

Wait for the installation to finish (1-2 minutes). This installs Circle's official SDK which handles all API requests, encryption, and wallet operations.


Optional Step: Setup TypeScript Configuration

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#1-2-configure-typescript-optional

This step helps prevent missing types in your IDE. Run:

npx tsc --init

Then update tsconfig.json with this content:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "types": ["node"]
  }
}

Step 3: Register Your Entity Secret (run once only)

Reference: https://developers.circle.com/wallets/dev-controlled/entity-secret-management

What is an entity secret?

The entity secret is a random password that locks down all your wallet stuff - making wallets, signing transactions, everything. It's tied to your Circle account, not to any single API key.

Entity secret vs API key - what's the difference?

Your entity secret is connected to your Circle account (the entity), not the API key. This means:

Think of it like this:

Your Circle account (entity)  <-- this holds the entity secret
    |-- API key 1 (can be deleted)
    |-- API key 2 (new)          <-- still the same entity!
    |-- API key 3 (another new)

Create the registration script

  1. Create a new file: register-secret.ts
  2. Copy this code:
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { registerEntitySecretCiphertext } from "@circle-fin/developer-controlled-wallets";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const OUTPUT_DIR = path.join(__dirname, "output");

async function main() {
  const apiKey = process.env.CIRCLE_API_KEY;
  if (!apiKey) {
    throw new Error(
      "CIRCLE_API_KEY is required. Add it to .env or set it as an environment variable."
    );
  }

  // Check if entity secret already exists
  const envPath = path.join(__dirname, ".env");
  const envContent = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf-8") : "";

  if (envContent.includes("CIRCLE_ENTITY_SECRET=")) {
    console.log("Entity secret already exists in .env file.");
    return;
  }

  console.log("Registering entity secret...");

  // Create output directory if it doesn't exist
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });

  // Generate a random entity secret
  const entitySecret = crypto.randomBytes(32).toString("hex");

  // Register the entity secret with Circle
  await registerEntitySecretCiphertext({
    apiKey,
    entitySecret,
    recoveryFileDownloadPath: OUTPUT_DIR,
  });

  console.log("The following entity secret is registered. Remember to save the secret somewhere safe.");
  console.log("-----------------------------");
  console.log("Entity secret is registered.");
  console.log("----------------------------");

  // Save to .env file
  fs.appendFileSync(envPath, `
 CIRCLE_ENTITY_SECRET=${entitySecret}
 `, "utf-8");

  console.log("Entity secret has been saved to .env file.");
  console.log(`Recovery file saved to: ${OUTPUT_DIR}/recovery-file.json`);
  console.log("Keep both files secure. They are needed to access your wallets.");
  console.log("You can now run the create-wallet-set.ts script to create your wallet set.");
}

main().catch((err) => {
  console.error("Error:", err.message || err);
  process.exit(1);
});

Run the registration script

node --env-file=.env --import=tsx register-secret.ts

Expected output:

Registering entity secret...

The following entity secret is registered. Remember to save the secret somewhere safe.
------------------------------------
Entity secret is registered.
------------------------------------

Entity secret has been saved to .env file.
Recovery file saved to: output/recovery-file.json

Keep both files secure. They are needed to access your wallets.

You can now run the create-wallet-set.ts script to create your wallet set.

Do not run this script a second time. Once registered, your entity secret is permanent for your account. The script already checks for this and will stop if a secret already exists in your .env file.

What just happened?

The script made a random password and sent it to Circle to save it to your account. From now on, every wallet you make will use this password. Circle saved a locked copy on their side; you have the real password in your .env file and a backup file in the output folder.

What got added to your .env: a new line CIRCLE_ENTITY_SECRET=...

Where to check: open your .env file - you'll see the entity secret value at the bottom.

What the backup file is for: if you ever lose the entity secret value in your .env, the backup file in output/recovery-file.json is your safety net. Save it somewhere safe.


Step 4: Create a Wallet Set

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#2-3-create-wallet-set

What is a wallet set?

A wallet set is a folder for your wallets. Think of it as a big container that can hold up to 10 million wallets. You usually make one wallet set per project, and all your user wallets live inside it.

Create the wallet set script

  1. Create a new file: create-wallet-set.ts
  2. Copy this code:
import fs from "node:fs";
import path from "node:path";
import readline from "node:readline";
import { fileURLToPath } from "node:url";
import {
  initiateDeveloperControlledWalletsClient,
  type TokenBlockchain,
} from "@circle-fin/developer-controlled-wallets";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const OUTPUT_DIR = path.join(__dirname, "output");
const WALLET_SET_NAME = "Circle Wallet Onboarding";

async function main() {
  const apiKey = process.env.CIRCLE_API_KEY;
  const entitySecret = process.env.CIRCLE_ENTITY_SECRET;

  if (!apiKey) {
    throw new Error(
      "CIRCLE_API_KEY is required. Add it to .env or set it as an environment variable."
    );
  }

  if (!entitySecret) {
    throw new Error(
      "CIRCLE_ENTITY_SECRET is required. Run 'node --env-file=.env --import=tsx register-secret.ts' first."
    );
  }

  // Create output directory if it doesn't exist
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });

  // Initialize Circle client
  const client = initiateDeveloperControlledWalletsClient({
    apiKey,
    entitySecret,
  });

  // Create wallet set
  console.log("Creating wallet set...");
  const walletSet = (await client.createWalletSet({ name: WALLET_SET_NAME })).data?.walletSet;
  if (!walletSet?.id) {
    throw new Error("Wallet set creation failed: no ID returned");
  }
  console.log("Wallet set ID:", walletSet.id);

  // Create Wallet on Arc Testnet
  console.log("\nCreating Wallet on ARC-TESTNET...");
  const wallet = (
    await client.createWallets({
      walletSetId: walletSet.id,
      blockchains: ["ARC-TESTNET"],
      count: 1,
      accountType: "EOA",
    })
  ).data?.wallets?.[0];
 
  if (!wallet) {
    throw new Error("Wallet creation failed: no wallet returned");
  }
 
  console.log("Wallet ID:", wallet.id);
  console.log("Address:", wallet.address);

  const envPath = path.join(__dirname, ".env");
  fs.appendFileSync(envPath, `CIRCLE_WALLET_ADDRESS=${wallet.address}\n`, "utf-8");
  fs.appendFileSync(envPath, `CIRCLE_WALLET_BLOCKCHAIN=${wallet.blockchain}\n`, "utf-8");
  fs.writeFileSync(
    path.join(OUTPUT_DIR, "wallet-info.json"),
    JSON.stringify(wallet, null, 2),
    "utf-8"
  );

  console.log("\nBefore continuing, request test USDC from the faucet:");
  console.log("  1. Go to https://faucet.circle.com");
  console.log('  2. Select "Arc Testnet" network');
  console.log(`  3. Paste your wallet address: ${wallet.address}`);
  console.log('  4. Click "Send USDC"');

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
 
  await new Promise((resolve) =>
    rl.question("\nPress Enter once faucet tokens have been sent... ", () => {
      rl.close();
      resolve(null);
    })
  );

  // Create second wallet
  console.log("\nCreating second wallet...");
  const secondWallet = (
    await client.createWallets({
      walletSetId: walletSet.id,
      blockchains: ["ARC-TESTNET"],
      count: 1,
      accountType: "EOA",
    })
  ).data?.wallets?.[0];
 
  if (!secondWallet) {
    throw new Error("Second wallet creation failed: no wallet returned");
  }
  console.log("Second wallet address:", secondWallet.address);

  // Get the token balances to find the correct USDC token ID
  console.log("\nFetching wallet token balances...");
  const balances = (await client.getWalletTokenBalance({ id: wallet.id })).data?.tokenBalances;
 
  if (!balances || balances.length === 0) {
    throw new Error("No token balances found. Make sure you received tokens from the faucet.");
  }

  // Find USDC token
  const usdcBalance = balances.find(b => b.token?.symbol === "USDC");
 
  if (!usdcBalance || !usdcBalance.token?.id) {
    console.log("\nAvailable tokens in wallet:");
    balances.forEach(b => {
      console.log(`  - ${b.token?.symbol}: ${b.amount} (Token ID: ${b.token?.id})`);
    });
    throw new Error("USDC token not found in wallet. Available tokens listed above.");
  }

  console.log(`\nFound USDC - Token ID: ${usdcBalance.token.id}`);
  console.log(`Current balance: ${usdcBalance.amount} USDC`);

  // Send USDC to second wallet using the token ID
  console.log("\nSending 5 USDC to second wallet...");
  const txResponse = await client.createTransaction({
    blockchain: wallet.blockchain as TokenBlockchain,
    walletId: wallet.id,
    destinationAddress: secondWallet.address,
    amounts: ["5"],
    tokenId: usdcBalance.token.id, // Use the token ID from the balance
    fee: { type: "level", config: { feeLevel: "MEDIUM" } },
  });
 
  const txId = txResponse.data?.id;
  if (!txId) throw new Error("Transaction creation failed: no ID returned");
  console.log("Transaction ID:", txId);

  // Poll until transaction reaches a terminal state
  const terminalStates = new Set(["COMPLETE", "FAILED", "CANCELLED", "DENIED"]);
  let currentState: string | undefined = txResponse.data?.state;
 
  while (!currentState || !terminalStates.has(currentState)) {
    await new Promise((resolve) => setTimeout(resolve, 3000));
    const poll = await client.getTransaction({ id: txId });
    const tx = poll.data?.transaction;
    currentState = tx?.state;
    console.log("Transaction state:", currentState);
   
    if (currentState === "COMPLETE" && tx?.txHash) {
      console.log(`Explorer: https://testnet.arcscan.app/tx/${tx.txHash}`);
    }
  }
 
  if (currentState !== "COMPLETE") {
    throw new Error(`Transaction ended in state: ${currentState}`);
  }

  // Verify both wallets' token balances
  console.log("\nSource wallet balances:");
  const srcBalances = (await client.getWalletTokenBalance({ id: wallet.id })).data?.tokenBalances;
  for (const b of srcBalances ?? []) {
    console.log(`  ${b.token?.symbol ?? "Unknown"}: ${b.amount}`);
  }
 
  console.log("\nSecond wallet balances:");
  const secondBalances = (
    await client.getWalletTokenBalance({ id: secondWallet.id })
  ).data?.tokenBalances;
  for (const b of secondBalances ?? []) {
    console.log(`  ${b.token?.symbol ?? "Unknown"}: ${b.amount}`);
  }
 
  console.log("\n Done! Successfully created two wallets and transferred USDC.");
}

main().catch((err) => {
  console.error("Error:", err.message || err);
  process.exit(1);
})

Run the wallet set script

node --env-file=.env --import=tsx create-wallet-set.ts

Expected output:

Creating wallet set...

----------------------------------
Wallet set created.
----------------------------------
Wallet set ID: 018c1234-5678-9abc-def0-123456789abc
Name: P2P Payment App Wallets
----------------------------------

Wallet set ID saved to .env file.

What just happened?

The script made a "folder" in Circle's system to keep all your wallets organized. Every wallet you make from now on will go in this wallet set.

What you see: the script prints a wallet set ID that looks like 018c1234-5678...

Where it got saved: open your .env file - you'll see CIRCLE_WALLET_SET_ID=... added at the bottom.

Do you need to run this again? No. One wallet set is enough for the whole project. You can make millions of user wallets inside this one set.


What to do if you lose your entity secret

If you already have wallet addresses in your .env file but are missing CIRCLE_ENTITY_SECRET, it means wallets were created previously using an entity secret that was not saved properly.

Where to look for the entity secret:

Once you have the entity secret back in your .env file, you can use this script to find your existing wallet set ID and wallets:

Create file: find-wallet-sets.ts

import { initiateDeveloperControlledWalletsClient } from "@circle-fin/developer-controlled-wallets";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

async function findWalletSets() {
  const apiKey = process.env.CIRCLE_API_KEY;
  const entitySecret = process.env.CIRCLE_ENTITY_SECRET;

  if (!apiKey || !entitySecret) {
    throw new Error("Both CIRCLE_API_KEY and CIRCLE_ENTITY_SECRET are required.");
  }

  const client = initiateDeveloperControlledWalletsClient({ apiKey, entitySecret });

  console.log("Looking up your wallet sets...
 ");

  const setsResponse = await client.listWalletSets({});
  const walletSets = setsResponse.data?.walletSets;

  if (!walletSets || walletSets.length === 0) {
    console.log("No wallet sets found for this entity.");
    return;
  }

  console.log(`Found ${walletSets.length} wallet set(s):
 `);

  for (const ws of walletSets) {
    console.log("----------------------------------");
    console.log("Wallet set ID:", ws.id);
    console.log("Name:", ws.name);
    console.log("----------------------------------");

    const walletsResponse = await client.listWallets({ walletSetId: ws.id });
    const wallets = walletsResponse.data?.wallets ?? [];

    console.log(`Wallets in this set: ${wallets.length}`);
    wallets.forEach((w, i) => {
      console.log(`  Wallet ${i + 1}: ${w.address} (ID: ${w.id})`);
    });
    console.log("");
  }

  // Save the first wallet set ID to .env if not already there
  const envPath = path.join(__dirname, ".env");
  const envContent = fs.readFileSync(envPath, "utf-8");

  if (!envContent.includes("CIRCLE_WALLET_SET_ID=") && walletSets[0]?.id) {
    fs.appendFileSync(envPath, `CIRCLE_WALLET_SET_ID=${walletSets[0].id}
 `, "utf-8");
    console.log("First wallet set ID has been saved to .env as CIRCLE_WALLET_SET_ID.");
  }
}

findWalletSets().catch((err) => {
  console.error("Error:", err.message || err);
  process.exit(1);
});

Run it

node --env-file=.env --import=tsx find-wallet-sets.ts

This will verify your entity secret works, list all your existing wallet sets, list all wallets inside them, and automatically add the wallet set ID to your .env file if it is missing.


Step 5: Create a Single Wallet

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#2-4-create-the-wallet

EOA vs SCA - which to choose?

EOA (externally owned account): a simple wallet like MetaMask. Controlled by one private key. Cheaper gas fees. Best for straightforward transfers.

SCA (smart contract account): an advanced wallet with gas sponsorship, batch transactions, and recovery options. Slightly higher gas fees. Best for P2P apps and anything more complex.

We use EOA for now because it is simpler to start with. You can switch to SCA later by changing accountType: "EOA" to accountType: "SCA".

What are metadata and refId?

When making a wallet, you can add extra info:

This is how you link a Circle wallet back to a real user in your system. When user "alice" signs up, you make a wallet with refId: "user-alice-001". Later, you can search for wallets by refId to find Alice's wallet without saving the wallet ID yourself.

Create the single wallet script

  1. Create a new file: create-single-wallet.ts
  2. Copy this code:
import {
  initiateDeveloperControlledWalletsClient,
} from "@circle-fin/developer-controlled-wallets";

async function createSingleWallet() {
  const apiKey = process.env.CIRCLE_API_KEY;
  const entitySecret = process.env.CIRCLE_ENTITY_SECRET;
  const walletSetId = process.env.CIRCLE_WALLET_SET_ID;

  if (!apiKey || !entitySecret || !walletSetId) {
    throw new Error("Missing required environment variables. Run create-wallet-set.ts first!");
  }

  console.log("Creating wallet on Arc Testnet...\n");

  const client = initiateDeveloperControlledWalletsClient({
    apiKey,
    entitySecret,
  });

  const response = await client.createWallets({
    walletSetId: walletSetId,
    blockchains: ["ARC-TESTNET"],
    count: 1,
    accountType: "EOA",
    metadata: [
      {
        name: "Alice Treasury Wallet",
        refId: "user-alice-001",
      },
    ],
  });

  const wallet = response.data?.wallets?.[0];

  if (!wallet) {
    throw new Error("Wallet creation failed");
  }

  console.log("----------------------------------");
  console.log("✓ Wallet Created Successfully!");
  console.log("----------------------------------");
  console.log("Wallet ID:", wallet.id);
  console.log("Address:", wallet.address);
  console.log("Blockchain:", wallet.blockchain);
  console.log("Account Type:", wallet.accountType);
  console.log("Name:", wallet.name);
  console.log("Reference ID:", wallet.refId);
  console.log("----------------------------------\n");
  
  console.log("Fund this wallet at: https://faucet.circle.com");
  console.log("Select: Arc Testnet");
  console.log("Address:", wallet.address);
}

createSingleWallet().catch((error) => {
  console.error("Error:", error.message);
  process.exit(1);
});

Run the script

node --env-file=.env --import=tsx create-single-wallet.ts

Expected output:

Creating wallet on Arc Testnet...

----------------------------------
Wallet created successfully.
----------------------------------
Wallet ID: 66b67097-307e-5b46-a1d5-0b1577d67fd4
Address: 0xe55628c98f5d81daaa79b72899b38a3535d10990
Blockchain: ARC-TESTNET
Account type: EOA
Name: Alice Treasury Wallet
Reference ID: user-alice-001
----------------------------------

To fund this wallet with test USDC:
  1. Go to https://faucet.circle.com
  2. Select Arc Testnet
  3. Paste your wallet address: 0xe55628c98f5d81daaa79b72899b38a3535d10990
  4. Click Send USDC

What just happened?

The script made one empty blockchain wallet for a user called Alice. This wallet lives on Arc Testnet and is ready to get test USDC.

What you see: the script prints a wallet address starting with 0x. This is Alice's real blockchain address.

Where to check it exists: copy the address, go to https://testnet.arcscan.app, and paste it in the search box. You'll see the wallet exists with a balance of zero.

Is the wallet empty? Yes, all wallets start empty. You add money using the faucet at https://faucet.circle.com.

What about sending USDC between wallets? That's covered in Day 5. Today is just about making wallets and checking balances.


Step 6: Create Multiple Wallets in Batch

Reference: https://developers.circle.com/wallets/dev-controlled/onboard-users

Why batch creation?

You can make up to 200 wallets in one API call. This is useful when bringing in existing users - instead of making 200 separate API calls, you make just one. Each wallet gets its own address and is tied to a user through refId.

Create the batch wallets script

  1. Create a new file: create-batch-wallets.ts
  2. Copy this code:
import {
  initiateDeveloperControlledWalletsClient,
} from "@circle-fin/developer-controlled-wallets";

async function createBatchWallets() {
  const apiKey = process.env.CIRCLE_API_KEY;
  const entitySecret = process.env.CIRCLE_ENTITY_SECRET;
  const walletSetId = process.env.CIRCLE_WALLET_SET_ID;

  if (!apiKey || !entitySecret || !walletSetId) {
    throw new Error("Missing environment variables");
  }

  console.log("Creating 5 wallets for multiple users...\n");

  const client = initiateDeveloperControlledWalletsClient({
    apiKey,
    entitySecret,
  });

  const response = await client.createWallets({
    walletSetId: walletSetId,
    blockchains: ["ARC-TESTNET"],
    count: 5,
    accountType: "EOA",
    metadata: [
      { name: "Bob Wallet", refId: "user-bob-002" },
      { name: "Charlie Wallet", refId: "user-charlie-003" },
      { name: "Diana Wallet", refId: "user-diana-004" },
      { name: "Eve Wallet", refId: "user-eve-005" },
      { name: "Frank Wallet", refId: "user-frank-006" },
    ],
  });

  console.log("----------------------------------");
  console.log("✓ Batch Wallets Created!");
  console.log("----------------------------------\n");

  response.data?.wallets?.forEach((wallet, index) => {
    console.log(`Wallet ${index + 1}:`);
    console.log("  Name:", wallet.name);
    console.log("  Address:", wallet.address);
    console.log("  Ref ID:", wallet.refId);
    console.log("  Wallet ID:", wallet.id);
    console.log("");
  });

  console.log("----------------------------------");
  console.log(`Total: ${response.data?.wallets?.length} wallets created`);
  console.log("----------------------------------");
}

createBatchWallets().catch((error) => {
  console.error("Error:", error.message);
  process.exit(1);
});

Run the script

node --env-file=.env --import=tsx create-batch-wallets.ts

Expected output:

Creating 5 wallets for multiple users...

----------------------------------
Batch wallets created.
----------------------------------

Wallet 1:
  Name: Bob Wallet
  Address: 0x29b27e792b8b854e48e85ab4f456cf5a9f1579fb
  Ref ID: user-bob-002
  Wallet ID: cda61d8d-7d46-5a39-a8a6-6b4a3d6fdac3

Wallet 2:
  Name: Charlie Wallet
  Address: 0x7a3d8b9e6f2c1d4a5e8b7c9d1f3a5b8e7c9d2f4a
  Ref ID: user-charlie-003
  Wallet ID: f8e9d7c6-5b4a-3d2c-1a0b-9f8e7d6c5b4a

...

----------------------------------
Total: 5 wallets created
----------------------------------

Connecting wallets to your users: the refId is how you map Circle wallets back to your database. When Bob (your database ID: user-bob-002) wants to get paid, you look up his wallet by refId and get his blockchain address.

User "Bob" (your database ID: user-bob-002)
  --> Circle wallet (refId: user-bob-002)
  --> Address: 0x29b27e...

What just happened?

The script made five separate wallets in one API call - one for Bob, one for Charlie, one for Diana, one for Eve, and one for Frank. Each has its own unique blockchain address.

What you see: five different wallet addresses printed to the terminal. Each one is a real blockchain wallet on Arc Testnet.

Where to check: take any one of those addresses, go to https://testnet.arcscan.app, and paste it in the search. You'll see that wallet exists with a balance of zero.

Do all wallets start empty? Yes. All wallets start with zero balance. You add money from the faucet or by sending test USDC to them.


Step 7: Check Wallet Balance

Reference: https://developers.circle.com/wallets/dev-controlled/create-your-first-wallet#2-6-create-second-wallet-send-usdc-and-verify-balances

Create the balance checker script

  1. Create a new file: check-wallet-balance.ts
  2. Copy this code:
import {
  initiateDeveloperControlledWalletsClient,
} from "@circle-fin/developer-controlled-wallets";

async function checkBalance() {
  const apiKey = process.env.CIRCLE_API_KEY;
  const entitySecret = process.env.CIRCLE_ENTITY_SECRET;

  if (!apiKey || !entitySecret) {
    throw new Error("Missing environment variables");
  }

  // REPLACE with your actual wallet ID from previous steps
  const walletId = "66b67097-307e-5b46-a1d5-0b1577d67fd4";

  const client = initiateDeveloperControlledWalletsClient({
    apiKey,
    entitySecret,
  });

  console.log("Fetching wallet details...\n");

  // Get wallet info
  const walletResponse = await client.getWallet({ id: walletId });
  const wallet = walletResponse.data?.wallet;

  console.log("----------------------------------");
  console.log("Wallet Details");
  console.log("----------------------------------");
  console.log("Name:", wallet?.name);
  console.log("Address:", wallet?.address);
  console.log("Blockchain:", wallet?.blockchain);
  console.log("Account Type:", wallet?.accountType);
  console.log("State:", wallet?.state);
  console.log("----------------------------------\n");

  // Get token balances
  const balanceResponse = await client.getWalletTokenBalance({ id: walletId });
  const balances = balanceResponse.data?.tokenBalances;

  console.log("Token Balances:");
  console.log("----------------------------------");

  if (!balances || balances.length === 0) {
    console.log("No tokens found. Wallet is empty.");
    console.log("\nFund this wallet at: https://faucet.circle.com");
    console.log("Address:", wallet?.address);
  } else {
    balances.forEach((balance) => {
      console.log(`${balance.token?.symbol}: ${balance.amount}`);
    });
  }
  
  console.log("----------------------------------");
}

checkBalance().catch((error) => {
  console.error("Error:", error.message);
  process.exit(1);
});

Important: replace the walletId value with your actual wallet ID from the output of step 5.

Run the script

node --env-file=.env --import=tsx check-wallet-balance.ts

Expected output (empty wallet):

Fetching wallet details...

----------------------------------
Wallet details
----------------------------------
Name: Alice Treasury Wallet
Address: 0xe55628c98f5d81daaa79b72899b38a3535d10990
Blockchain: ARC-TESTNET
Account type: EOA
State: LIVE
----------------------------------

Token balances:
----------------------------------
No tokens found. Wallet is empty.

Fund this wallet at: https://faucet.circle.com
Select: Arc Testnet
Address: 0xe55628c98f5d81daaa79b72899b38a3535d10990
----------------------------------

After funding from the faucet:

Token balances:
----------------------------------
USDC: 10
----------------------------------

What just happened?

The script asked Circle's API how much USDC (or any token) is in the wallet. Circle checked the blockchain and sent back the balance.

If the wallet is empty: the output says "no tokens found." This is normal for a brand new wallet.

After using the faucet: the output will show USDC: 10 (or however much the faucet sent).

Where else to check: the block explorer also shows balances. Copy the wallet address, go to https://testnet.arcscan.app, and paste it - you'll see the same USDC balance shown there.

What about sending USDC? Sending USDC between wallets is covered in Day 5. Today is just about making wallets and checking what's in them.


Troubleshooting

Error: Malformed API key - should contain 3 substrings separated by colon

Your API key must look like TEST_API_KEY:abc...:xyz... - with exactly two colons. Check your .env file and copy the entire key from Circle Console including all colons. Make sure there are no spaces before or after the value.

Error: CIRCLE_API_KEY is required

Make sure your .env file exists in your arc-project folder and contains a line starting with CIRCLE_API_KEY=. There should be no quotes around the value.

Entity secret already exists in .env file

This isn't an error - it means the entity secret was already registered successfully. Skip register-secret.ts and move on to create-wallet-set.ts.

Error: Missing required environment variables

Run the scripts in order: first register-secret.ts, then create-wallet-set.ts, then the wallet creation scripts. Your .env file needs all three values:

CIRCLE_API_KEY=TEST_API_KEY:...
CIRCLE_ENTITY_SECRET=...
CIRCLE_WALLET_SET_ID=...

Error: Cannot find module

Run the install command again:

npm install @circle-fin/developer-controlled-wallets typescript tsx

What You Learned Today

Technical skills

Key concepts

Your Project Structure Now

arc-project/
├── .env                         (updated with all secrets)
├── package.json
├── node_modules/
├── output/
│   └── recovery-file.json       (back this up somewhere safe)
├── register-secret.ts           (step 3 - run once)
├── create-wallet-set.ts         (step 4 - run once)
├── create-single-wallet.ts      (step 5 - creates one wallet)
├── create-batch-wallets.ts      (step 6 - creates many wallets)
├── check-wallet-balance.ts      (step 7 - checks balance)
├── find-wallet-sets.ts          (recovery - finds existing wallets)
└── ... (files from previous days)

Key takeaway

You can now create wallets programmatically using Circle's developer-controlled wallets SDK. This is the foundation for building a P2P payment app where users don't need MetaMask or private keys - you handle everything securely through Circle's API.

Official documentation: https://developers.circle.com/wallets/dev-controlled

Ready for Day 5!