# @circle-fin/adapter-viem-v2

## 1.18.0

### Minor Changes

- Add Arc mainnet (`Blockchain.Arc`, chainId 5042) as a supported chain. Arc is wired for CCTP v2 bridging (`BridgeChain.Arc`, domain 26) with Circle's Forwarding Service enabled for Arc as a destination, and for Gateway v1 (`UnifiedBalanceChain.Arc`). The viem v2 adapter resolves a custom chain definition for Arc mainnet.
- Support CCTPx cross-chain transfers

  EVM adapters can now execute Circle CrossChainTokenService transfers through the new `crossChainTransfer` action.

## 1.17.1

### Patch Changes

- Fix `getSupportedChains({ sourceFeeSupported: true })` over-reporting source-fee
  bridging support. Previously, source-fee eligibility was inferred from a contract
  address shared with the fast-deposit forwarding path, causing fast-deposit-only chains
  to appear supported and fail at the Quote API instead of being rejected client-side.
  Source-fee support is now gated on an explicit allowlist of eligible source chains.

## 1.17.0

### Minor Changes

- Add Plasma (mainnet and testnet) support. Bridge USDC to and from Plasma via CCTP v2 in Bridge Kit and App Kit using `'Plasma'` or `'Plasma_Testnet'` as source or destination. No change required unless you want these routes.

### Patch Changes

- Return the decoded value from `ViemAdapter.read` instead of a stringified one,
  and validate its input at runtime like `prepare` already does.

  `batchExecute` now retries the public-RPC receipt read while the endpoint
  reports the transaction as not yet indexed, so a confirmed batch no longer
  drops its logs when the chain definition's endpoint lags behind Circle's node.
  Enrichment is capped by both an attempt count and a single wall-clock deadline,
  with the transport's own retries disabled so the two budgets cannot compound.
  The read stays best-effort: it never throws, and a receipt that exists is
  treated as final even when it carries no usable logs.

## 1.16.0

### Minor Changes

- Add `getTokenAllowance()` for reading a token allowance directly, returning base
  units as a `bigint`. Reads no longer arrive at `prepareAction`, so wrappers
  around it aren't affected. On Solana this returns the maximum uint256 value.
- Add a `token.name` read action that returns the on-chain name of a token
  contract. Call it with any token selector, for example `{ token: 'USDC' }` or a
  raw contract address. EVM adapters read the contract. Solana adapters report the
  action as unsupported.

  This also restores the `usdc.name` alias, which the `./next` adapters did not
  register. `UnifiedBalanceKit.deposit()` stopped with an
  `INPUT_UNSUPPORTED_ACTION` error before it sent any transaction. The default
  `authorize` strategy and the `permit` strategy both read the USDC contract name.
  All `allowanceStrategy` values now succeed, so the `'approve'` workaround is no
  longer necessary. Circle Wallets user-controlled wallets were affected too,
  because `createCircleUserWalletAdapter` composes
  `@circle-fin/adapter-viem-v2/next`.

  The token registry also gains the USDC address for Celo Alfajores, so `usdc.*`
  actions now resolve on that chain.

  `usdc.name` is deprecated, like the other `usdc.*` aliases. Use `token.name`
  with `{ token: 'USDC' }` instead.

  `usdc.name` is one exception among the `usdc.*` aliases. It always reads the
  chain's default USDC address, and it ignores a custom token registry override.
  This matches the address that Gateway's `permit` and `authorize` signatures
  target, so the two stay consistent. If your token registry overrides USDC and
  you need that override's contract name, call `token.name` with the explicit
  address instead of `usdc.name`.

### Patch Changes

- `getTokenDecimals()` now takes `ChainDefinition` rather than
  `EVMChainDefinition`, so its signature matches the shared adapter contract.
  Passing an EVM chain is unchanged. A test double that types the `chain`
  parameter as `EVMChainDefinition` must widen it.

## 1.15.1

### Patch Changes

- Add ERC-20 contract-address token resolution to `/next` adapters, fixing the
  `getTokenDecimals() not configured` error. Malformed addresses now throw
  `INPUT_INVALID_ADDRESS`, and failed reads now distinguish retryable provider
  errors from permanent contract failures. Provider credentials are redacted.

## 1.15.0

### Minor Changes

- Add request-scoped authorization review hooks to the next-generation EVM
  adapters, including lazy semantic review metadata, canonical payload snapshots,
  explicit approval or rejection, cancellation, and legacy prepareAction
  propagation.

  Behavior changes (these ride along with the feature and apply whether or not an
  `onBeforeAuthorize` hook is configured):

  1. **Sender/signer mismatch now fails fast.** viem and ethers `execute` and
     `signTypedData` reject a `from` that does not match the resolved
     wallet/signer with `INPUT_VALIDATION_FAILED`. Previously the wallet's own
     account silently won and a diverging `from` was ignored.
  2. **`SigningContext.intent.action` carries the registered action name.**
     `SigningStrategy` implementations now see the action name (e.g.
     `cctp.depositForBurn`) instead of `'execute'` for action-driven flows. This
     surfaces in Circle Wallets' `onChallenge`/progress events and in
     `createSigningRejectedError` messages.
  3. **Prepared transactions inherit the prepare-time invocation.** `estimate`,
     `simulate`, and `execute` on a prepared transaction now reuse the
     `traceId` + `signal` captured at `prepare()` time (better trace
     correlation). A caller that passes a timed signal to `prepare()` and calls
     `prepared.execute()` after that signal aborts now gets `NETWORK_ABORTED`.

- Add X Layer chain definitions (mainnet and testnet) with CCTP v2 support, USDC token addresses, Viem adapter mappings, Bridge Kit exports.
- Batch same-chain Earn deposits and withdrawals through an adapter's shared
  `supportsAtomicBatch` and `batchExecute` capabilities. Approval and execution
  calls are submitted atomically when supported, with a configuration option to
  force the existing sequential flow. Legacy Viem batches now request atomic
  EIP-5792 execution by default.
- Support spending a unified balance from a smart contract account via Gateway's
  ERC-1271 programmable authorization.

  Previously, `spend` rejected any smart contract account (SCA) signer up front
  and told you to register an EOA delegate against the SCA, because Gateway
  validated burn-intent signatures with `ecrecover` only. Gateway now also
  validates contract signatures with ERC-1271, so the SDK detects a contract
  signer from its on-chain bytecode and marks the transfer request
  `contractSigner: true` — multisigs, passkey wallets, Circle SCA wallets, and
  other ERC-1271 accounts can authorize transfers directly.

  No API change: `spend` takes the same parameters and picks the validation path
  for you. EOA transfers are unaffected, and EIP-7702-delegated EOAs keep using
  the `ecrecover` path since their signatures verify that way.

  ERC-1271 validation is EVM-only. Solana burn intents are unchanged.

## 1.14.1

### Patch Changes

- Internal dependency updates. No user-facing changes.

## 1.14.0

### Minor Changes

- Add a pluggable `SigningStrategy` to the viem adapter, so you control how transactions are authorized — sign in-process, hand off to your own signing infrastructure, or call a remote signing service — without changing how you call `bridge()` / `swap()` / `send()`.

  - **`signing` option** on `createViemAdapter` / `createViemAdapterContext`. When set, `execute`, `signTypedData`, and `batchExecute` are authorized by your strategy instead of a `WalletClient` (via the bundled `externalSigning` helper, or your own). The adapter builds the ready-to-sign payload; the strategy returns the signature or broadcast result. Unsupported payloads and cancellations are handled with clear errors.
  - **Keyless construction.** `getWalletClient` is now optional. `createViemAdapter({ getPublicClient, signing })` builds a keyless adapter, and `createViemAdapter({ getPublicClient, address? })` builds a signing-optional **read-only** adapter (reads, gas estimation, and simulation only) — no hand-rolled wallet stub required. A bound `address` supplies `getAddress()` when there is no wallet.
  - **`supportsSignTypedData()`** on the adapter, answered from the strategy, so callers can choose an on-chain approval when a strategy cannot produce EIP-712 signatures.
  - **`fromAddress`** added to `BatchExecuteOptions` — required when `batchExecute` is routed through a strategy (there is no wallet account to read the sender from); ignored on the EIP-5792 wallet path.
  - Re-exports `externalSigning`, the signing-strategy types, and `createSigningRejectedError` / `isSigningRejected`, so a keyless adapter can be built from this package alone.

## 1.13.0

### Minor Changes

- Add support for bridging USDC to and from Cronos (mainnet and testnet) via CCTP v2.

## 1.12.1

### Patch Changes

- Internal dependency updates. No user-facing changes.

## 1.12.0

### Minor Changes

- Add cooperative cancellation via `AbortSignal`. When an `AbortSignal` is
  supplied through the invocation context, operations check it **before**
  signing/broadcasting and throw `NETWORK_ABORTED` (`3008`) if already aborted,
  and the wait for confirmation aborts promptly when the signal fires. After a
  transaction is broadcast, aborting only stops the local wait — the
  transaction is **not** cancelled on-chain.

- Bound adapter actions and the lifecycle events they emit now carry a
  human-readable `description`, so loggers, metrics, and tracing tools can
  label each step without decoding its internal name. Action registry entries
  exposed through the action dispatch include `description`, and the events
  those actions emit carry it too.

- Introduce the next-generation adapter architecture via `@circle-fin/adapter-viem-v2/next`.

  This release ships a ground-up redesign of the Viem adapter — built around composable primitives, a unified fee model, and first-class observability — while staying fully backward-compatible with the Bridge Kit and all existing providers.

  Import from `/next` today, change nothing else:

  ```ts
  import { createViemAdapterFromPrivateKey } from "@circle-fin/adapter-viem-v2/next";
  ```

  What's new:

  - `simulate()` on every prepared transaction — catch reverts before spending gas.
  - Consistent `{ fee, units, unitPrice }` fee model across EVM and Solana.
  - Built-in structured logging and pluggable metrics (`runtime` option).
  - Token registry — resolve tokens by symbol instead of hard-coding addresses.
  - Configurable gas buffers, priority-fee floors, confirmation timeouts, and automatic retry.
  - Automatic nonce management via viem's `nonceManager`, with per-adapter nonce tracking backed by JSON-RPC state — running multiple adapters in one process (e.g. against different RPC endpoints) no longer risks nonce contention.
  - `ensureChain` pre-flight: before write operations the adapter verifies the wallet is on the target chain and can prompt the user to switch (or throw / skip) via the `chainSwitch` option, surfacing `INPUT_CHAIN_MISMATCH` (1010), `INPUT_CHAIN_SWITCH_REJECTED` (1011), or `INPUT_UNRECOGNIZED_CHAIN` (1012) so consumers can branch programmatically.
  - EIP-5792 batched-transaction status reporting: `batchExecute` finalizes on `statusCode` `200` (success), `400` (offchain failure), `500` (full revert), and `600` (partial revert), and exposes the raw `statusCode` on `BatchExecuteResult` so callers can distinguish outcomes.
  - Fewer wallet popups for auto-connecting browser providers: `createViemAdapterFromProvider` tries the non-prompting `eth_accounts` first and only falls back to `eth_requestAccounts` when no account is returned (e.g. WalletConnect, Dynamic).

  This architecture will become the default entrypoint in the next major release.

### Patch Changes

- **Behavioral change (legacy + `/next`):** the viem `http()` transport's
  built-in retry layer is now disabled (`retryCount: 0`, `retryDelay: 0`)
  in `createEnhancedTransport`.

  Previously viem's transport retried transient RPC failures (default
  `retryCount: 3`, `retryDelay: 150`) **independently** of the SDK's
  middleware-level retry, so one transient failure could fan out to up to
  3 × 4 = 12 underlying requests. Retry is now owned by a single layer —
  the SDK middleware. Consumers relying on transport-level retries for
  adapters built through the default factories should configure retry via
  the middleware/runtime options, or supply their own transport through
  `getPublicClient` / `getWalletClient`.

## 1.11.2

### Patch Changes

- Internal dependency updates. No user-facing changes.

## 1.11.1

### Patch Changes

- Enable Earn deposit, withdrawal, and claim rewards execution when paired with `@circle-fin/earn-kit`.

## 1.11.0

### Minor Changes

- Improves the error you get when attempting a Gateway spend with a smart-contract account (SCA) as the signer. The failure previously surfaced as a confusing `invalid integer value <nil>/<nil> for type uint256` response from the Circle Wallets backend; you now get a clear `INPUT_UNSUPPORTED_ACTION` error up front that points at the delegate workflow (`kit.unifiedBalance.addDelegate` + `kit.unifiedBalance.spend` with the delegate EOA as `from.address` and the SCA as `from.sourceAccount`).

### Patch Changes

- Fix excessive MetaMask mobile app-switching prompts during bridge estimation and support chain switching for WalletConnect/Dynamic mobile wallet providers

## 1.10.0

### Minor Changes

- Add support for bridging USDC to and from Injective (mainnet and testnet) via CCTP v2. Both networks are now available as source and destination options in Bridge Kit.

## 1.9.0

### Minor Changes

- Add support for bridging USDC to and from Pharos (mainnet and testnet) via CCTP v2.

### Patch Changes

- Bridge errors now expose a machine-readable `errorCategory` so apps can distinguish user rejections, wallet capability errors, and offchain vs onchain failures without string-matching.

## 1.8.3

### Patch Changes

- Bundled Gateway v1 action handlers for Unified Balance Kit on-chain operations

## 1.8.2

### Patch Changes

- Update HyperEVM mainnet explorer URL to resolve location-restricted access issues
- Improved search discoverability

## 1.8.1

### Patch Changes

- Add support for Solana as a forwarder destination

## 1.8.0

### Minor Changes

- Add support for EIP-5792 batched transactions via `wallet_sendCalls`

### Patch Changes

- Update HyperEVM explorer URLs to use the official Hyperliquid explorer

## 1.7.0

### Minor Changes

- Add support for bridging USDC to and from Edge and Morph networks. Both mainnet and testnet chains are now available as source and destination options in Bridge Kit.

## 1.6.0

### Minor Changes

- More accurate gas fee estimates for cross-chain transfers. Added automatic transaction simulation with retry logic before execution to catch errors early. Gas estimation now accepts an optional fallback value for chains with unreliable fee oracles. Updated default Polygon RPC endpoints.

## 1.5.0

### Minor Changes

Add Circle Forwarder support for CCTP v2 bridging.

Forwarding is a relay-assisted mode where Circle observes the burn transaction,
retrieves attestation data, and submits the destination mint on the user's
behalf. This removes most destination-side orchestration from client code.

What this enables:

- Opt-in forwarding with `useForwarder: true` so Circle handles destination mint
  submission.
- Forwarder-only destinations (no destination adapter required) using
  `{ recipientAddress, chain, useForwarder: true }`.
- Forwarding-fee-aware estimation and max-fee calculation when `maxFee` is
  auto-derived.
- New hook-based burn actions: `cctp.v2.depositForBurnWithHook` and
  `cctp.v2.customBurnWithHook`.
- New forwarding helpers: `buildForwardingHookData` and
  `buildForwardingHookDataBuffer`.
- Chain-level forwarding metadata via `cctp.forwarderSupported` for route
  capability checks.

Compatibility:

- Existing non-forwarded bridge flows remain unchanged.
- If you set `config.maxFee` manually, include any expected forwarding fee.

### Patch Changes

- 667e1d9: Fix RPC state propagation race condition in pre-flight simulation.

  Added retry logic with exponential backoff when simulation fails with allowance errors ("exceeds allowance" or "insufficient allowance"). The adapter now retries up to 3 times with 1s, 2s delays to allow RPC nodes time to reflect recently confirmed transactions in their 'latest' block view.

  This fixes an intermittent issue where bridging would fail during the burn step even though the approve transaction succeeded, particularly on chains with fast finality.

## 1.4.0

### Minor Changes

- Monad chain support added

  Monad mainnet and testnet are now supported for cross-chain USDC transfers. Use `'Monad'` or `'Monad_Testnet'` as chain identifiers in your bridge operations.

## 1.3.0

### Minor Changes

- Add `native.balanceOf` action to query native token balances (ETH, SOL, etc.)
  - Added `NativeActionMap` with `balanceOf` action to check native token balance for any wallet address
  - Added abstract `readNativeBalance(address, chain)` method to base adapters
  - Implemented `readNativeBalance` in all concrete adapters (Viem, Ethers, Solana, SolanaKit)
  - Registered `native.balanceOf` action handlers for EVM and Solana chains
  - Balance reads are gas-free operations returning balance as string (wei for EVM, lamports for Solana)

### Patch Changes

- **Faster balance and allowance checks**: Read-only operations like checking token balances or allowances no longer require wallet network switching. This means no wallet popups asking for permission to switch networks, resulting in quicker responses and a smoother user experience.

## 1.2.0

### Minor Changes

- Clearer viem factory names eliminate aliasing when using multiple adapters. Prefer `createViemAdapterFromProvider` and `createViemAdapterFromPrivateKey` over the deprecated generic `createAdapterFromProvider` and `createAdapterFromPrivateKey`. Existing code works unchanged.

### Patch Changes

- Fixed an issue where custom RPC URLs were not fully respected in Viem adapter, ensuring users can now properly configure alternative RPC endpoints.
- Validation errors now use standardized error codes for consistent error handling. All validation failures return the same `KitError` structure as other SDK errors.

  **Migration:** If you're catching validation errors, update your error handling:

  - Check `error.code === 1098` instead of `instanceof ValidationError`
  - Access details via `error.cause?.trace?.validationErrors` instead of `error.errors`

  The legacy `ValidationError` class remains available for backward compatibility.

## 1.1.1

### Patch Changes

- Fixed adapter `getAddress()` types to match function logic by requiring a `chain` parameter, and updated documentation accordingly.
- Improved error handling with more informative and consistent error messages.

  Errors now include:

  - Specific error codes for programmatic handling
  - Error type categorization (BALANCE, ONCHAIN, RPC, NETWORK)
  - Recoverability information (FATAL vs RETRYABLE)
  - Clearer error messages with chain context
  - Original error details preserved for debugging

- Fixed bug where tokens could be burned when bridging to unsupported chains. Bridge operations now fail immediately if the adapter doesn't support the source or destination chain, before any tokens are approved or burned. Error messages now clearly list all supported chains when an unsupported chain is used, and chain validation errors use the correct `INVALID_CHAIN` error code instead of `UNSUPPORTED_ROUTE`.

## 1.1.0

### Minor Changes

- Improves static gas estimate values for contract calls. Updates adapters' `prepare()` method so that transaction simulation is now performed only during `execute()`, not during `estimate()`. Adds an optional fallback parameter to `estimate()` for cases where gas estimation fails.

### Patch Changes

- Fix CommonJS compatibility by correcting file extensions and package exports. This resolves a "ReferenceError: require is not defined" error that occurred when using packages in CommonJS projects with ts-node.

- Fixes an important bug affecting developer-controlled adapter scenarios (such as when using Fireblocks or Circle Wallets). Previously, these adapters would mistakenly attempt to use the connected wallet's account during contract execution, which could cause failures if no user wallet was connected. With this update, developer-controlled adapters now correctly use the address specified in your operation (as a JSON-RPC account), ensuring API-based signing services work as intended. User-controlled adapters continue to use the connected wallet account as before. If you use programmatic signing (such as MPC or custody APIs), this update resolves issues with transaction execution and integration with non-wallet-based flows.

## 1.0.1

### Patch Changes

- Add support for Arc Testnet chain definition. Arc is Circle's EVM-compatible Layer-1 blockchain designed for stablecoin finance and asset
  tokenization, featuring USDC as the native gas token and sub-second finality via the Malachite BFT consensus engine.
- Improve error messages for developer-controlled address contexts. Calling `getAddress()` on an adapter configured with `addressContext: 'developer-controlled'` now throws a clear error explaining that addresses must be provided explicitly in the operation context.
- Update Sonic Testnet chain definition to canonical network. The `SonicTestnet` chain definition now points to the official Sonic Testnet (chainId: 14601) instead of the deprecated Sonic Blaze Testnet (chainId: 57054). The RPC endpoint has been updated to `https://rpc.testnet.soniclabs.com`, the display name simplified to "Sonic Testnet", and the USDC contract address updated to the new deployment.

  **Breaking Changes:**

  - **Chain ID:** 57054 → 14601
  - **RPC Endpoint:** `https://rpc.blaze.soniclabs.com` → `https://rpc.testnet.soniclabs.com`
  - **USDC Address:** `0xA4879Fed32Ecbef99399e5cbC247E533421C4eC6` → `0x0BA304580ee7c9a980CF72e55f5Ed2E9fd30Bc51`

  **Migration:** If you were using `SonicTestnet`, your application will automatically connect to the new network upon upgrading. Any accounts, contracts, or transactions on the old Blaze testnet (chainId: 57054) will need to be recreated on the new testnet.

## 1.0.0

### Major Changes

- # Viem v2 Adapter 1.0.0 Release 🎉

  Modern EVM blockchain adapter built on viem v2 - providing cutting-edge EVM integration with superior performance, type safety, and developer experience.

  ## 🚀 Modern EVM Features

  - **Viem v2 Integration**: Built on the latest viem with best-in-class performance
  - **Superior Type Safety**: Enhanced TypeScript support with viem's advanced type system
  - **Optimized Performance**: Faster RPC calls and improved caching mechanisms
  - **Modern Architecture**: Clean, composable APIs following modern web3 patterns

  ## 🔗 Advanced Network Support

  - **All EVM Networks**: Comprehensive support for Ethereum and EVM-compatible chains
  - **Built-in Chain Definitions**: Pre-configured support for major networks
  - **Custom Chain Support**: Easy configuration for custom or private networks
  - **Network Switching**: Seamless chain switching with automatic configuration

  ## 💼 Flexible Address Management

  **User-Controlled Adapters**

  - Wallet integration with automatic address resolution
  - Support for modern wallet standards and connection methods
  - Real-time account and network change detection

  **Developer-Controlled Adapters**

  - Private key-based signing for server applications
  - Deterministic address management for automated workflows
  - Secure key handling with viem's security best practices

  ```typescript
  // User-controlled adapter with wallet
  const adapter = createAdapterFromWallet({
    walletClient: walletClient,
  });

  // Developer-controlled adapter with private key
  const adapter = createViemAdapterFromPrivateKey({
    privateKey: "0x...",
  });
  ```

  ## ⚡ Performance Optimizations

  - **Efficient RPC Management**: Optimized RPC client with intelligent caching
  - **Batch Operations**: Support for batched RPC calls to reduce latency
  - **Smart Gas Estimation**: Advanced gas estimation with minimal overhead
  - **Connection Pooling**: Efficient connection management for high-throughput applications

  ## 🔐 Enhanced Security

  - **Viem Security Model**: Leverages viem's security-first design principles
  - **Type-Safe Transactions**: Compile-time validation of transaction parameters
  - **Secure Key Management**: Best-practice key handling and signing flows
  - **Comprehensive Validation**: Runtime validation with detailed error reporting

  ## 🛠️ Developer Experience

  - **Modern TypeScript**: Full TypeScript support with advanced type inference
  - **Rich Documentation**: Comprehensive JSDoc with practical examples
  - **Intuitive APIs**: Clean, predictable interfaces following viem conventions
  - **Excellent Tooling**: Superior IDE support and debugging capabilities

  ## 🌟 Viem Advantages

  - **Tree Shaking**: Optimized bundle sizes with excellent tree shaking support
  - **Modular Design**: Use only the features you need for minimal footprint
  - **Active Development**: Built on the rapidly evolving viem ecosystem
  - **Community Support**: Backed by the growing viem community and ecosystem

  This adapter represents the future of EVM integration, providing developers with the most modern and efficient tools for cross-chain USDC transfers while maintaining the highest standards of security and reliability.
