Skip to main content
This reference guide describes the public interfaces, methods, and types available in the Bridge Kit SDK.

BridgeKit class

Bridge Kit lets you perform cost estimates and crosschain transfers. You can also add event listeners for each bridging provider.

constructor(config?)

Creates a new BridgeKit instance.
TypeScript
constructor(config?: BridgeKitConfig)
Parameters
NameTypeDescription
configBridgeKitConfigOptionally adds extra bridging providers
Usage example
TypeScript
// Standard setup
const kit = new BridgeKit();

// Setup with an additional provider
const provider = new MyCustomBridgingProvider();
const kit = new BridgeKit({ providers: [provider] });

BridgeKitConfig

Optionally adds extra bridging providers.
TypeScript
interface BridgeKitConfig {
  /**
   * Add an array of bridging providers available for routing transfers.
   *
   * Each provider must implement the BridgingProvider interface and declare
   * which chains and tokens it supports. The kit will automatically select
   * the appropriate provider based on order and the transfer parameters.
   */
  providers?: BridgingProvider[];
}
Properties
NameTypeDescription
providersBridgingProviderBridging providers to use in addition to CCTP (optional)

CustomFeePolicy

Global configuration for collecting a transfer fee. For details on how custom fees work, see Custom Fees.
TypeScript
export interface CustomFeePolicy {
  /**
   * A function that returns the fee to charge for the bridge transfer.
   * Return the fee in human-readable format (for example, '1' or '1.0' for 1 USDC).
   * The fee is added on top of the transfer amount.
   */
  computeFee: (params: BridgeParams) => Promise<string> | string;
  /**
   * A function that returns the fee recipient address on the source chain.
   * Must return a valid address for the source chain.
   */
  resolveFeeRecipientAddress: (
    feePayoutChain: ChainDefinition,
    params: BridgeParams,
  ) => Promise<string> | string;
}
Properties
NameTypeDescription
computeFeefunctionReturns the fee amount in human-readable format. See Custom Fees for fee splitting details.
resolveFeeRecipientAddressfunctionReturns the address that receives the fee on the source chain. Must be a valid address for the source chain.
Usage example
TypeScript
const kit = new BridgeKit();

// Set a global custom fee policy
kit.setCustomFeePolicy({
  computeFee: (params) => {
    const amount = parseFloat(params.amount);
    // 1% fee, capped between 5-50 USDC
    const fee = Math.min(Math.max(amount * 0.01, 5), 50);
    return fee.toFixed(6);
  },
  resolveFeeRecipientAddress: (feePayoutChain) => {
    // Return appropriate address format based on chain type
    return feePayoutChain.type === "solana"
      ? "YOUR_SOLANA_ADDRESS" // Base58 format
      : "YOUR_EVM_ADDRESS"; // 0x format
  },
});

Methods

bridge(params: BridgeParams)

Executes crosschain transfers.
TypeScript
async bridge(params: BridgeParams): Promise
Parameters
NameTypeDescription
paramsBridgeParamsBridge transfer parameters
Returns BridgeResult Usage example
TypeScript
const result = await kit.bridge({
  from: { adapter, chain: "Arc_Testnet" },
  to: { adapter, chain: "Ethereum_Sepolia" },
  amount: "10.00",
});

console.log("Transfer completed:", result.state);

estimate(params: BridgeParams)

Estimates costs before transferring.
TypeScript
async estimate(params: BridgeParams): Promise
Parameters
NameTypeDescription
paramsBridgeParamsBridge transfer parameters
Returns EstimateResult Usage example
TypeScript
// Estimate costs
const estimate = await kit.estimate({
  from: { adapter, chain: "Arc_Testnet" },
  to: { adapter, chain: "Base_Sepolia" },
  amount: "10.00",
});
console.log("Estimated fees:", estimate);

const cctpFee = estimate.fees.find((fee) => fee.type === "provider")?.amount;

// Only proceed if the CCTP protocol fee is less than 0.10 USDC
// Also proceed if the `cctpFee` variable is null/undefined since there is no protocol fee to charge
if (cctpFee == null || parseFloat(cctpFee) < 0.1) {
  // Execute the crosschain transfer
  const result = await kit.bridge({
    from: { adapter, chain: "Arc_Testnet" },
    to: { adapter, chain: "Base_Sepolia" },
    amount: "10.00",
  });
  console.log("Bridge completed:", result);
  // Error if the cost is over 5 USDC
} else {
  console.log("CCTP fee is above threshold:", cctpFee, "USDC");
}

getSupportedChains()

Returns a list of available blockchains.
TypeScript
getSupportedChains(): ChainDefinition[]
Returns ChainDefinition[] An array of blockchains, each object containing:
  • chain - String identifier of the blockchain, used in bridge parameters
  • name - Human-readable name of the blockchain, used in UI displays
  • type - Blockchain type
  • chainId - Network ID for EVM chains only
  • usdcAddress - USDC token contract address on the chain
  • cctp - CCTP configuration including domain ID and contract addresses
Usage example This code shows how to use the data returned by ChainDefinition[]:
TypeScript
import { BridgeKit, ChainDefinition } from "@circle-fin/bridge-kit";

const kit = new BridgeKit();
const chains = kit.getSupportedChains();

// Use 'name' property to display in your UI
function showChainSelector(chains: ChainDefinition[]) {
  return chains.map((chain) => (
    <option value={chain.chain}>{chain.name}</option>
  ));
}

on(action: string, handler: function)

Adds an event listener.
TypeScript
on(
  action: string,
  handler: (payload: AllActions) => void
): void
Parameters
NameTypeDescription
actionstringEvent type or * for all events. Events are type-safe and defined by the providers.
handlerfunctionEvent handler
Returns void Usage example
TypeScript
// Listen to specific events
kit.on("approve", (payload) => {
  console.log("Approval completed:", payload.values.txHash);
});
kit.on("mint", (payload) => {
  console.log("Mint completed:", payload.values.txHash);
});

// Listen to all events
kit.on("*", (event) => {
  console.log(`[${event.method}] Progress:`, event.values);
});

off(action: string, handler: function)

Removes an event listener.
TypeScript
off(
  action: string,
  handler: (payload: AllActions) => void
): void
Parameters
NameTypeDescription
actionstringEvent type or * for all events.
handlerfunctionEvent handler
Returns void Usage example
TypeScript
const mintHandler = (event) => console.log("Mint:", event.values.txHash);

// Register handler
kit.on("mint", mintHandler);

// Remove handler
kit.off("mint", mintHandler);

retry(result: BridgeResult, context: RetryContext)

Retries a failed or incomplete bridge operation.
TypeScript
async retry(result: BridgeResult, context: RetryContext): Promise<BridgeResult>
Parameters
NameTypeDescription
resultBridgeResultThe bridge result from a previous failed or incomplete operation
contextRetryContextRetry context containing fresh adapter instances for source and destination chains
Returns BridgeResult Usage example
TypeScript
// Assume we have a failed bridge result from a previous operation
const failedResult = await kit.bridge({
  from: { adapter, chain: "Arbitrum_Sepolia" },
  to: { adapter, chain: "Arc_Testnet" },
  amount: "100.00",
});

// If the bridge failed, retry it
if (failedResult.state === "error") {
  try {
    const retryResult = await kit.retry(failedResult, {
      from: adapter,
      to: adapter,
    });

    console.log("Retry completed:", retryResult.state);
  } catch (error) {
    console.error("Retry failed:", error);
  }
}

setCustomFeePolicy(customFeePolicy: CustomFeePolicy)

Sets a global custom fee policy for all transfers.
TypeScript
setCustomFeePolicy(customFeePolicy: CustomFeePolicy): void
Parameters
NameTypeDescription
customFeePolicyCustomFeePolicyThe custom fee policy configuration
Returns void Usage example For usage example, see CustomFeePolicy.

removeCustomFeePolicy()

Removes the custom fee policy for the kit.
TypeScript
removeCustomFeePolicy(): void
Returns void Usage example
TypeScript
// Set a custom fee policy
kit.setCustomFeePolicy({
  computeFee: (params) => "1.0",
  resolveFeeRecipientAddress: () => "YOUR_WALLET_ADDRESS",
});

// Later, remove it
kit.removeCustomFeePolicy();

Method parameters

BridgeParams

Parameters to execute a crosschain bridge transfer.
TypeScript
interface BridgeParams {
  from: AdapterContext;
  to: BridgeDestination;
  amount: string;
  config?: BridgeConfig;
  token?: "USDC";
}
Properties
NameTypeDescription
fromAdapterContextThe source adapter and the specific chain on which the source address exists
toBridgeDestinationThe destination adapter, the destination chain, and a recipient address (optional, if different than adapter’s default address)
amountstringThe amount of tokens to transfer
configBridgeConfigConfiguration of transfer speed (optional)
tokenUSDCThe type of token to transfer (optional, defaults to USDC if omitted)
Usage example
// Basic transfer with default transfer speed (fast) and token (USDC)
const params: BridgeParams = {
  from: { adapter, chain: "Arc_Testnet" },
  to: { adapter, chain: "Polygon_Amoy_Testnet" },
  amount: "10.00",
};

BridgeConfig

Configuration for transfer speed.
TypeScript
interface BridgeConfig {
  transferSpeed?: "FAST" | "SLOW";
  maxFee?: string;
  customFee?: CustomFee | undefined;
}
Properties
NameTypeDescription
transferSpeedFAST | SLOWThe speed of the transfer (optional, defaults to FAST if omitted)
maxFeestringFAST transfers only: the maximum fee per transfer in human-readable format (for example, "5" for 5 USDC). If the actual fee exceeds this, the transfer speed switches to SLOW.
customFeeCustomFeeA custom fee that you can add to the transfer
Usage example
const result = await kit.bridge({
  from: { adapter, chain: "HyperEVM_Testnet" },
  to: { adapter, chain: "Arc_Testnet" },
  amount: "100.00",
  config: { transferSpeed: "SLOW" }, // Transfer speed
});

CustomFee

Per-transfer fee configuration that can be included in BridgeConfig. For details on how custom fees work, see Custom Fees.
TypeScript
interface CustomFee {
  value?: string;
  recipientAddress?: string;
}
Properties
NameTypeDescription
valuestringThe fee amount in human-readable format (for example, "1" for 1 USDC, "0.5" for 0.5 USDC). The fee is added on top of the transfer amount.
recipientAddressstringThe address that receives the fee on the source chain. Must be a valid address for the source chain.
Usage example
TypeScript
// Transfer with a per-transfer custom fee
const result = await kit.bridge({
  from: { adapter, chain: "Arc_Testnet" },
  to: { adapter, chain: "Base_Sepolia" },
  amount: "100.00",
  config: {
    transferSpeed: "FAST",
    customFee: {
      value: "2.0",
      recipientAddress: "YOUR_FEE_RECIPIENT_ADDRESS", // Must match source chain format
    },
  },
});

AdapterContext

The adapter and its associated chain.
TypeScript
type AdapterContext = {
  adapter: Adapter;
  chain: ChainIdentifier;
};
Properties
NameTypeDescription
adapterAdapterThe adapter instance that handles blockchain operations
chainChainIdentifierThe identifier of the blockchain
Usage example
TypeScript
await kit.bridge({
  from: { adapter, chain: "Ethereum_Sepolia" }, // AdapterContext for Ethereum Sepolia
  to: { adapter, chain: "Arc_Testnet" }, // AdapterContext for Arc Testnet
  amount: "25.00",
});

BridgeDestination

Specifies where tokens should be sent.
TypeScript
type BridgeDestination = AdapterContext | BridgeDestinationWithAddress;
Types
TypeDescription
AdapterContextThe adapter’s address on the destination chain
BridgeDestinationWithAddressIncludes a specific recipient address used to override the default adapter’s address
Usage example
await kit.bridge({
  from: { adapter, chain: "Arc_Testnet" },
  // Tokens sent to adapter's default address on Polygon Amoy Testnet
  to: { adapter, chain: "Polygon_Amoy_Testnet" },
  amount: "10.00",
});

BridgeDestinationWithAddress

Specifies a recipient wallet address.
TypeScript
type BridgeDestinationWithAddress = AdapterContext & {
  recipientAddress: string;
};
Properties
NameTypeDescription
adapterAdapterThe adapter
chainChainIdentifierThe chain identifier
recipientAddressstringThe recipient wallet address on the destination chain
Usage example
TypeScript
await kit.bridge({
  from: { adapter: myAdapter, chain: "Base_Sepolia" },
  to: {
    adapter: myAdapter,
    chain: "Arc_Testnet",
    recipientAddress: "RECIPIENT_WALLET_ADDRESS", // Custom address on Arc Testnet
  },
  amount: "50.0",
});

RetryContext

Context for retrying a failed bridge operation.
TypeScript
interface RetryContext {
  from: Adapter;
  to: Adapter;
}
Properties
NameTypeDescription
fromAdapterFresh adapter instance for the source chain
toAdapterFresh adapter instance for the destination chain
Usage example
TypeScript
// Retry a failed bridge operation with fresh adapters
const retryResult = await kit.retry(failedResult, {
  from: sourceAdapter,
  to: destAdapter,
});

Method results

BridgeResult

Shows the transfer state, transaction step, source, and destination chain information, and the transfer amount. Returned by the bridge method.
TypeScript
interface BridgeResult {
  amount: string;
  token: "USDC";
  state: "pending" | "success" | "error";
  config?: BridgeConfig;
  provider: string;
  source: {
    address: string;
    chain: ChainDefinition;
  };
  destination: {
    address: string;
    chain: ChainDefinition;
    recipientAddress?: string;
  };
  steps: BridgeStep[];
}
Properties
NameTypeDescription
amountstringThe amount of the transfer
tokenstringThe token to transfer, defaults to USDC
state"pending" | "success" | "error"The state of the transfer
configBridgeConfigThe bridge configurations passed in the transfer
sourceobjectSource chain information
destinationobjectDestination chain and address (includes optional recipientAddress if custom address was specified)
stepsBridgeStep[]Array of transaction steps, each containing the transaction state and hash
Example response
JSON
{
  "amount": "25.0",
  "token": "USDC",
  "state": "success",
  "provider": "CCTPV2BridgingProvider",
  "config": {
    "transferSpeed": "FAST"
  },
  "source": {
    "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    "chain": {
      "type": "evm",
      "chain": "Arc_Testnet",
      "chainId": 421614,
      "name": "Arc Testnet"
      // ... nativeCurrency, explorerUrl, rpcEndpoints, usdcAddress, eurcAddress, cctp, etc.
    }
  },
  "destination": {
    "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    "chain": {
      "type": "evm",
      "chain": "Base_Sepolia",
      "chainId": 84532,
      "name": "Base Sepolia"
      // ... additional ChainDefinition properties
    }
  },
  "steps": [
    {
      "name": "approve",
      "state": "success",
      "txHash": "0x1234567890abcdef1234567890abcdef12345678",
      "explorerUrl": "https://testnet.arcscan.io/tx/0x1234567890abcdef1234567890abcdef12345678"
    },
    {
      "name": "burn",
      "state": "success",
      "txHash": "0xabcdef1234567890abcdef1234567890abcdef12",
      "explorerUrl": "https://testnet.arcscan.io/tx/0xabcdef1234567890abcdef1234567890abcdef12"
    },
    {
      "name": "fetchAttestation",
      "state": "success",
      "data": {
        "attestation": "0x9876543210fedcba9876543210fedcba98765432"
      }
    },
    {
      "name": "mint",
      "state": "success",
      "txHash": "0xfedcba9876543210fedcba9876543210fedcba98",
      "explorerUrl": "https://sepolia.basescan.org/tx/0xfedcba9876543210fedcba9876543210fedcba98"
    }
  ]
}

BridgeStep

Individual transaction step within a bridge operation. Each step represents a distinct action in the cross-chain transfer process.
TypeScript
interface BridgeStep {
  name: string;
  state: "pending" | "success" | "error" | "noop";
  txHash?: string;
  explorerUrl?: string;
  data?: unknown;
  errorMessage?: string;
  error?: unknown;
}
Properties
NameTypeDescription
namestringHuman-readable name (for example, “Approve”, “Burn”, “Mint”)
state"pending" | "success" | "error" | "noop"Current state of the step
txHashstringTransaction hash for this step (optional)
explorerUrlstringBlock explorer URL for viewing the transaction (optional)
dataunknownAdditional data for the step (optional)
errorMessagestringHuman-readable error message if step failed (optional)
errorunknownRaw error object from the chain (optional)
Example response
{
  "name": "approve",
  "state": "success",
  "txHash": "0x1234567890abcdef1234567890abcdef12345678",
  "explorerUrl": "https://testnet.arcscan.io/tx/0x1234567890abcdef..."
}

EstimateResult

Estimated costs of the transaction, returned by the estimate method.
TypeScript
interface EstimateResult {
  token: "USDC";
  amount: string;
  source: {
    address: string;
    chain: Blockchain;
  };
  destination: {
    address: string;
    chain: Blockchain;
    recipientAddress?: string;
  };
  gasFees: {
    name: string;
    token: string;
    blockchain: Blockchain;
    fees: EstimatedGas | null;
    error?: unknown;
  }[];
  fees: {
    type: "kit" | "provider";
    token: "USDC";
    amount: string | null;
    error?: unknown;
  }[];
}
Properties
NameTypeDescription
tokenstringThe token being transferred (currently only USDC is supported)
amountstringThe amount being transferred
sourceobjectSource chain and address information
destinationobjectDestination chain and address information
gasFeesEstimatedGas[]Array of gas costs for each step on source and destination chains
feesobject[]Array of protocol and kit fees (type "provider" or "kit")
Example response
JSON
{
  "token": "USDC",
  "amount": "100.0",
  "source": {
    "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    "chain": "Arc_Testnet"
  },
  "destination": {
    "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
    "chain": "Base_Sepolia"
  },
  "gasFees": [
    {
      "name": "Approve",
      "token": "Arc",
      "blockchain": "Arc_Testnet",
      "fees": {
        /* EstimatedGas object */
      }
    },
    {
      "name": "Burn",
      "token": "Arc",
      "blockchain": "Arc_Testnet",
      "fees": {
        /* EstimatedGas object */
      }
    },
    {
      "name": "Mint",
      "token": "ETH",
      "blockchain": "Base_Sepolia",
      "fees": {
        /* EstimatedGas object */
      }
    }
  ],
  "fees": [
    {
      "type": "provider",
      "token": "USDC",
      "amount": "0.01" // CCTP protocol fee (varies by route, 0-0.14 USDC for FAST)
    },
    {
      "type": "kit",
      "token": "USDC",
      "amount": "1.0" // Custom developer fee (optional)
    }
  ]
}

EstimatedGas

Gas estimation details for a specific transaction step. Returned as part of gasFees entries in EstimateResult.
TypeScript
interface EstimatedGas {
  gas: bigint;
  gasPrice: bigint;
  fee: string;
}
Properties
NameTypeDescription
gasbigintThe amount of gas units estimated for the transaction
gasPricebigintThe estimated price per unit of gas (primarily for EVM chains)
feestringThe total estimated fee in the native token (for example, ETH, MATIC, SOL)
Notes:
  • For EVM chains: fee equals gas * gasPrice (represented in wei)
  • For non-EVM chains: gas and gasPrice may represent different metrics (for example, compute units on Solana)
  • The fee field is always in the smallest unit of the native currency
Example response
{
  "gas": "150000",
  "gasPrice": "1500000000", // 1.5 Gwei
  "fee": "0.000225" // 150000 * 1.5 Gwei = 0.000225 ETH
}

Error Handling

Bridge Kit provides structured error handling with typed errors, type guards, and utility functions to help you handle errors gracefully in your application.

KitError

Structured error class for all Bridge Kit operations. All errors thrown by Bridge Kit extend this class with consistent properties for programmatic handling.
TypeScript
class KitError extends Error {
  readonly code: number;
  readonly name: string;
  readonly type: ErrorType;
  readonly recoverability: Recoverability;
  readonly cause?: {
    trace?: unknown;
  };
}
Properties
NameTypeDescription
codenumberNumeric error code following standardized ranges (see error constants below)
namestringHuman-readable error ID (for example, "INPUT_NETWORK_MISMATCH")
typeErrorTypeError category: "INPUT", "BALANCE", "ONCHAIN", "RPC", or "NETWORK"
recoverabilityRecoverabilityError handling strategy: "FATAL", "RETRYABLE", or "RESUMABLE"
messagestringUser-friendly error explanation with context
causeobjectRaw error details or the original error that caused this one (optional)
Error Code Ranges
RangeTypeDescription
1000-1999INPUTParameter validation, invalid inputs, configuration errors
3000-3999NETWORKInternet connectivity, DNS, connection issues
4000-4999RPCBlockchain RPC provider issues, gas estimation, nonce errors
5000-5999ONCHAINTransaction/simulation failures, gas exhaustion, reverts
9000-9999BALANCEInsufficient funds, token balance, allowance issues
Usage example
TypeScript
import { KitError, isKitError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isKitError(error)) {
    console.log(`Error ${error.code}: ${error.name}`);
    console.log(`Type: ${error.type}, Recoverability: ${error.recoverability}`);
    console.log(`Message: ${error.message}`);
  }
}

Error Constants

Bridge Kit exports error constant objects for each error type, providing easy access to error codes and names for specific error scenarios.

InputError

Validation failures and invalid parameters. Always FATAL recoverability.
TypeScript
const InputError: {
  NETWORK_MISMATCH: {
    code: 1001;
    name: "INPUT_NETWORK_MISMATCH";
    type: "INPUT";
  };
  INVALID_AMOUNT: { code: 1002; name: "INPUT_INVALID_AMOUNT"; type: "INPUT" };
  UNSUPPORTED_ROUTE: {
    code: 1003;
    name: "INPUT_UNSUPPORTED_ROUTE";
    type: "INPUT";
  };
  INVALID_ADDRESS: { code: 1004; name: "INPUT_INVALID_ADDRESS"; type: "INPUT" };
  INVALID_CHAIN: { code: 1005; name: "INPUT_INVALID_CHAIN"; type: "INPUT" };
  VALIDATION_FAILED: {
    code: 1098;
    name: "INPUT_VALIDATION_FAILED";
    type: "INPUT";
  };
};
Usage example
TypeScript
import { InputError, getErrorCode } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (getErrorCode(error) === InputError.NETWORK_MISMATCH.code) {
    console.log("Cannot bridge between mainnet and testnet");
  }
}

BalanceError

Insufficient funds or allowance issues. Always FATAL recoverability.
TypeScript
const BalanceError: {
  INSUFFICIENT_TOKEN: {
    code: 9001;
    name: "BALANCE_INSUFFICIENT_TOKEN";
    type: "BALANCE";
  };
  INSUFFICIENT_GAS: {
    code: 9002;
    name: "BALANCE_INSUFFICIENT_GAS";
    type: "BALANCE";
  };
  INSUFFICIENT_ALLOWANCE: {
    code: 9003;
    name: "BALANCE_INSUFFICIENT_ALLOWANCE";
    type: "BALANCE";
  };
};
Usage example
TypeScript
import { BalanceError, isBalanceError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isBalanceError(error)) {
    console.log("Insufficient funds. Please add more tokens to your wallet.");
    showAddFundsUI();
  }
}

OnchainError

Transaction execution or simulation failures. Typically FATAL recoverability.
TypeScript
const OnchainError: {
  TRANSACTION_REVERTED: {
    code: 5001;
    name: "ONCHAIN_TRANSACTION_REVERTED";
    type: "ONCHAIN";
  };
  SIMULATION_FAILED: {
    code: 5002;
    name: "ONCHAIN_SIMULATION_FAILED";
    type: "ONCHAIN";
  };
  OUT_OF_GAS: { code: 5003; name: "ONCHAIN_OUT_OF_GAS"; type: "ONCHAIN" };
  GAS_LIMIT_EXCEEDED: {
    code: 5004;
    name: "ONCHAIN_GAS_LIMIT_EXCEEDED";
    type: "ONCHAIN";
  };
};
Usage example
TypeScript
import { OnchainError, isOnchainError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isOnchainError(error)) {
    console.log("Transaction failed on-chain:", error.message);
  }
}

RpcError

Blockchain RPC provider communication issues. Typically RETRYABLE recoverability.
TypeScript
const RpcError: {
  ENDPOINT_ERROR: { code: 4001; name: "RPC_ENDPOINT_ERROR"; type: "RPC" };
  INVALID_RESPONSE: { code: 4002; name: "RPC_INVALID_RESPONSE"; type: "RPC" };
  NONCE_ERROR: { code: 4003; name: "RPC_NONCE_ERROR"; type: "RPC" };
};
Usage example
TypeScript
import { RpcError, isRpcError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isRpcError(error)) {
    console.log("RPC provider issue. Retrying...");
    setTimeout(() => retryOperation(), 5000);
  }
}

NetworkError

Network connectivity issues. Typically RETRYABLE recoverability.
TypeScript
const NetworkError: {
  CONNECTION_FAILED: {
    code: 3001;
    name: "NETWORK_CONNECTION_FAILED";
    type: "NETWORK";
  };
  TIMEOUT: { code: 3002; name: "NETWORK_TIMEOUT"; type: "NETWORK" };
};
Usage example
TypeScript
import { NetworkError, isNetworkError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isNetworkError(error)) {
    console.log("Network connection issue. Please check your internet.");
  }
}

Error Type Guards

Type guard functions that enable TypeScript type narrowing and help you handle different error types appropriately.

isKitError()

Checks if an error is a KitError instance.
TypeScript
function isKitError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error is a KitError with type narrowing Usage example
TypeScript
import { isKitError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isKitError(error)) {
    console.log(`Structured error: ${error.name} (${error.code})`);
  } else {
    console.log("Regular error:", error);
  }
}

isFatalError()

Checks if an error has FATAL recoverability. Fatal errors require user intervention and should not be retried.
TypeScript
function isFatalError(error: unknown): boolean;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has FATAL recoverability Usage example
TypeScript
import { isFatalError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isFatalError(error)) {
    // Don't retry - show user-friendly error message
    showUserError(error.message);
  }
}

isRetryableError()

Checks if an error has RETRYABLE recoverability. Retryable errors are transient and may succeed on subsequent attempts.
TypeScript
function isRetryableError(error: unknown): boolean;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has RETRYABLE recoverability Usage example
TypeScript
import { isRetryableError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isRetryableError(error)) {
    // Implement retry logic with exponential backoff
    setTimeout(() => retryOperation(), 5000);
  }
}

isInputError()

Checks if an error is an input validation error.
TypeScript
function isInputError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has INPUT type Usage example
TypeScript
import { isInputError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isInputError(error)) {
    console.log("Validation error:", error.message);
    showValidationUI();
  }
}

isBalanceError()

Checks if an error is a balance-related error.
TypeScript
function isBalanceError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has BALANCE type Usage example
TypeScript
import { isBalanceError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isBalanceError(error)) {
    console.log("Insufficient funds:", error.message);
    showAddFundsUI();
  }
}

isOnchainError()

Checks if an error is an on-chain execution error.
TypeScript
function isOnchainError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has ONCHAIN type Usage example
TypeScript
import { isOnchainError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isOnchainError(error)) {
    console.log("Transaction failed:", error.message);
    showTransactionErrorUI();
  }
}

isRpcError()

Checks if an error is an RPC provider error.
TypeScript
function isRpcError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has RPC type Usage example
TypeScript
import { isRpcError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isRpcError(error)) {
    console.log("RPC error:", error.message);
    retryWithBackoff();
  }
}

isNetworkError()

Checks if an error is a network connectivity error.
TypeScript
function isNetworkError(error: unknown): error is KitError;
Parameters
NameTypeDescription
errorunknownError object to check
Returns boolean - true if error has NETWORK type Usage example
TypeScript
import { isNetworkError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  if (isNetworkError(error)) {
    console.log("Network issue:", error.message);
    retryWithBackoff();
  }
}

Error Utility Functions

Utility functions for extracting error information safely from any error type.

getErrorMessage()

Safely extracts error message from any error type. Never throws.
TypeScript
function getErrorMessage(error: unknown): string;
Parameters
NameTypeDescription
errorunknownError object to extract message
Returns string - Error message or fallback message Usage example
TypeScript
import { getErrorMessage } from "@circle-fin/bridge-kit";

try {
  await riskyOperation();
} catch (error) {
  const message = getErrorMessage(error);
  console.log("Error occurred:", message);
  // Works with Error, KitError, string, or any other type
}

getErrorCode()

Safely extracts error code from a KitError, or returns null for other error types.
TypeScript
function getErrorCode(error: unknown): number | null;
Parameters
NameTypeDescription
errorunknownError object to extract code
Returns number | null - Error code or null if not a KitError Usage example
TypeScript
import { getErrorCode, InputError } from "@circle-fin/bridge-kit";

try {
  await kit.bridge(params);
} catch (error) {
  const code = getErrorCode(error);
  if (code === InputError.NETWORK_MISMATCH.code) {
    showNetworkMismatchHelp();
  }
}