Day 5: User-Controlled Wallets (PIN)

What You Will Learn Today

Time needed: 35-50 minutes

Why Are We Doing This?

Developer-controlled vs user-controlled

On Day 4 you built developer-controlled wallets. Your server holds the keys and signs every transaction. That is right for a treasury or backend automation.

Today you build user-controlled wallets. The user holds their own keys on their device. They set a PIN. You as the developer cannot sign transactions for them. The user must enter their PIN to approve anything.

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

Why does a P2P app need user-controlled wallets?

When Alice sends money to Bob, Alice should be the one who approves it, not your server. User-controlled wallets give users real control of their funds while you still build the app around them. No MetaMask, no seed phrases. Just a PIN, like a banking app.

Security note from Circle docs: Keyshares stay only on the user's device and are never sent to your server or to Circle. The SDK encrypts all request bodies in transit. Neither your app nor Circle can access funds without the user's PIN.

Reference: https://developers.circle.com/wallets/user-controlled/sdk-architecture


Step 1: Understand the Three Authentication Methods

Reference: https://developers.circle.com/wallets/user-controlled/authentication-methods

Before you touch the Console, you need to understand what Circle is asking you to set up. Circle supports three authentication methods for user-controlled wallets. You must pick one and configure it in the Configurator.

Method How users sign up How users approve transactions Setup needed in Configurator
PIN You give them a userId. Circle does not check identity. User enters a 6-digit PIN in a Circle-hosted popup. Security questions for recovery. Nothing extra. PIN is on by default. Just copy the App ID.
Email OTP User enters their email. Circle sends a one-time code via your SMTP server. Circle shows a confirmation screen. User taps confirm. You must set up your SMTP credentials in Configurator before it works.
Social Login User clicks Sign in with Google, Apple, or Facebook. Circle shows a confirmation screen. User taps confirm. You must get a Google Client ID or Facebook/Apple App ID and add them in Configurator.

We are using PIN today

PIN needs zero extra setup in the Console. No SMTP server, no Google OAuth, no Apple developer account. You just copy the App ID and continue. We will cover social login on a later day.

In a real P2P app you would use Email OTP or Social Login to verify who the user is, then use the PIN as an extra step to approve each transaction. The Circle docs say: "A PIN by itself does not verify user identity. In production, apps should authenticate users first to establish a Circle user session. PINs then serve as a layer to authorize wallet actions."

Reference: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin


Step 2: Get Your App ID from the Configurator

Reference: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin

The Configurator is where Circle links your API key to your user-controlled wallet settings.

Open the Configurator

  1. Log in to https://console.circle.com
  2. In the left sidebar go to Wallets → User Controlled → Configurator

Copy your App ID

At the top of the Configurator page you will see your App ID. Copy it. You need it in the next step. It looks like this: 8df7f1cd-e4ca-4553-a8e5-b5e0f1c5fbe2

For PIN (what we are doing today): PIN is on by default. You do not need to click anything in the Configurator to enable PIN. Just copy the App ID and move on.

For Email OTP (later): Go to Configurator, then Email. Enter your SMTP host, port, username, password, From address, and an email template that includes {{ email.otp }}.

For Social Login with Google (later): Go to https://console.cloud.google.com, create a project, create OAuth 2.0 credentials, copy the Client ID. Then in Circle Console go to Configurator, then Authentication Methods, then Social Logins, and paste it in.

Reference: https://developers.circle.com/wallets/user-controlled/authentication-methods

Get App ID from the terminal instead

If you prefer not to use the Console UI, run this with your actual API key:

curl -s https://api.circle.com/v1/w3s/config/entity \
  -H "Authorization: Bearer YOUR_CIRCLE_API_KEY" \
  -H "Accept: application/json"

The appId field in the response is your App ID.

Reference: https://developers.circle.com/api-reference/wallets/programmable-wallets/get-entity-config

What just happened?

You now have the App ID that links your web app to your Circle user-controlled wallet setup. Every user you create, every challenge, every wallet belongs to this App ID. PIN is already active for it by default.


Step 3: Create the Next.js Project Inside arc-project

Reference: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin

The Circle Web SDK is a browser library that opens Circle's hosted PIN screen. We need a web app to run it. We create a Next.js app called circle-pin inside your existing arc-project folder.

Why Next.js? The Web SDK runs in the browser. Next.js also gives us server-side API routes that keep your Circle API key on the server. It never goes to the browser.

Why only one npm package? The server-side Circle calls (createUser, getUserToken, initializeUser, listWallets, getBalance) are plain fetch() calls to Circle's REST API. No extra package needed on the server. The only package we install is the browser SDK that handles the PIN popup.

3.1 Create the Next.js project

Open the terminal in VS Code. Make sure you are inside arc-project, then run:

npx create-next-app@latest circle-pin --yes
cd circle-pin

3.2 Install the Circle Web SDK

npm install @circle-fin/w3s-pw-web-sdk

Reference: https://www.npmjs.com/package/@circle-fin/w3s-pw-web-sdk

3.3 Create the .env.local file

Inside arc-project/circle-pin, create a new file called .env.local:

CIRCLE_API_KEY=TEST_API_KEY:your_key_id:your_secret
NEXT_PUBLIC_CIRCLE_APP_ID=your_app_id_here

Two variables, two different prefixes:

Copy the CIRCLE_API_KEY value from your root arc-project/.env file. Copy the App ID from Step 2.

3.4 Simplify the default layout

Open circle-pin/app/layout.tsx and replace all contents with:

// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

What just happened?

The default Next.js layout includes Google Fonts and global CSS that can cause build errors with the Circle SDK. Removing them prevents those errors. The Circle docs do this same step in their own quickstart.


Step 4: Create the Backend API Route

Reference: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin

POST /v1/w3s/users: https://developers.circle.com/api-reference/wallets/user-controlled-wallets/create-user

POST /v1/w3s/users/token: https://developers.circle.com/api-reference/wallets/user-controlled-wallets/get-user-token

POST /v1/w3s/user/initialize: https://developers.circle.com/api-reference/wallets/user-controlled-wallets/create-user-with-pin-challenge

GET /v1/w3s/wallets: https://developers.circle.com/api-reference/wallets/user-controlled-wallets/list-wallets

Create the directory and file: circle-pin/app/api/endpoints/route.ts

// app/api/endpoints/route.ts
import { NextResponse } from "next/server";

const CIRCLE_BASE_URL =
  process.env.NEXT_PUBLIC_CIRCLE_BASE_URL ?? "https://api.circle.com";
const CIRCLE_API_KEY = process.env.CIRCLE_API_KEY as string;

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { action, ...params } = body ?? {};

    if (!action) {
      return NextResponse.json({ error: "Missing action" }, { status: 400 });
    }

    switch (action) {
      case "createUser": {
        const { userId } = params;
        if (!userId) {
          return NextResponse.json(
            { error: "Missing required field: userId" },
            { status: 400 },
          );
        }
        const response = await fetch(`${CIRCLE_BASE_URL}/v1/w3s/users`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${CIRCLE_API_KEY}`,
          },
          body: JSON.stringify({ userId }),
        });
        const data = await response.json();
        if (!response.ok) {
          return NextResponse.json(data, { status: response.status });
        }
        return NextResponse.json(data.data, { status: 200 });
      }

      case "getUserToken": {
        const { userId } = params;
        if (!userId) {
          return NextResponse.json(
            { error: "Missing required field: userId" },
            { status: 400 },
          );
        }
        const response = await fetch(`${CIRCLE_BASE_URL}/v1/w3s/users/token`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${CIRCLE_API_KEY}`,
          },
          body: JSON.stringify({ userId }),
        });
        const data = await response.json();
        if (!response.ok) {
          return NextResponse.json(data, { status: response.status });
        }
        // Returns: { userToken, encryptionKey }
        return NextResponse.json(data.data, { status: 200 });
      }

      case "initializeUser": {
        const { userToken, accountType, blockchains } = params;
        if (!userToken) {
          return NextResponse.json(
            { error: "Missing userToken" },
            { status: 400 },
          );
        }
        const requestBody: any = { idempotencyKey: crypto.randomUUID() };
        if (accountType) requestBody.accountType = accountType;
        if (blockchains) requestBody.blockchains = blockchains;

        const response = await fetch(
          `${CIRCLE_BASE_URL}/v1/w3s/user/initialize`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${CIRCLE_API_KEY}`,
              "X-User-Token": userToken,
            },
            body: JSON.stringify(requestBody),
          },
        );
        const data = await response.json();
        if (!response.ok) {
          // code 155106 means user already initialized
          return NextResponse.json(data, { status: response.status });
        }
        // Returns: { challengeId }
        return NextResponse.json(data.data, { status: 200 });
      }

      case "listWallets": {
        const { userToken } = params;
        if (!userToken) {
          return NextResponse.json(
            { error: "Missing userToken" },
            { status: 400 },
          );
        }
        const response = await fetch(`${CIRCLE_BASE_URL}/v1/w3s/wallets`, {
          method: "GET",
          headers: {
            accept: "application/json",
            "content-type": "application/json",
            Authorization: `Bearer ${CIRCLE_API_KEY}`,
            "X-User-Token": userToken,
          },
        });
        const data = await response.json();
        if (!response.ok) {
          return NextResponse.json(data, { status: response.status });
        }
        // Returns: { wallets: [...] }
        return NextResponse.json(data.data, { status: 200 });
      }

      case "getOnchainBalance": {
        // Circle's balance API does not index USDC on ARC-TESTNET for user-controlled wallets.
        // We read the balance directly from ArcScan (Blockscout public API) instead.
        // ARC-TESTNET USDC is the native token. ArcScan returns it in coin_balance with 18 decimals.
        const { walletAddress } = params;
        if (!walletAddress) {
          return NextResponse.json(
            { error: "Missing walletAddress" },
            { status: 400 },
          );
        }
        const response = await fetch(
          `https://testnet.arcscan.app/api/v2/addresses/${walletAddress}`,
          { headers: { Accept: "application/json" } },
        );
        const data = await response.json();
        const raw = BigInt(data?.coin_balance ?? "0");
        // Native USDC on ARC-TESTNET uses 18 decimals in coin_balance
        const balance = (Number(raw) / 1e18).toFixed(2);
        return NextResponse.json({ balance }, { status: 200 });
      }

      default:
        return NextResponse.json(
          { error: `Unknown action: ${action}` },
          { status: 400 },
        );
    }
  } catch (error) {
    console.error("Error in /api/endpoints:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

What each handler does

HandlerCircle endpointWhat it returns
createUserPOST /v1/w3s/usersCreates a Circle user record from your userId.
getUserTokenPOST /v1/w3s/users/tokenReturns a userToken and encryptionKey. Both expire after 60 minutes.
initializeUserPOST /v1/w3s/user/initializeSets up the wallet on ARC-TESTNET. Returns challengeId. Error 155106 means already initialized.
listWalletsGET /v1/w3s/walletsReturns all wallets for this user.
getOnchainBalanceArcScan public APIReturns the USDC balance by reading directly from the block explorer. Used because Circle's balance API does not index ARC-TESTNET USDC for user-controlled wallets.

Why getOnchainBalance instead of Circle's balance API?

Circle's GET /v1/w3s/wallets/{id}/balances endpoint returns an empty tokenBalances array for user-controlled wallets on ARC-TESTNET. This is a known gap in Circle's testnet indexer. The USDC does exist on-chain (you can verify it on ArcScan), but Circle's API does not pick it up. To work around this, we call the ArcScan public API directly. It returns coin_balance, which is the native USDC balance in 18-decimal format. We divide by 1e18 to get the human-readable amount.

What just happened?

You created a single Next.js API route that sits between your browser and Circle's REST API. CIRCLE_API_KEY stays on the server. Next.js never sends environment variables to the browser unless they have the NEXT_PUBLIC_ prefix.


Step 5: Create the Frontend Page

Reference: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin

Web SDK reference: https://developers.circle.com/wallets/user-controlled/web-sdk

Open circle-pin/app/page.tsx and replace all contents with:

// app/page.tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { W3SSdk } from "@circle-fin/w3s-pw-web-sdk";

const appId = process.env.NEXT_PUBLIC_CIRCLE_APP_ID as string;
const ACCOUNT_TYPE = "SCA";
const PRIMARY_WALLET_BLOCKCHAIN = "ARC-TESTNET";

type LoginResult = {
  userToken: string;
  encryptionKey: string;
};

type Wallet = {
  id: string;
  address: string;
  blockchain: string;
  [key: string]: unknown;
};

export default function HomePage() {
  const sdkRef = useRef<W3SSdk | null>(null);

  const [sdkReady, setSdkReady] = useState(false);
  const [deviceId, setDeviceId] = useState<string>("");
  const [userId, setUserId] = useState<string>("");
  const [loginResult, setLoginResult] = useState<LoginResult | null>(null);
  const [challengeId, setChallengeId] = useState<string | null>(null);
  const [wallets, setWallets] = useState<Wallet[]>([]);
  const [usdcBalance, setUsdcBalance] = useState<string | null>(null);
  const [status, setStatus] = useState<string>("Ready");
  const [isError, setIsError] = useState<boolean>(false);

  // Initialize SDK on mount
  useEffect(() => {
    let cancelled = false;
    const initSdk = async () => {
      try {
        const sdk = new W3SSdk({ appSettings: { appId } });
        sdkRef.current = sdk;
        if (!cancelled) {
          setSdkReady(true);
          setIsError(false);
          setStatus("SDK initialized. Ready to create user.");
        }
      } catch (err) {
        console.log("Failed to initialize Web SDK:", err);
        if (!cancelled) {
          setIsError(true);
          setStatus("Failed to initialize Web SDK");
        }
      }
    };
    void initSdk();
    return () => { cancelled = true; };
  }, []);

  // Get and cache deviceId
  useEffect(() => {
    const fetchDeviceId = async () => {
      if (!sdkRef.current) return;
      try {
        const cached =
          typeof window !== "undefined"
            ? window.localStorage.getItem("deviceId")
            : null;
        if (cached) { setDeviceId(cached); return; }
        const id = await sdkRef.current.getDeviceId();
        setDeviceId(id);
        if (typeof window !== "undefined") {
          window.localStorage.setItem("deviceId", id);
        }
      } catch (error) {
        console.log("Failed to get deviceId:", error);
        setIsError(true);
        setStatus("Failed to get deviceId");
      }
    };
    if (sdkReady) void fetchDeviceId();
  }, [sdkReady]);

  // Load USDC balance from ArcScan
  // Circle's balance API does not index ARC-TESTNET USDC for user-controlled wallets.
  // We read coin_balance from ArcScan's public API and divide by 1e18.
  async function loadUsdcBalance(userToken: string, walletAddress: string) {
    try {
      const response = await fetch("/api/endpoints", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "getOnchainBalance", walletAddress }),
      });
      const data = await response.json();
      if (!response.ok) {
        setIsError(true);
        setStatus("Failed to load USDC balance");
        return null;
      }
      setUsdcBalance(data.balance);
      setIsError(false);
      setStatus("Wallet details and USDC balance loaded.");
      return data.balance;
    } catch (err) {
      console.log("Failed to load USDC balance:", err);
      setIsError(true);
      setStatus("Failed to load USDC balance");
      return null;
    }
  }

  // Load wallets for the current user
  const loadWallets = async (
    userToken: string,
    options?: { source?: "afterCreate" | "alreadyInitialized" },
  ) => {
    try {
      setIsError(false);
      setStatus("Loading wallet details...");
      setUsdcBalance(null);

      const response = await fetch("/api/endpoints", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "listWallets", userToken }),
      });
      const data = await response.json();

      if (!response.ok) {
        setIsError(true);
        setStatus("Failed to load wallet details");
        return;
      }

      const fetched = (data.wallets as Wallet[]) || [];
      setWallets(fetched);

      if (fetched.length > 0) {
        // Pass wallet address (not wallet id) to loadUsdcBalance
        await loadUsdcBalance(userToken, fetched[0].address);

        if (options?.source === "afterCreate") {
          setIsError(false);
          setStatus("Wallet created successfully! Wallet details and USDC balance loaded.");
        } else if (options?.source === "alreadyInitialized") {
          setIsError(false);
          setStatus("User already initialized. Wallet details and USDC balance loaded.");
        }
      } else {
        setIsError(false);
        setStatus("Wallet creation in progress. Click Initialize user again to refresh.");
      }
    } catch (err) {
      console.log("Failed to load wallet details:", err);
      setIsError(true);
      setStatus("Failed to load wallet details");
    }
  };

  // Step 1: Create User
  const handleCreateUser = async () => {
    if (!userId || userId.length < 5) {
      setIsError(true);
      setStatus("User ID must be at least 5 characters.");
      return;
    }
    setLoginResult(null); setChallengeId(null); setWallets([]); setUsdcBalance(null);
    try {
      setIsError(false);
      setStatus("Creating user...");
      const response = await fetch("/api/endpoints", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "createUser", userId }),
      });
      const data = await response.json();
      if (!response.ok) {
        setIsError(true);
        setStatus(data.error || data.message || "Failed to create user");
        return;
      }
      setIsError(false);
      setStatus("User created successfully! Click Get User Token to continue.");
    } catch (err) {
      setIsError(true);
      setStatus("Failed to create user");
    }
  };

  // Step 2: Get User Token
  const handleGetUserToken = async () => {
    if (!userId || userId.length < 5) {
      setIsError(true);
      setStatus("User ID must be at least 5 characters.");
      return;
    }
    try {
      setIsError(false);
      setStatus("Getting user token...");
      const response = await fetch("/api/endpoints", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "getUserToken", userId }),
      });
      const data = await response.json();
      if (!response.ok) {
        setIsError(true);
        setStatus(data.error || data.message || "Failed to get user token");
        return;
      }
      setLoginResult({ userToken: data.userToken, encryptionKey: data.encryptionKey });
      setIsError(false);
      setStatus("User token retrieved successfully! Click Initialize user to continue.");
    } catch (err) {
      setIsError(true);
      setStatus("Failed to get user token");
    }
  };

  // Step 3: Initialize User
  const handleInitializeUser = async () => {
    if (!loginResult?.userToken) {
      setIsError(true);
      setStatus("Missing userToken. Please get user token first.");
      return;
    }
    try {
      setIsError(false);
      setStatus("Initializing user...");
      const response = await fetch("/api/endpoints", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "initializeUser",
          userToken: loginResult.userToken,
          accountType: ACCOUNT_TYPE,
          blockchains: [PRIMARY_WALLET_BLOCKCHAIN],
        }),
      });
      const data = await response.json();
      if (!response.ok) {
        if (data.code === 155106) {
          await loadWallets(loginResult.userToken, { source: "alreadyInitialized" });
          setChallengeId(null);
          return;
        }
        const errorMsg = data.code
          ? `[${data.code}] ${data.error || data.message}`
          : data.error || data.message;
        setIsError(true);
        setStatus("Failed to initialize user: " + errorMsg);
        return;
      }
      setChallengeId(data.challengeId);
      setIsError(false);
      setStatus("User initialized. Click Create wallet to continue.");
    } catch (err: any) {
      if (err?.code === 155106 && loginResult?.userToken) {
        await loadWallets(loginResult.userToken, { source: "alreadyInitialized" });
        setChallengeId(null);
        return;
      }
      const errorMsg = err?.code
        ? `[${err.code}] ${err.message}`
        : err?.message || "Unknown error";
      setIsError(true);
      setStatus("Failed to initialize user: " + errorMsg);
    }
  };

  // Step 4: Execute Challenge (opens Circle PIN popup)
  const handleExecuteChallenge = async () => {
    const sdk = sdkRef.current;
    if (!sdk) { setIsError(true); setStatus("SDK not ready"); return; }
    if (!challengeId) { setIsError(true); setStatus("Missing challengeId. Initialize user first."); return; }
    if (!loginResult?.userToken || !loginResult?.encryptionKey) {
      setIsError(true); setStatus("Missing login credentials. Please get user token again."); return;
    }
    try {
      sdk.setAuthentication({
        userToken: loginResult.userToken,
        encryptionKey: loginResult.encryptionKey,
      });
      setIsError(false);
      setStatus("Executing challenge...");
      await sdk.execute(challengeId, (error, result) => {
        if (error) {
          setIsError(true);
          setStatus("Failed to execute challenge: " + ((error as any)?.message ?? "Unknown error"));
          return;
        }
        console.log("Challenge executed successfully:", result);
        setChallengeId(null);
        setTimeout(async () => {
          if (loginResult?.userToken) {
            await loadWallets(loginResult.userToken, { source: "afterCreate" });
          }
        }, 2000);
      });
    } catch (err) {
      setIsError(true);
      setStatus("Failed to execute challenge: " + ((err as any)?.message ?? "Unknown error"));
    }
  };

  const primaryWallet = wallets[0];

  return (
    <main>
      <div style={{ width: "50%", margin: "0 auto" }}>
        <h1>Create a user wallet using PIN</h1>
        <p>Enter the username or email of the user you want to create a wallet for:</p>

        <div style={{ marginBottom: "12px" }}>
          <label>
            User ID:
            <input
              type="text"
              value={userId}
              onChange={(e) => setUserId(e.target.value)}
              style={{ marginLeft: "8px", width: "70%" }}
              placeholder="Enter user ID (min 5 chars)"
              minLength={5}
            />
          </label>
        </div>

        <div>
          <button onClick={handleCreateUser} style={{ margin: "6px" }} disabled={!userId || userId.length < 5}>
            1. Create User
          </button><br />
          <button onClick={handleGetUserToken} style={{ margin: "6px" }} disabled={!userId || userId.length < 5 || !!loginResult}>
            2. Get User Token
          </button><br />
          <button onClick={handleInitializeUser} style={{ margin: "6px" }} disabled={!loginResult || !!challengeId || wallets.length > 0}>
            3. Initialize user (get challenge)
          </button><br />
          <button onClick={handleExecuteChallenge} style={{ margin: "6px" }} disabled={!challengeId || wallets.length > 0}>
            4. Create wallet (execute challenge)
          </button>
        </div>

        <p>
          <strong>Status:</strong>{" "}
          <span style={{ color: isError ? "red" : "black" }}>{status}</span>
        </p>

        {primaryWallet && (
          <div style={{ marginTop: "12px" }}>
            <h2>Wallet details</h2>
            <p><strong>Address:</strong> {primaryWallet.address}</p>
            <p><strong>Blockchain:</strong> {primaryWallet.blockchain}</p>
            {usdcBalance !== null && (
              <p><strong>USDC balance:</strong> {usdcBalance}</p>
            )}
          </div>
        )}

        <pre style={{ whiteSpace: "pre-wrap", wordBreak: "break-all", lineHeight: "1.8", marginTop: "16px" }}>
          {JSON.stringify(
            { deviceId, userId, userToken: loginResult?.userToken, encryptionKey: loginResult?.encryptionKey, challengeId, wallets, usdcBalance },
            null,
            2,
          )}
        </pre>
      </div>
    </main>
  );
}

What just happened?

This is the PIN wallet flow. The four buttons map to the four steps:

The debug block at the bottom shows all the internal values. It is from Circle's own quickstart and is useful when something does not work.


Step 6: Run the App

From inside arc-project/circle-pin, run:

npm run dev

Open http://localhost:3000 in your browser.

Complete the flow step by step

  1. Enter a User ID, for example alice-001 (minimum 5 characters)
  2. Click Create User and wait for: "User created successfully!"
  3. Click Get User Token and wait for: "User token retrieved successfully!"
  4. Click Initialize user and wait for: "User initialized. Click Create wallet to continue."
  5. Click Create wallet. A Circle-hosted popup opens in your browser.
  6. In the popup: enter a 6-digit PIN, confirm it, then answer the 3 security questions.
  7. The popup closes. Status shows: "Wallet created successfully! Wallet details and USDC balance loaded."

About the PIN popup

The popup is hosted by Circle. The Web SDK opens a screen on a Circle domain. Your server never sees the PIN. If the popup does not open, your browser is blocking it. Look for a blocked popup icon in the address bar and click Allow, then click Create Wallet again.

Reference: https://developers.circle.com/wallets/user-controlled/sdk-architecture

Expected status messages in order:

SDK initialized. Ready to create user.
Creating user...
User created successfully! Click Get User Token to continue.
Getting user token...
User token retrieved successfully! Click Initialize user to continue.
Initializing user...
User initialized. Click Create wallet to continue.
Executing challenge...
Wallet created successfully! Wallet details and USDC balance loaded.

What just happened?

You created a user-controlled SCA wallet on Arc Testnet. The wallet address starting with 0x is controlled by the user who set the PIN.

Verify it exists: copy the address, go to https://testnet.arcscan.app and paste it in the search box.

Verify in Circle Console: Wallets, then User Controlled, then Users. Find your userId and click it. The wallet is listed there.


Step 7: Fund the Wallet and Check Balance

Faucet: https://faucet.circle.com

  1. Copy the wallet address (0x...) shown in the app
  2. Go to https://faucet.circle.com
  3. Select Arc Testnet as the network
  4. Paste the wallet address in the Send to field
  5. Click Send USDC
  6. Return to http://localhost:3000
  7. Enter the same User ID, click Create User, then Get User Token, then Initialize User. Since the user is already initialized (error 155106 is handled automatically), the app loads the existing wallet with the updated balance.

Expected balance after funding:

USDC balance: 10.00

Note on balance display: Circle's balance API returns empty results for user-controlled wallets on ARC-TESTNET. This is a known gap in their testnet indexer. The app reads the balance directly from ArcScan instead. The amount shown comes from the on-chain native USDC balance.


Troubleshooting

Failed to initialize Web SDK / NEXT_PUBLIC_CIRCLE_APP_ID is undefined

Open circle-pin/.env.local and check that NEXT_PUBLIC_CIRCLE_APP_ID=your_app_id is there with no quotes and no spaces around the value. Restart the dev server after any change to .env.local: press Ctrl+C then run npm run dev again.

401 Unauthorized

CIRCLE_API_KEY must be in circle-pin/.env.local, not only in the root arc-project/.env. The Next.js API route reads only from its own directory. The key must be the full three-part format: TEST_API_KEY:id:secret.

PIN popup does not open

Your browser is blocking popups for localhost:3000. In Chrome look for the blocked popup icon in the address bar. Click it and select Allow. Then click Create Wallet again.

Error code 155106

This is not an error. It means the user was already initialized before. The app catches this and loads the existing wallet automatically. If the wallet loads after you see this, everything is working.

Reference: https://developers.circle.com/api-reference/wallets/user-controlled-wallets/create-user-with-pin-challenge

Challenge failed / token expired

The userToken expires after 60 minutes. Click Get User Token again to get a new one, then continue from Initialize User.

Cannot find module '@circle-fin/w3s-pw-web-sdk'

Run this from inside circle-pin:

npm install @circle-fin/w3s-pw-web-sdk

USDC balance shows 0

Circle's balance API does not index USDC for user-controlled wallets on ARC-TESTNET. The app uses ArcScan to read the balance instead. If it still shows 0, check that the faucet send completed by pasting your wallet address into https://testnet.arcscan.app. If the balance shows there, wait a few seconds and reload the app flow.


What You Learned Today

Technical skills

Key concepts

Your Project Structure Now

arc-project/
|-- .env                           (root: CIRCLE_API_KEY, CIRCLE_ENTITY_SECRET, etc.)
|-- package.json
|-- node_modules/
|-- output/
|   |-- recovery-file.json
|-- register-secret.ts             (Day 4)
|-- create-wallet-set.ts           (Day 4)
|-- create-single-wallet.ts        (Day 4)
|-- create-batch-wallets.ts        (Day 4)
|-- check-wallet-balance.ts        (Day 4)
|-- find-wallet-sets.ts            (Day 4 recovery)
|-- circle-pin/                    (Day 5 - Next.js app)
    |-- .env.local                 (CIRCLE_API_KEY + NEXT_PUBLIC_CIRCLE_APP_ID)
    |-- package.json
    |-- node_modules/
    |-- app/
        |-- layout.tsx             (minimal, no fonts or CSS)
        |-- page.tsx               (PIN wallet flow, 4 buttons)
        |-- api/
            |-- endpoints/
                |-- route.ts      (backend proxy, 5 handlers)

Key Takeaway

You now know the three authentication methods Circle offers and exactly what Console setup each one needs. For today we used PIN because it needs no extra configuration beyond copying the App ID. You built a complete PIN wallet flow. A user can create a wallet, set their PIN, and control their own keys without MetaMask or seed phrases.

Authentication methods: https://developers.circle.com/wallets/user-controlled/authentication-methods

Full PIN walkthrough: https://developers.circle.com/wallets/user-controlled/create-user-wallets-with-pin

Web SDK: https://developers.circle.com/wallets/user-controlled/web-sdk

Stay tuned for Day 6