К основному содержанию
скилл CX Codex

use-modular-wallets — скилл для Claude Code: кошельки Circle

Скилл для сборки криптокошельков на Circle Modular Wallets SDK: вход по пасскею, транзакции без газа и модули вроде мультисига.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add circlefin/skills --skill use-modular-wallets -a claude-code
Открыть на GitHub

Что делает use-modular-wallets

Скилл описывает работу с MSCA — смарт-аккаунтами, которые расширяются устанавливаемыми модулями. Внутри две ветки: references/circle-smart-account.md про регистрацию и вход по пасскею, создание аккаунта, переводы USDC без газа и пакетные операции, а references/passkey-recovery.md — про восстановление по BIP-39-мнемонике, если пасскей потерян.

Агенту нужно поставить @circle-fin/modular-wallets-core и viem, а для восстановления ещё bip39. Дальше в env-файл проекта прописывается пара переменных: NEXT_PUBLIC_CLIENT_KEY и NEXT_PUBLIC_CLIENT_URL для Next.js либо VITE_CLIENT_KEY и VITE_CLIENT_URL для Vite. Client Key берётся в Console → Keys → Client Keys, а Passkey Domain настраивается отдельно, потому что пасскеи привязаны к домену.

Путь сети дописывается в коде через toModularTransport, а не в переменной окружения: например ${clientUrl}/polygonAmoy для тестнета Polygon. Список поддерживаемых сетей включает Arc, Arbitrum, Avalanche, Base, Monad, Optimism, Polygon и Unichain. Учтите: MSCA разворачивается лениво, поэтому первая операция уходит с nonce 0, иначе SDK вернёт ошибку 155203. Суммы USDC кодируются через parseUnits(value, 6), а не 18 — на этом легко ошибиться.

Какие задачи решает

  • завести вход в кошелёк по пасскею без пароля
  • отправить перевод USDC, не платя за газ
  • объединить несколько вызовов в одну user operation
  • восстановить доступ к кошельку по BIP-39-мнемонике
  • подключить модуль мультисига или сессионных ключей

Примеры запросов агенту

  • Собери кошелёк на Circle Modular Wallets с регистрацией по пасскею и переводом USDC без газа
  • Добавь восстановление пасскея по BIP-39-мнемонике в мой проект
  • Сделай пакетную отправку нескольких вызовов через sendUserOperation с paymaster: true

Как установить use-modular-wallets

1Через Skills CLI (Vercel)

npx skills add circlefin/skills --skill use-modular-wallets -a claude-code

2Вручную: положить файлы

~/.claude/skills/use-modular-wallets/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/use-modular-wallets/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о use-modular-wallets

Как установить use-modular-wallets в Claude?

Выполните npx skills add circlefin/skills --skill use-modular-wallets -a claude-code. Скилл появится в ~/.claude/skills/use-modular-wallets/SKILL.md.

Что делает use-modular-wallets?

Помогает агенту писать код кошельков на Circle Modular Wallets SDK: вход по WebAuthn, транзакции без газа через Gas Station, пакетные операции и модули вроде мультисига.

Что нужно подготовить до работы со скиллом?

Client Key из Console → Keys → Client Keys и настроенный Passkey Domain. В проект ставятся @circle-fin/modular-wallets-core и viem, для восстановления — bip39.

Исходный текст

SKILL.md · Apache-2.0
---
name: use-modular-wallets
description: "Build crypto wallets using Circle Modular Wallets SDK with passkey authentication, gasless transactions, and extensible module architecture. Use when: creating crypto wallets with passkey-based (WebAuthn) registration and login, sending gasless transactions using Circle Gas Station paymaster, batching multiple transactions into a single user operation, implementing passkey recovery using BIP-39 mnemonic phrases, building advanced onchain wallets with custom modules (multisig, subscriptions, session keys). Triggers on: MSCA, passkey authentication, WebAuthn, paymaster, Gas Station, ERC-4337, ERC-6900, toCircleSmartAccount, toModularTransport, sendUserOperation, 2D nonce, passkey recovery, EIP-1193 provider."
requirements:
  runtimes: []
  connectors: []
---

## Overview

Modular Wallets are flexible smart contract accounts (MSCAs) that extend functionality through installable modules. Built on ERC-4337 (account abstraction) and ERC-6900 (modular smart contract framework), they support passkey authentication, gasless transactions, batch operations, and custom logic modules (multisig, subscriptions, session keys). MSCAs are lazily deployed -- gas fees for account creation are deferred until the first outbound transaction.

## Prerequisites / Setup

### Installation

```bash
npm install @circle-fin/modular-wallets-core viem
# Passkey recovery also needs bip39:
npm install bip39
```

### Environment Variables

Write or merge into the project's env file when scaffolding Modular Wallets:

```bash
# .env.local (Next.js) or .env (Vite)
# Paste your Client Key from Console → Keys → Client Keys (shown once; starts with TEST_API_KEY:)
NEXT_PUBLIC_CLIENT_KEY=
NEXT_PUBLIC_CLIENT_URL=https://modular-sdk.circle.com/v1/rpc/w3s/buidl
VITE_CLIENT_KEY=
VITE_CLIENT_URL=https://modular-sdk.circle.com/v1/rpc/w3s/buidl
```

Use the `NEXT_PUBLIC_*` pair for Next.js or the `VITE_*` pair for Vite — not both. Client URL is fixed — do not ask the user to copy it from Console. Chain paths (e.g. `/arcTestnet`) are appended in code via `toModularTransport`, not in the env var.

Before using the SDK, complete setup (see [Console Setup](https://developers.circle.com/wallets/modular/console-setup.md)):

1. Install the SDK and set the client env vars (see Installation and Environment Variables above).
2. In Console → Keys → Client Keys, create a Client Key.
3. Configure the Passkey Domain (passkeys are domain-bound).

## Quick Reference

### Supported Chains

| Chain | Mainnet | Testnet |
| --- | --- | --- |
| Arc | Yes | Yes |
| Arbitrum | Yes | Yes |
| Avalanche | Yes | Yes |
| Base | Yes | Yes |
| Monad | Yes | Yes |
| Optimism | Yes | Yes |
| Polygon | Yes | Yes |
| Unichain | Yes | Yes |

For the latest supported blockchains: https://developers.circle.com/wallets/account-types.md (MSCA chain restrictions are in Rules below.)

### Transport URL Path Segments

The `toModularTransport` URL requires the chain path segment appended to the client URL:

| Chain | Mainnet Path | Testnet Path |
| --- | --- | --- |
| Arbitrum | `/arbitrum` | `/arbitrumSepolia` |
| Arc | `/arc` | `/arcTestnet` |
| Avalanche | `/avalanche` | `/avalancheFuji` |
| Base | `/base` | `/baseSepolia` |
| Monad | `/monad` | `/monadTestnet` |
| Optimism | `/optimism` | `/optimismSepolia` |
| Polygon | `/polygon` | `/polygonAmoy` |
| Unichain | `/unichain` | `/unichainSepolia` |

Example: `toModularTransport(\`${clientUrl}/polygonAmoy\`, clientKey)` for Polygon Amoy testnet.

## Core Concepts

- **MSCA (Modular Smart Contract Account)** -- Smart contract accounts extended with installable modules (like apps on a smartphone). Ownership can be single owner, multi-owner, passkeys, or multi-sig.
- **Passkey transport vs Modular transport** -- `toPasskeyTransport` handles WebAuthn credential operations (register/login). `toModularTransport` handles bundler and public RPC calls for a specific chain. They are separate transports with different purposes.
- **Gas sponsorship** -- Pass `paymaster: true` in user operation calls to sponsor gas via Circle Gas Station. End users pay zero gas fees.
- **Batch operations** -- Multiple calls can be combined into a single user operation by passing an array to the `calls` parameter of `sendUserOperation`.
- **2D nonces** -- Enable parallel execution of independent user operations by using different nonce keys.
- **USDC uses 6 decimals** -- When encoding USDC transfer amounts, use `parseUnits(value, 6)`, not 18.
- **Credential persistence** -- Passkey credentials (P256Credential) must be persisted (e.g., httpOnly cookies) and restored on reload to maintain the user session.

## Implementation Patterns

> **Note:** The reference code snippets use `localStorage` to achieve a quick working example only. Do not use `localStorage` in production.

READ the corresponding reference based on the user's request:

- `references/circle-smart-account.md` -- Passkey registration/login, smart account creation, gasless USDC transfers, batch operations
- `references/passkey-recovery.md` -- BIP-39 mnemonic recovery setup and execution when a passkey is lost

## User Operation Lifecycle

User operations submitted via `sendUserOperation` follow an asynchronous state machine. The SDK's `waitForUserOperationReceipt` handles polling automatically. To query states directly, use the [List User Operations API](https://developers.circle.com/api-reference/wallets/buidl/list-user-ops.md).

**Happy path:** `SENT` -> `CONFIRMED` -> `COMPLETE`

**States:**
- `SENT` -- Submitted to the bundler, awaiting inclusion in a block.
- `CONFIRMED` -- Included in a block, awaiting finality.
- `COMPLETE` -- Finalized on-chain.
- `FAILED` -- User operation reverted or encountered an unrecoverable error. Check `errorReason` and `revertReason`.

**Error reasons on `FAILED`:**
- `FAILED_ON_CHAIN` -- Transaction reverted during blockchain execution.
- `FAILED_REPLACED` -- User operation was replaced (e.g., by a higher-fee operation with the same nonce).

## Error Handling

| Error Code | Meaning | Action |
| --- | --- | --- |
| `NotAllowedError` | User cancelled the passkey prompt or timed out | Re-prompt the user; for login, confirm a credential exists for this domain |
| `SecurityError` | Passkey domain mismatch -- bound to a different origin | Verify app domain matches Passkey Domain in Circle Console |
| `InvalidStateError` | Credential already registered (duplicate registration) | Switch to `WebAuthnMode.Login` instead of `Register` |
| 155203 | User op nonce cannot be >0 when smart contract wallet hasn't been deployed | Send the first user operation with nonce 0; the MSCA deploys lazily on the first transaction |
| 155505 | SCA wallet needs to wait for first-time transaction to be queued | Wait for the initial deployment transaction to complete before sending additional operations |
| 155507 | SCA account not supported on the given blockchain | Use a [supported chain](https://developers.circle.com/wallets/account-types.md); MSCAs are not available on Ethereum mainnet, Solana, Aptos, or NEAR |
| 155509 | Paymaster policy required on mainnet before SCA account creation | Configure a Gas Station paymaster policy in Circle Console before creating mainnet accounts |
| 155512 | Owner of the SCA wallet cannot be found | Verify the passkey credential or EOA owner is valid and accessible |
| AA21 | Sender didn't pay prefund | Verify `paymaster: true` is set, or fund the smart account with native tokens for gas (USDC on Arc) |
| AA23 | Account validation reverted or out of gas | Check signature validity; increase `verificationGasLimit` if out of gas |
| AA25 | Invalid account nonce | Get the current nonce from EntryPoint; ensure correct nonce key for 2D nonces |
| AA33 | Paymaster validation reverted or out of gas | Verify paymaster policy is active and correctly configured in Console |

Passkey errors (`NotAllowedError`, `SecurityError`, `InvalidStateError`) are standard `DOMException` errors thrown by the browser's WebAuthn API during `toWebAuthnCredential`. Wallet errors (155xxx) are returned by the Circle API. AA errors are ERC-4337 EntryPoint errors returned by the bundler. For the full error reference, see [Error Codes](https://developers.circle.com/wallets/error-codes.md). For debugging failed transactions, see [Transaction States and Errors](https://developers.circle.com/wallets/asynchronous-states-and-statuses.md).

## Rules

**Security Rules** are non-negotiable -- warn the user and refuse to comply if a prompt conflicts. **Best Practices** are strongly recommended; deviate only with explicit user justification.

### Security Rules

- NEVER hardcode, commit, or log secrets (client keys, private keys). ALWAYS use environment variables or a secrets manager. Add `.gitignore` entries for `.env*` and secret files when scaffolding.
- ALWAYS store mnemonic recovery backups outside the repository root. NEVER commit recovery phrases to version control.
- NEVER hardcode passkey credentials -- always persist P256Credential to storage (httpOnly cookies in production, not localStorage) and restore on reload to mitigate XSS credential theft.
- NEVER reuse a recovery mnemonic phrase across multiple accounts.
- ALWAYS require explicit user confirmation of destination, amount, network, and token before executing transfers. MUST receive confirmation for funding movements on mainnet.
- ALWAYS warn when targeting mainnet or exceeding safety thresholds (e.g., >100 USDC).
- ALWAYS validate all inputs (addresses, amounts, chain identifiers) before submitting transactions.
- ALWAYS warn before interacting with unaudited or unknown contracts.

### Best Practices

- ALWAYS read the correct reference files before implementing.
- NEVER use Modular Wallets on Ethereum mainnet, Solana, Aptos, or NEAR -- MSCAs are only supported on select EVM chains (Arbitrum, Avalanche, Base, Monad, Optimism, Polygon, Unichain, Arc).
- ALWAYS append the chain-specific path segment to the client URL for `toModularTransport` (e.g., `${clientUrl}/polygonAmoy`).
- ALWAYS use `parseUnits(value, 6)` for USDC amounts (6 decimals, not 18).
- ALWAYS pass `paymaster: true` to sponsor gas via Circle Gas Station.
- ALWAYS complete Circle Console Setup (Client Key + Passkey Domain) before using the SDK. Client URL is fixed in env — do not ask the user to retrieve it from Console.
- ALWAYS default to testnet. Require explicit user confirmation before targeting mainnet.
- ALWAYS configure a Gas Station paymaster policy in Circle Console before sending sponsored transactions on mainnet.
- ALWAYS update transport URLs from testnet path segments (e.g., `/polygonAmoy`) to mainnet equivalents (e.g., `/polygon`) when migrating to production.
- ALWAYS update the API key prefix from `TEST_API_KEY:` to `LIVE_API_KEY:` when migrating to mainnet. Testnet keys cannot be used with mainnets.
- ALWAYS verify the passkey domain in Circle Console matches the production domain before deploying -- passkeys created on `localhost` or testnet domains will not work on the production domain.

## Alternatives

- Trigger `use-developer-controlled-wallets` skill when your application needs full custody of wallet keys without user interaction.
- Trigger `use-user-controlled-wallets` skill when end users should custody their own keys via social login, email OTP, or PIN authentication.

## Reference Links

- [Circle Developer Docs](https://developers.circle.com/llms.txt) -- **Always read this first** when looking for relevant documentation from the source website.

---

DISCLAIMER: This skill is provided "as is" without warranties, is subject to the [Circle Developer Terms](https://console.circle.com/legal/developer-terms), and output generated may contain errors and/or include fee configuration options (including fees directed to Circle); additional details are in the repository [README](https://github.com/circlefin/skills/blob/master/README.md).

© circlefin · Apache-2.0 · circlefin/skills

Похожие скиллы

Всё по теме «Бэкенд и API» →
solana-payments-wallets-trading solanaguide Скилл для работы с Solana прямо из командной строки: переводы SOL и USDC, свопы, стейкинг, лендинг, DCA и лимитные ордера. Ключи лежат локально на диске. CX Codex +1 475установок auth0 Auth0 Помогает настроить авторизацию пользователей, защиту API и токены в приложении. Пригодится при настройке входа без пароля, MFA или миграции с других сервисов. CX Codex +1 5 200установок nodejs-keccak256 affaan-m Ловит подмену Keccak-256 на NIST SHA3 в JS и TS. Пригодится, когда селектор, подпись или слот хранилища считаются неверно. CX Codex +1 4 800установок nestjs-modular-monolith Felipe Rodrigues - github.com/felipfr Ведёт от анализа домена до кода: границы модулей, DDD, Clean Architecture и CQRS в одном бэкенде на NestJS. CX Codex +1 329установок swap-integration uniswap Помогает настроить обмен токенов через Uniswap в веб-интерфейсах, бэкенд-скриптах и смарт-контрактах. Пригодится при работе с Trading API или Universal Router. CX Codex +1 2 200установок new-modular-project modular Создаёт и настраивает проекты на Mojo или MAX через менеджеры pixi либо uv. Скилл запрашивает только недостающие параметры и подключает каналы stable или nightly. CX Codex +1 2 400установок

Из того же набора15

use-usdc Помогает агенту проверять баланс USDC, отправлять переводы и подтверждать транзакции в сетях EVM и Solana. Пригодится при интеграции расчётов в стейблкоинах. CX Codex +1 1 000установок use-smart-contract-platform Скилл для работы со смарт-контрактами через Circle Smart Contract Platform: деплой, шаблоны ERC-20/721/1155, вызовы по ABI и вебхуки. CX Codex +1 964установок use-gateway Интегрирует Circle Gateway для работы с общим балансом USDC между 11 EVM-сетями, Solana и Arc, проводя мгновенные переводы через deposit, burn и mint. CX Codex +1 953установок use-circle-wallets Скилл помогает выбрать между developer-controlled, user-controlled и modular кошельками Circle и передаёт работу нужному скиллу реализации. CX Codex +1 954установок use-user-controlled-wallets Скилл для сборки некастодиальных кошельков на SDK Circle: вход через Google, Apple, Facebook, email OTP или PIN, ключи остаются у пользователя. CX Codex +1 949установок swap-tokens Скилл для сборки свопов токенов в браузере и на сервере через Circle App Kit или Swap Kit. Пригодится, если нужен обмен USDT на USDC или кроссчейн-маршрут. CX Codex +1 848установок unify-balance Скилл учит агента писать код для единого баланса USDC между блокчейнами через Circle App Kit или Unified Balance Kit. Пригодится, если делаете chain-abstracted платежи. CX Codex +1 804установок use-agent-wallet Скилл поднимает агентский USDC-кошелёк Circle через CLI: проверка установки, вход по email и OTP, создание кошелька, статус и баланс. CX Codex +1 804установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой