# Get all supported tokens Source: https://docs.chainrails.io/api-reference/chains/get-all-supported-tokens /api-reference/openapi.json get /chains/tokens/all Retrieves all unique token symbols supported on Chainrails across all blockchain networks # Get supported chains Source: https://docs.chainrails.io/api-reference/chains/get-supported-chains /api-reference/openapi.json get /chains Retrieves all supported blockchain networks, optionally filtered by network type (mainnet/testnet) # Get supported tokens for chain Source: https://docs.chainrails.io/api-reference/chains/get-supported-tokens-for-chain /api-reference/openapi.json get /chains/{chain}/tokens Retrieves all supported tokens available on the specified blockchain network # Get wallet balances across all chains Source: https://docs.chainrails.io/api-reference/chains/get-wallet-balances-across-all-chains /api-reference/openapi.json get /chains/balances/{address} Retrieves all token balances for the specified wallet address across all supported blockchain networks. Returns only non-zero balances by default. # Calculate destination intent address Source: https://docs.chainrails.io/api-reference/intents/calculate-destination-intent-address /api-reference/openapi.json get /intents/destination-address/{address} Calculates what the intent address would be on the destination chain for a given source intent # Create new intent Source: https://docs.chainrails.io/api-reference/intents/create-new-intent /api-reference/openapi.json post /intents Creates a new payment intent with cross-chain transfer parameters # Get all client intents Source: https://docs.chainrails.io/api-reference/intents/get-all-client-intents /api-reference/openapi.json get /intents Retrieves all intents for the authenticated client with pagination and optional status filtering # Get intent by address Source: https://docs.chainrails.io/api-reference/intents/get-intent-by-address /api-reference/openapi.json get /intents/address/{address} Retrieves an intent using its contract address # Get intent by ID Source: https://docs.chainrails.io/api-reference/intents/get-intent-by-id /api-reference/openapi.json get /intents/{id} Retrieves information about a specific intent using its unique id # Get user intents Source: https://docs.chainrails.io/api-reference/intents/get-user-intents /api-reference/openapi.json get /intents/user/{sender} Retrieves all intents created by a specific user # Manually trigger intent processing Source: https://docs.chainrails.io/api-reference/intents/manually-trigger-intent-processing /api-reference/openapi.json post /intents/{intentAddress}/trigger-processing Triggers manual processing of an intent. Checks funding status, starts the intent if needed, and initiates completion flow. Use this as a fallback when the indexer misses the funding event. # Refund an expired intent Source: https://docs.chainrails.io/api-reference/intents/refund-an-expired-intent /api-reference/openapi.json post /intents/{intentAddress}/refund Manually refunds an expired intent for the authenticated client. This is an escape hatch for recovering stuck funds when automation fails. # Update intent status Source: https://docs.chainrails.io/api-reference/intents/update-intent-status /api-reference/openapi.json patch /intents/{id}/status Updates the status of an existing intent # Introduction Source: https://docs.chainrails.io/api-reference/introduction API Reference for Chainrails You need an API Key to access the Chainrails API. You can get one by signing up on our [dashboard](https://dashboard.chainrails.io) or contacting us at [contact@horuslabs.co](mailto:contact@horuslabs.co). ## Overview Chainrails exposes a RESTful API that allows developers to integrate cross-chain payment functionalities into their applications seamlessly. These API covers everything from requesting quotes, to creating and fulfilling payment intents. ## BASE URL All API requests are made to the following base URL: ``` https://api.chainrails.io ``` ## Authentication All API requests require authentication using an API Key. You can include your API Key in the `Authorization` header as a Bearer token. Example: `Authorization: Bearer YOUR_API_KEY` ## Rate Limits To ensure fair usage and maintain optimal performance, the Chainrails API enforces rate limits on incoming requests. The default rate limit is set to 250 requests per minute. If you exceed this limit, you will receive a `429 Too Many Requests` response. If you require higher rate limits, please contact the team. ## Testing the API For testing purposes, we recommend using test keys and testnets. You can find more information about our supported testnets and tokens in the [Supported Networks & Tokens](/guides/integrations) guide. **NB:** We do not provide indexing support for testnet chains and thus you may need to manually call the `POST /api/v1/intents/{intent_address}/trigger-processing` endpoint to trigger intent processing. Also note that some chains have no testnet support and for these you may need to use mainnet with small amounts. # Inspect configured provider requirements Source: https://docs.chainrails.io/api-reference/kyc/inspect-configured-provider-requirements /api-reference/openapi.json get /kyc/requirements # Inspect the current KYC state for a transaction Source: https://docs.chainrails.io/api-reference/kyc/inspect-the-current-kyc-state-for-a-transaction /api-reference/openapi.json get /kyc/state # Submit KYC fields and start any required verification Source: https://docs.chainrails.io/api-reference/kyc/submit-kyc-fields-and-start-any-required-verification /api-reference/openapi.json post /kyc/submit # Create a modal session Source: https://docs.chainrails.io/api-reference/modal-sessions/create-a-modal-session /api-reference/openapi.json post /modal/sessions Creates a modal session with constraints (recipient, token, chain, amount). Returns a session token valid for 60 minutes. # Get best quote across all bridges Source: https://docs.chainrails.io/api-reference/quotes/get-best-quote-across-all-bridges /api-reference/openapi.json get /quotes/best Retrieves the best quote (lowest total fee) from all supported bridge protocols # Get quote from specific bridge Source: https://docs.chainrails.io/api-reference/quotes/get-quote-from-specific-bridge /api-reference/openapi.json get /quotes/single Retrieves a cross-chain transfer quote from a specific bridge protocol # Get quotes from all bridges Source: https://docs.chainrails.io/api-reference/quotes/get-quotes-from-all-bridges /api-reference/openapi.json get /quotes/multiple Retrieves quotes from all supported bridge protocols for comparison # Get quotes from all source chains to destination Source: https://docs.chainrails.io/api-reference/quotes/get-quotes-from-all-source-chains-to-destination /api-reference/openapi.json get /quotes/multi-source Shows Alice all her options to send money to a specific destination chain, including same-chain transfers # Cancel a ramp order Source: https://docs.chainrails.io/api-reference/ramp/cancel-a-ramp-order /api-reference/openapi.json post /ramp/orders/{id}/cancel Cancels a ramp order if it is still in a cancellable state. # Confirm a ramp order Source: https://docs.chainrails.io/api-reference/ramp/confirm-a-ramp-order /api-reference/openapi.json post /ramp/orders/{id}/confirm Confirms a ramp order after the user has completed their deposit action. # Create a ramp order Source: https://docs.chainrails.io/api-reference/ramp/create-a-ramp-order /api-reference/openapi.json post /ramp/orders Creates an on-ramp or off-ramp order with the selected provider. # Get a ramp order by ID Source: https://docs.chainrails.io/api-reference/ramp/get-a-ramp-order-by-id /api-reference/openapi.json get /ramp/orders/{id} Returns the full details of a ramp order, scoped to the authenticated client. # Get a ramp order by intent address Source: https://docs.chainrails.io/api-reference/ramp/get-a-ramp-order-by-intent-address /api-reference/openapi.json get /ramp/orders/by-intent/{intentAddress} Returns the full details of a ramp order looked up by its on-chain intent address. # Get aggregated ramp quotes Source: https://docs.chainrails.io/api-reference/ramp/get-aggregated-ramp-quotes /api-reference/openapi.json get /ramp/quotes Returns on-ramp or off-ramp quotes from all eligible providers, sorted by cheapest total cost. # Get provider KYC requirements Source: https://docs.chainrails.io/api-reference/ramp/get-provider-kyc-requirements /api-reference/openapi.json get /ramp/kyc/requirements # Get user KYC state Source: https://docs.chainrails.io/api-reference/ramp/get-user-kyc-state /api-reference/openapi.json get /ramp/kyc Returns the Chainrails KYC state and transaction requirements for a user. # List ramp orders Source: https://docs.chainrails.io/api-reference/ramp/list-ramp-orders /api-reference/openapi.json get /ramp/orders Returns ramp orders for the authenticated client, optionally filtered by type. Newest first. # List supported countries Source: https://docs.chainrails.io/api-reference/ramp/list-supported-countries /api-reference/openapi.json get /ramp/countries Returns all enabled countries with currency details. Optionally filter by fiat currency code, minimum crypto (USDC) amount, and ramp type. When type=off-ramp, only countries with direct S2S off-ramp support are returned. # List supported fiat currencies Source: https://docs.chainrails.io/api-reference/ramp/list-supported-fiat-currencies /api-reference/openapi.json get /ramp/currencies Returns all enabled fiat currencies. Optionally filter by a specific ramp provider and/or ramp type. When type=off-ramp, only currencies with direct S2S off-ramp support are returned. # Submit KYC information Source: https://docs.chainrails.io/api-reference/ramp/submit-kyc-information /api-reference/openapi.json post /ramp/kyc Submits available KYC fields. The Chainrails KYC engine determines whether text validation, external verification, or both are required. # Find optimal cross-chain transfer route Source: https://docs.chainrails.io/api-reference/router/find-optimal-cross-chain-transfer-route /api-reference/openapi.json get /router/optimal-route Analyzes available bridges and returns the optimal route with best pricing # Get all supported bridges Source: https://docs.chainrails.io/api-reference/router/get-all-supported-bridges /api-reference/openapi.json get /router/supported-bridges/all Returns all bridges and their supported routes # Get supported bridges for specific route Source: https://docs.chainrails.io/api-reference/router/get-supported-bridges-for-specific-route /api-reference/openapi.json get /router/supported-bridges/route Returns all bridges that support transfers between specific source and destination chains # Get supported routes for specific bridge Source: https://docs.chainrails.io/api-reference/router/get-supported-routes-for-specific-bridge /api-reference/openapi.json get /router/supported-routes/bridge/{bridge} Returns all source/destination chain pairs supported by a specific bridge # Chainrails vs (Bridges/Aggregators) Source: https://docs.chainrails.io/concepts/chainrails-vs-others How Chainrails compares to other solutions like bridges and aggregators While Chainrails interacts with multiple bridges and liquidity sources under the hood, it is not a bridge, and it is much more than just an aggregator. ## Traditional Bridges Bridges are protocols that facilitate the transfer of assets from one blockchain to another. They typically require the user or developer to choose: * which bridge to use, * which route to take (the source and destination chains), * which token representation to receive on the destination chain. They work well for manual cross-chain transfers, but they introduce complexity for developers building applications that need to accept payments or deposits from users on multiple chains. Developers must still: * Integrate with multiple bridges to cover different routes, * Manage route discovery and liquidity risks, * Monitor transactions for completion and refunds, accounting for bridge-specific nuances. ## Aggregators Aggregators like LI.FI or Socket do an incredible job of simplifying access to multiple bridges and liquidity pools. They provide a unified interface to route transactions through the best available paths. However, they are primarily focused on optimizing trade routing and liquidity access. Users or developers still need to deal with bridging risks, retries, transaction monitoring, and refunds. Ideal for swaps and liquidity routing, but not optimal for business use cases like payments or deposits. ## Chainrails Chainrails sits a layer above aggregators, abstracting away the entire bridging experience. It lets developers accept value from any chain, in any token, or even fiat without managing bridges, liquidity, or settlements. Every transaction is modeled as an Intent — a high-level instruction that defines what the user wants to achieve, and Chainrails handles how it happens behind the scenes. Developers no longer worry about: * Which bridge or route to use — the most optimal bridge is automatically selected under the hood. * Liquidity or bridging risk — handled by Chainrails’ relayers. * Speed trade-offs — transactions typically complete in 15-20 seconds. * Monitoring and refunds — managed automatically. * Integration overhead — a single API or SDK call covers all chains. * Fiat on/off ramps — handled seamlessly. Chainrails is designed for business use cases — deposits, withdrawals, payments, and value flows, not just bridging. ## Comparison at a glance | Feature / Model | **Bridges** | **Aggregators** | **Chainrails** | | -------------------- | ----------------------------------- | ---------------------------- | ------------------------------------------ | | Core focus | Move tokens between specific chains | Optimize cross-chain routing | Abstract value transfer & intent execution | | Target user | End users, DeFi traders | Advanced users, DEXs | Developers & businesses | | Integration effort | High (per bridge) | Moderate (per aggregator) | Single integration | | Who manages routing | Developer / user | Aggregator | Chainrails | | Liquidity management | Handled by user | Handled by aggregator | Handled by Chainrails relayers | | Transaction speed | Varies (minutes) | Varies (depends on bridge) | 15-20 seconds (constant) | | Refund & monitoring | Developer-managed | Partial | Automatic | | Fiat on/off ramps | Not supported | Not supported | Handled seamlessly | # Know Your Customer (KYC) Source: https://docs.chainrails.io/concepts/kyc Understand Chainrails-owned KYC, progressive requirements, verification methods, and API states ## Overview Chainrails KYC is a reusable identity layer for headless financial flows. Instead of asking a user to repeat verification with every provider, Chainrails maintains one profile and evaluates it against the requirements of the provider and transaction being used. The engine follows a progressive model: clients collect only the requirements currently missing for a transaction. Information already provided or verified is reused where the next provider accepts it. Chainrails KYC applies to headless providers. For widget providers, create the ramp order and redirect the user to `widgetUrl`; that provider owns its KYC flow. ## How the flow works 1. Ask for the provider requirements with `GET /api/v1/kyc/requirements`. 2. Read the user's current eligibility with `GET /api/v1/kyc/state`. 3. Collect only missing, insufficient, or rejected fields. 4. Submit them with `POST /api/v1/kyc/submit`. 5. If an external verification URL is returned, redirect the user and poll state after they return. 6. Continue when `canProceed` is `true`, or direct the user to support when `blocked` is `true`. Submitting KYC creates the profile automatically when one does not exist. Only email is required initially, and the profile is reused through the normalized email address. Your application remains responsible for authenticating the user and verifying ownership of that email. ## Progressive requirements Every required field has an assurance level: | Assurance | Meaning | | ---------- | ---------------------------------------------------------------------------------------------------------------------- | | `provided` | A stored value is sufficient. This commonly applies to mutable details such as phone or address. | | `verified` | The value must be validated by an accepted identity source. This commonly applies to names, DOB, and identity numbers. | State responses group requirements by what the client should do next: | Property | Client action | | -------------------------- | ----------------------------------------------------------------------- | | `missingRequirements` | Ask the user for the missing values. | | `insufficientRequirements` | Submit the stronger evidence requested by the requirement. | | `pendingRequirements` | Wait and poll state again. | | `rejectedRequirements` | Correct the relevant information before resubmitting. | | `blockedRequirements` | Stop automatic retries and direct the user to support. | | `satisfiedRequirements` | No further action is required for these fields. | | `requiredCapabilities` | Complete the listed verification flow, such as `external_verification`. | | `satisfiedCapabilities` | The capability has already been completed and can be reused. | ## Verification methods Chainrails currently supports: * **Text verification:** registry validation of country-specific identifiers. Nigeria currently supports BVN and NIN. * **External verification:** a hosted identity-document and biometric flow covering document verification, liveness, face match, phone verification, and device/IP analysis. * **Manual review:** used when verified identity evidence conflicts or a provider result is inconclusive. `countryCode` identifies the transaction corridor. `fields.country` identifies the user's current country of residence. They are separate concepts and do not need to match. ## Standalone KYC endpoints Use the dedicated endpoints when KYC is managed independently of a ramp transaction or will be reused across multiple Chainrails products: ```text theme={null} GET /api/v1/kyc/requirements GET /api/v1/kyc/state POST /api/v1/kyc/submit ``` For a ramp-only integration, use the equivalent `/api/v1/ramp/kyc` entry points documented in the [Complete Ramping Guide](/guides/ramping). They apply ramp-specific amount handling and access checks while calling the same KYC engine. ## Security and privacy * Send KYC requests only from your authenticated backend. * Never expose your Chainrails API key in a frontend application. * Do not log identity numbers, document data, verification payloads, or decrypted profile fields. * Do not assume that returning from an external verification URL means approval; always query KYC state. * Do not repeatedly resubmit blocked data. Manual review is required when `blocked` is `true`. # Paymaster Source: https://docs.chainrails.io/concepts/paymaster Sponsor protocol fees for your users with Chainrails Paymaster The Chainrails Paymaster enables you to sponsor protocol fees (bridging and swap fees) on behalf of your users, creating a seamless and frictionless payment experience for your application. ## What is a Paymaster? Each cross-chain transaction on Chainrails incurs protocol fees to cover costs associated with bridges, AMMs and relayers. These fees are charged in the token being transferred, eliminating the need for users to hold multiple tokens for gas or fees. ## Getting Started Here’s how to enable and use the Paymaster in your application: ### Step 1: Access the Dashboard Navigate to the [Chainrails Dashboard](https://dashboard.chainrails.io) and go to the **Billing** section. ### Step 2: Choose Your Billing Plan Chainrails offers three billing options to suit different use cases: **Best for:** Use cases that's fine with users paying their own fees * Users pay their own protocol fees * No additional costs to you * Easy to get started **Best for:** Growing applications with variable transaction volumes * You pay protocol fees as transactions occur * Only pay for what you use * Requires manual balance management * Real-time usage tracking in the Dashboard Keep your paymaster balance funded to prevent transaction failures. **Best for:** High-volume applications with predictable usage * Fixed monthly fee with included transaction quota * No manual paymaster management required * Automatic overage handling * Never worry about insufficient balance * Best value for consistent usage Transactions beyond your monthly quota incur additional fees. View pricing details in the Dashboard. ### Step 3: Enable the Paymaster Once you select either **PAYG** or **Monthly Subscription**, the Paymaster is automatically enabled for your account. All transactions using your API key will have protocol fees covered. ## Using the Paymaster in Your Application Once enabled, the Paymaster works automatically—no code changes required. Simply make transactions as usual: PS: Ignore the `fees` field returned in intents as that is returned to track usage, but you would notice the `totalAmount` field is same as the `initialAmount` field, which means the user is not charged any additional fees. ## Managing Your Paymaster ### For PAYG Plans **Funding Your Balance:** 1. Go to the Dashboard → Billing section 2. Click "Add Funds" to deposit funds to your paymaster balance 3. Choose your funding amount **Monitoring Usage:** * View real-time balance in the Dashboard * Track transaction history and fee breakdowns * Set up low-balance alerts We recommend maintaining a balance that covers at least 7 days of expected transaction volume. ### For Monthly Subscription Plans **Transaction Quotas:** * Your plan includes a set number of transactions per month * View your current usage and remaining quota in the Dashboard * Overages are automatically charged at the end of your billing cycle **No Manual Management:** * Transactions never fail due to insufficient balance * Automatic renewal each month * Upgrade or downgrade anytime ## FAQ Transactions will fail if your paymaster balance is insufficient. Users will see an error and the transaction won't be processed. To avoid this, regularly monitor your balance and top up as needed. Yes, you can switch back to the Free plan at any time. This will require users to pay their own protocol fees for subsequent transactions. Protocol fees vary based on the source and destination chains, token being transferred, and current network conditions. View detailed fee breakdowns for each transaction in your Dashboard. # Refunds Source: https://docs.chainrails.io/concepts/refunds How Chainrails automates refunds for failed/excess payments Refunds are an essential part of any payment system, they ensure users never lose funds due to failed or excess transactions. Chainrails automates the refund process for all cross-chain transfers, making it secure, predictable, and effortless for both developers and users. ## When are refunds triggered? Refunds can occur in two primary scenarios: ### 1. Failed Transfers If a cross-chain transfer fails to execute (for example, due to network congestion, insufficient deposit, or unexpected errors), the funds are automatically refunded once the intent expires (typically in 1 hour). This delay ensures that premature refunds aren’t made while a transaction may still be in progress or could be retried. ### 2. Excess Payments If a user sends more than the required amount for an intent, Chainrails automatically deducts the needed value and refunds the excess back to the sender. ## Predictable Outcomes Chainrails is designed to protect users from cross-chain risks. Relayers handle bridge and liquidity risk behind the scenes, meaning users are always guaranteed one of two outcomes: * Successful settlement — funds arrive on the destination chain, or * Automatic refund — funds are returned to the sender’s wallet. In other words, users never lose funds because of failed bridges or liquidity issues. ## Manual Refunds (Rare Cases) In very rare cases where an intent’s final status cannot be determined automatically (for example, due to an indexer outage), you can trigger a refund manually using the `POST /api/v1/intents/{intent_address}/refund`. For more complicated cases, please contact our support team with the intent address and transaction details for assistance. # EVM Implementation Source: https://docs.chainrails.io/contract-reference/evm-implementation Chainrails Intent Broadcaster Implementation for EVM-compatible chains ## Overview In this section, we walk you through how to implement the Chainrails Intent Broadcaster in your smart contracts on EVM-compatible chains. ### Step 1 — Import the Interface First, create and import the `IIntentBroadcaster` interface into your contract. ```Solidity Import theme={null} import {IIntentBroadcaster} from "./interfaces/IIntentBroadcaster.sol"; ``` ### Step 2 — Define the required types Next, define the `BroadcastedIntent`, `Chain` and `TokenAmount` objects in your contract. These are used to structure the data for broadcasting an intent. ```Solidity Types theme={null} struct BroadcastedIntent { Chain sourceChain; Chain destinationChain; TokenAmount[] bridgeTokenOutOptions; address sender; bytes32 destinationRecipient; address refundAddress; } enum Chain { ARBITRUM_MAINNET, ARBITRUM_TESTNET, BASE_MAINNET, BASE_TESTNET, STARKNET_MAINNET, STARKNET_TESTNET, AVALANCHE_MAINNET, AVALANCHE_TESTNET, ETHEREUM_MAINNET, ETHEREUM_TESTNET, POLYGON_MAINNET, POLYGON_TESTNET, ... // See full enum in example repo } struct TokenAmount { bytes32 token; uint256 amount; } ``` ### Step 3 — Create a util function to encode token address ```Solidity Encode to bytes32 theme={null} function encodeEvmToken(address tokenAddress) internal pure returns (bytes32) { return bytes32(uint256(uint160(tokenAddress))); } ``` ### Step 4 — Create the Intent Broadcaster Instance Create an instance of the `IIntentBroadcaster` interface in your contract, pointing to the deployed `IntentBroadcaster` contract address. ```Solidity Intent Broadcaster Instance theme={null} IIntentBroadcaster public immutable broadcaster; constructor(address _broadcasterAddress) { require(_broadcasterAddress != address(0), "Invalid broadcaster address"); broadcaster = IIntentBroadcaster(_broadcasterAddress); } ``` ### Step 5 — Broadcast an Intent Now you can create a function in your contract to broadcast an intent using the `broadcastIntent` function from the `IIntentBroadcaster` interface. This function will take in the necessary parameters, structure the `BroadcastedIntent` object, and call the broadcaster to broadcast the intent. ```Solidity Broadcast Intent theme={null} interface IERC20Minimal { function transferFrom(address from, address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } event IntentSent(bytes32 indexed broadcastId, address indexed sender, uint256 amount); event IntentCancelled(bytes32 indexed broadcastId, address indexed caller); function broadcastSimpleIntent( Chain sourceChain, address sourceToken, uint256 amount, Chain destinationChain, address destinationToken, bytes32 recipient, address refundAddress, uint256 maxFeeBudget, bool isLive ) external returns (bytes32 broadcastId) { uint256 totalDeposit = amount + maxFeeBudget; // Transfer tokens from sender to this contract require( IERC20Minimal(sourceToken).transferFrom(msg.sender, address(this), totalDeposit), "Token transferFrom failed" ); // Approve the broadcaster to spend the tokens require( IERC20Minimal(sourceToken).approve(address(broadcaster), totalDeposit), "Token approve failed" ); // Create the intent BroadcastedIntent memory intent = BroadcastedIntent({ sourceChain: sourceChain, destinationChain: destinationChain, bridgeTokenOutOptions: new TokenAmount[](1), sender: msg.sender, destinationRecipient: recipient, refundAddress: refundAddress }); // Set the token amount for bridge output (destination token address) intent.bridgeTokenOutOptions[0] = TokenAmount({token: encodeEvmToken(destinationToken), amount: amount}); // Create deposits array (source token address) - includes amount + fee budget TokenAmount[] memory deposits = new TokenAmount[](1); deposits[0] = TokenAmount({token: encodeEvmToken(sourceToken), amount: totalDeposit}); // Broadcast the intent broadcastId = broadcaster.broadcastIntent(intent, deposits, maxFeeBudget, isLive); emit IntentSent(broadcastId, msg.sender, amount); return broadcastId; } ``` ## Cancellation and Refunds Cancellation and refunds of broadcasted intents are handled automatically like a normal intent after the intent expiration (typically in 1 hour after broadcasting). You can also choose to implement a function in your contract to allow users to manually cancel their broadcasted intents before expiration by calling the `cancelBroadcast` function from the `IIntentBroadcaster` interface. ```Solidity Cancel Broadcast theme={null} function cancelBroadcast(bytes32 broadcastId) external { broadcaster.cancelBroadcast(broadcastId); emit IntentCancelled(broadcastId, msg.sender); } ``` **NB:** Only the broadcasting contract can manually cancel a broadcast before expiration, if it has not been executed. Once cancelled, the escrowed funds for that intent will be automatically refunded to the specified `refundAddress`. Find the full implementation of the above example in the GitHub repository. # EVM Interface Source: https://docs.chainrails.io/contract-reference/evm-interface Chainrails Intent Broadcaster Interface for EVM-compatible chains ## Overview The Chainrails Intent Broadcaster provides an interface for EVM-compatible chains, allowing protocols to create intents directly from their smart contracts on all our supported EVM chains. ## Contract Address The `IntentBroadcaster` contract is deployed to the same address on all our supported EVM chains. ```Contract Address theme={null} 0xC3d9c7d72dfe9512E1cE06739dd9916d31fD6144 ``` ## Interface The `IntentBroadcaster` contract exposes the following interface: ```Solidity EVM Interface theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "../utils/Types.sol"; /// @title IIntentBroadcaster /// @notice Interface for the IntentBroadcaster contract used to interact with Chainrails on the contract level interface IIntentBroadcaster { /// @notice Broadcasts a Chainrails intent and escrows funds /// @param intent The Chainrails intent to broadcast /// @param deposits Array of token amounts to deposit /// @param maxFeeBudget The maximum fee budget the sender is willing to pay (0 to use paymaster) /// @param isLive Whether this is a production broadcast (true) or test broadcast (false) /// @return broadcastId The unique identifier for this broadcast function broadcastIntent( BroadcastedIntent calldata intent, TokenAmount[] calldata deposits, uint256 maxFeeBudget, bool isLive ) external returns (bytes32 broadcastId); /// @notice Allows initiator to cancel a broadcast and retrieve escrowed funds /// @dev Automatically refunds all payment tokens used in the broadcast /// @param broadcastId The unique identifier of the broadcast to cancel function cancelBroadcast(bytes32 broadcastId) external; /// @notice Returns the total escrowed amount for a specific broadcast across all tokens /// @param broadcastId The broadcast identifier /// @return amount The total escrowed amount function getEscrowedAmount(bytes32 broadcastId) external view returns (uint256 amount); /// @notice Returns whether a broadcast has been executed /// @param broadcastId The broadcast identifier /// @return executed True if the broadcast has been executed, false otherwise function getBroadcastExecutionStatus(bytes32 broadcastId) external view returns (bool executed); /// @notice Emitted when an intent is broadcasted /// @param broadcastId The unique identifier for this broadcast /// @param sender The address to use as sender /// @param sourceChain The source blockchain /// @param destinationChain The destination blockchain /// @param recipient The recipient address on destination chain /// @param refundAddress The address to refund to if needed /// @param deposits Array of token amounts deposited for this broadcast /// @param bridgeTokenOutOptions The bridge token output options /// @param broadcaster The IntentBroadcaster contract address /// @param broadcastingContract The contract that initiated the broadcast /// @param isLive Whether this is a production broadcast (true) or test (false) event IntentBroadcasted( bytes32 indexed broadcastId, address indexed sender, Chain sourceChain, Chain destinationChain, bytes32 recipient, address refundAddress, TokenAmount[] deposits, TokenAmount[] bridgeTokenOutOptions, address broadcaster, address indexed broadcastingContract, bool isLive ); /// @notice Emitted when a broadcast is executed /// @param broadcastId The unique identifier of the broadcast /// @param executor The address that executed the broadcast event BroadcastExecuted(bytes32 indexed broadcastId, address indexed executor); /// @notice Emitted when a broadcast is cancelled /// @param broadcastId The unique identifier of the broadcast /// @param caller The address that triggered the cancellation /// @param refundAddress The address that received the escrowed funds event BroadcastCancelled(bytes32 indexed broadcastId, address indexed caller, address indexed refundAddress); /// @notice Thrown when an unauthorized address attempts to cancel a broadcast error UnauthorizedCancellation(); /// @notice Thrown when attempting to execute or cancel an already executed broadcast error BroadcastAlreadyExecuted(); } ``` # Introduction Source: https://docs.chainrails.io/contract-reference/introduction Contract-level Integrations With Chainrails ## Overview The Chainrails Intent Broadcaster enables contract-level integrations with Chainrails. It allows protocols to create intents directly from their smart contracts instead of via API calls, with funds escrowed on-chain and processed automatically. ## How It Works
```mermaid theme={null} sequenceDiagram autonumber participant U as User participant BC as Broadcasting Contract participant IB as Chainrails IntentBroadcaster (on source chain) participant IX as Indexer + Webhook participant BE as Chainrails Backend participant RT as Router/Quote Engine participant IC as IntentCore/Execution Contracts participant BR as Bridge Protocol (if cross-chain) U->>BC: Initiate transfer intent in integrator app BC->>IB: broadcast_intent(...) IB->>IB: Lock user funds in escrow IB-->>IX: Emit IntentBroadcasted(broadcastId, payload) IX->>BE: POST /v1/broadcaster/webhooks/process-intent BE->>BE: Verify webhook + client + whitelist BE->>RT: Compute route + bridge + fee data RT-->>BE: Best executable route alt Same-chain route BE->>IC: startBroadcastedIntent(...) IC->>IC: Execute transfer on source chain IC-->>BE: Intent completed else Cross-chain route BE->>IC: startBroadcastedIntent(...bridgeData) IC->>BR: Initiate bridge transfer BR-->>IC: Settlement/fill on destination chain IC-->>BE: Intent completed end ``` The diagram above illustrates the flow: 1. **Your contract broadcasts an intent** * Your integration contract calls `broadcast_intent`. * Chainrails escrows the funds and emits `IntentBroadcasted` with a `broadcastId`. 2. **Chainrails picks the best route** * The event is indexed and sent to the backend. * Chainrails validates the caller and computes the best executable route. 3. **Chainrails executes on-chain** * The backend calls `startBroadcastedIntent` with route data for on-chain execution. 4. **Intent settles and completes** * Funds are fulfilled to the destination based on the selected route. ## Broadcasting an Intent To broadcast an intent from your contract, you simply need to interface with the `IntentBroadcaster` contract on the source chain. Method name depends on your chain: * EVM: `broadcastIntent` * Starknet/Solana: `broadcast_intent` This takes in parameters such as: * The broadcasted intent payload (`sourceChain`, `destinationChain`, `bridgeTokenOutOptions`, `sender`, `refundAddress`, `destinationRecipient`) * `deposits` — an array of tokens and amounts to be escrowed for the intent. * `maxFeeBudget` — the maximum fee budget for the intent, which can be used to cover execution fees on the destination chain. Leave this as 0 to use paymaster for fee payment. * `isLive` — A boolean indicating if it's a production intent or a test intent. We currently only support production intents, so this should be set to `true`. We've created full example contracts in Solidity, Cairo and Rust for EVM, Starknet and Solana respectively, demonstrating how to broadcast intents from your contracts, you can find them below: * [Solidity Example](https://github.com/horuslabsio/chainrails-demo/blob/main/contracts/solidity) * [Cairo Example](https://github.com/horuslabsio/chainrails-demo/blob/main/contracts/starknet) * Rust example (coming soon) ## Whitelisting Contracts To ensure security and prevent unauthorized use, only whitelisted contracts can broadcast intents for a particular client. To whitelist your contract, you need to: 1. Sign up for a Chainrails account on the [Chainrails Dashboard](https://dashboard.chainrails.io). 2. Head to Settings -> Whitelisted Contracts 3. Add the chain and contract address of your integration contract. Once your contract is whitelisted, you should be able to broadcast intents directly from your contract. ## Notes The `IntentBroadcaster` currently only supports the USDC token. Support for additional tokens is coming soon. # Starknet Implementation Source: https://docs.chainrails.io/contract-reference/starknet-implementation Chainrails Intent Broadcaster Implementation for Starknet ## Overview In this section, we walk you through how to implement the Chainrails Intent Broadcaster in your Cairo contracts on Starknet. ### Step 1 — Import required interfaces and types Import the broadcaster dispatcher, ERC20 dispatcher, and shared types. ```Rust Imports theme={null} use starknet::ContractAddress; use starknet::{get_caller_address, get_contract_address}; use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess}; use core::num::traits::Zero; use crate::base::types::types::{BroadcastedIntent, Chain, TokenAmount}; use crate::interfaces::IERC20::{IERC20Dispatcher, IERC20DispatcherTrait}; use crate::mocks::interfaces::IMockIntentBroadCaster::{ IIntentBroadCasterDispatcher, IIntentBroadCasterDispatcherTrait, }; use crate::utils::address_utils::contract_address_to_u256; ``` ### Step 2 — Define your contract interface Expose functions for broadcasting, canceling, and querying execution/escrow status. ```Rust Contract Interface theme={null} #[starknet::interface] pub trait ISimpleIntentBroadcaster { fn broadcast_simple_intent( ref self: TContractState, source_chain: Chain, source_token: ContractAddress, amount: u256, destination_chain: Chain, destination_token: ContractAddress, recipient: u256, refund_address: ContractAddress, max_fee_budget: u256, is_live: bool, ) -> felt252; fn cancel_intent(ref self: TContractState, broadcast_id: felt252); fn is_executed(self: @TContractState, broadcast_id: felt252) -> bool; fn get_escrowed_amount(self: @TContractState, broadcast_id: felt252) -> u256; } ``` ### Step 3 — Add utility for token address encoding Chainrails token representation uses `u256`, so convert Starknet `ContractAddress` to `u256`. ```Rust Address Utils theme={null} use core::felt252; use core::integer::u256; use starknet::ContractAddress; pub fn contract_address_to_u256(address: ContractAddress) -> u256 { let felt_value: felt252 = address.try_into().unwrap(); felt_value.try_into().unwrap() } ``` ### Step 4 — Store broadcaster address and initialize it Persist the broadcaster address in storage and validate it in constructor. ```Rust Storage and Constructor theme={null} #[storage] struct Storage { broadcaster: ContractAddress, } #[constructor] fn constructor(ref self: ContractState, broadcaster_address: ContractAddress) { assert(!broadcaster_address.is_zero(), 'Invalid broadcaster address'); self.broadcaster.write(broadcaster_address); } ``` ### Step 5 — Broadcast an intent Create a function that escrows funds, approves broadcaster spend, builds `BroadcastedIntent` + `deposits`, and calls `broadcast_intent`. ```Rust Broadcast Intent theme={null} #[event] #[derive(Drop, starknet::Event)] pub enum Event { IntentSent: IntentSent, } #[derive(Drop, starknet::Event)] pub struct IntentSent { #[key] pub broadcast_id: felt252, #[key] pub sender: ContractAddress, pub amount: u256, } fn broadcast_simple_intent( ref self: ContractState, source_chain: Chain, source_token: ContractAddress, amount: u256, destination_chain: Chain, destination_token: ContractAddress, recipient: u256, refund_address: ContractAddress, max_fee_budget: u256, is_live: bool, ) -> felt252 { let total_deposit = amount + max_fee_budget; let caller = get_caller_address(); let this_contract = get_contract_address(); let broadcaster_address = self.broadcaster.read(); // Pull source tokens from user into this contract. let token_dispatcher = IERC20Dispatcher { contract_address: source_token }; token_dispatcher.transfer_from(caller, this_contract, total_deposit); // Allow broadcaster to escrow the tokens. token_dispatcher.approve(broadcaster_address, total_deposit); let bridge_token_out_options = array![ TokenAmount { token: contract_address_to_u256(destination_token), amount }, ]; let intent = BroadcastedIntent { source_chain, destination_chain, bridge_token_out_options, sender: caller, destination_recipient: recipient, refund_address, }; let deposits = array![ TokenAmount { token: contract_address_to_u256(source_token), amount: total_deposit, }, ]; let broadcast_dispatcher = IIntentBroadCasterDispatcher { contract_address: broadcaster_address, }; let broadcast_id = broadcast_dispatcher.broadcast_intent(intent, deposits, max_fee_budget, is_live); self.emit(IntentSent { broadcast_id, sender: caller, amount }); broadcast_id } ``` ## Cancellation and Refunds Cancellation and refunds of broadcasted intents are handled automatically after intent expiration (typically around 1 hour after broadcasting). You can also support manual cancel from your broadcasting contract: ```Rust Cancel Broadcast theme={null} fn cancel_intent(ref self: ContractState, broadcast_id: felt252) { let broadcaster_address = self.broadcaster.read(); let broadcast_dispatcher = IIntentBroadCasterDispatcher { contract_address: broadcaster_address, }; broadcast_dispatcher.cancel_broadcast(broadcast_id); } ``` **NB:** Only the broadcasting contract can manually cancel a broadcast before expiration, if it has not been executed. Once cancelled, escrowed funds for that broadcast are refunded to the configured `refund_address`. Find the full implementation of the above example in the GitHub repository. # Starknet Interface Source: https://docs.chainrails.io/contract-reference/starknet-interface Chainrails Intent Broadcaster Interface for Starknet ## Overview The Chainrails Intent Broadcaster provides a Starknet interface so protocols can create intents directly from Cairo contracts. ## Contract Address Here's the deployed address of the `IntentBroadcaster` contract on Starknet: ```Rust Contract Address theme={null} 0x03411de7524ba7b58960e6ac54bcb996c90ab0ca6ac8fd38177f780ee900c196 ``` ## Interface The broadcaster interface used in the Starknet demo is shown below: ```Rust Starknet Interface theme={null} use core::array::Array; use core::integer::u256; use starknet::ContractAddress; use crate::base::types::types::{BroadcastedIntent, Chain, TokenAmount}; #[starknet::interface] pub trait IIntentBroadCaster { /// @notice Broadcasts a new payment intent and escrows the required tokens /// @param intent The broadcasted intent containing transfer details and destination information /// @param deposits Array of token amounts to be escrowed for this broadcast /// @param max_fee_budget Maximum fee amount /// @return felt252 Unique identifier for the broadcasted intent fn broadcast_intent( ref self: TState, intent: BroadcastedIntent, deposits: Array, max_fee_budget: u256, isLive: bool, ) -> felt252; /// @notice Cancels a broadcasted intent and returns escrowed tokens to the broadcaster /// @param broadcast_id The unique identifier of the broadcast to cancel fn cancel_broadcast(ref self: TState, broadcast_id: felt252); /// @notice Retrieves the total amount of tokens currently escrowed for a broadcast /// @param broadcast_id The unique identifier of the broadcast to query /// @return u256 Total amount of tokens held in escrow for this broadcast fn get_escrowed_amount(self: @TState, broadcast_id: felt252) -> u256; /// @notice Checks whether a broadcasted intent has been executed /// @param broadcast_id The unique identifier of the broadcast to query /// @return bool True if the broadcast has been executed, false otherwise fn get_broadcast_execution_status(self: @TState, broadcast_id: felt252) -> bool; } ``` The interface relies on these core types: ```Rust Types theme={null} #[derive(Debug, Drop, Copy, Serde, Hash, PartialEq, starknet::Store)] pub struct TokenAmount { pub token: u256, pub amount: u256, } #[derive(Drop, Serde, Clone, PartialEq)] pub struct BroadcastedIntent { pub source_chain: Chain, pub destination_chain: Chain, pub bridge_token_out_options: Array, pub sender: ContractAddress, pub destination_recipient: u256, pub refund_address: ContractAddress, } ``` # Supported Networks, Tokens & Currencies Source: https://docs.chainrails.io/essentials/integrations Check out the networks, tokens and currencies supported by Chainrails ## Supported Networks | Network | Mainnet | Testnet | Bi-directional | | --------- | ----------- | ------- | -------------- | | Ethereum | ✅ | ✅ | ✅ | | Arbitrum | ✅ | ✅ | ✅ | | Avalanche | ✅ | ✅ | ✅ | | Base | ✅ | ✅ | ✅ | | Starknet | ✅ | ✅ | ✅ | | Optimism | ✅ | ✅ | ✅ | | Monad | ✅ | ✅ | ✅ | | Solana | ✅ | ✅ | ✅ | | BNB Chain | ✅ | ❌ | ✅ | | Polygon | ✅ | ❌ | ✅ | | HyperEVM | ✅ | ❌ | ✅ | | Tron | ✅ | ❌ | ❌ | | Lisk | ☑️ (paused) | ❌ | ✅ | **NB:** Bi-directional support means that the network supports both "paying from" and "receiving to" the network. If a network does not have bi-directional support, it can only be used as a payment chain. For example, Tron is currently only supported for payments, but not for settlements. ## Supported Tokens We support a wide range of tokens across all supported networks. Including but not limited to USDC, USDT, DAI, USDS, BUSD, EURC, LINK, POL, AVAX, WMON, ETH, WETH, STRK, BNB and more. Query the quotes endpoint to get a full list of supported tokens and their associated networks. **NB:** All testnet networks only support USDC for development and testing purposes. ## Supported Ramp Countries The table below lists all countries supported for fiat ramping and their onramp/offramp/headless API support status. | Country | Onramping | Offramping | Headless API | | --------------------------- | :-------: | :--------: | :----------: | | Argentina (ARS) | ✅ | ✅ | ✅ | | Benin (XOF) | ✅ | ✅ | ✅ | | Botswana (BWP) | ✅ | ✅ | ✅ | | Brazil (BRL) | ✅ | ✅ | ✅ | | Cameroon (XAF) | ✅ | ✅ | ✅ | | Colombia (COP) | ✅ | ✅ | ✅ | | Gabon (XAF) | ✅ | ✅ | ✅ | | Ivory Coast (XOF) | ✅ | ✅ | ✅ | | Kenya (KES) | ✅ | ✅ | ✅ | | Malawi (MWK) | ✅ | ✅ | ✅ | | Mexico (MXN) | ✅ | ✅ | ✅ | | Nigeria (NGN) | ✅ | ✅ | ✅ | | Republic of the Congo (XAF) | ✅ | ✅ | ✅ | | Rwanda (RWF) | ✅ | ✅ | ✅ | | Senegal (XOF) | ✅ | ✅ | ✅ | | Tanzania (TZS) | ✅ | ✅ | ✅ | | Togo (XOF) | ✅ | ✅ | ✅ | | Uganda (UGX) | ✅ | ✅ | ✅ | | Zambia (ZMW) | ✅ | ✅ | ✅ | | Australia (AUD) | ✅ | ❌ | ❌ | | Austria (EUR) | ✅ | ❌ | ❌ | | Belgium (EUR) | ✅ | ❌ | ❌ | | Burkina Faso (XOF) | ✅ | ❌ | ❌ | | Canada (CAD) | ✅ | ❌ | ❌ | | Chile (CLP) | ✅ | ❌ | ❌ | | Croatia (EUR) | ✅ | ❌ | ❌ | | Cyprus (EUR) | ✅ | ❌ | ❌ | | Czechia (CZK) | ✅ | ❌ | ❌ | | Denmark (DKK) | ✅ | ❌ | ❌ | | Dominican Republic (DOP) | ✅ | ❌ | ❌ | | Ecuador (USD) | ✅ | ❌ | ❌ | | El Salvador (USD) | ✅ | ❌ | ❌ | | Estonia (EUR) | ✅ | ❌ | ❌ | | Finland (EUR) | ✅ | ❌ | ❌ | | France (EUR) | ✅ | ❌ | ❌ | | Germany (EUR) | ✅ | ❌ | ❌ | | Ghana (GHS) | ✅ | ❌ | ❌ | | Greece (EUR) | ✅ | ❌ | ❌ | | Hong Kong (HKD) | ✅ | ❌ | ❌ | | India (INR) | ✅ | ❌ | ❌ | | Indonesia (IDR) | ✅ | ❌ | ❌ | | Ireland (EUR) | ✅ | ❌ | ❌ | | Italy (EUR) | ✅ | ❌ | ❌ | | Japan (JPY) | ✅ | ❌ | ❌ | | Kiribati (AUD) | ✅ | ❌ | ❌ | | Latvia (EUR) | ✅ | ❌ | ❌ | | Liechtenstein (CHF) | ✅ | ❌ | ❌ | | Lithuania (EUR) | ✅ | ❌ | ❌ | | Luxembourg (EUR) | ✅ | ❌ | ❌ | | Malta (EUR) | ✅ | ❌ | ❌ | | Marshall Islands (USD) | ✅ | ❌ | ❌ | | Micronesia (USD) | ✅ | ❌ | ❌ | | Montenegro (EUR) | ✅ | ❌ | ❌ | | Nauru (AUD) | ✅ | ❌ | ❌ | | Netherlands (EUR) | ✅ | ❌ | ❌ | | New Zealand (NZD) | ✅ | ❌ | ❌ | | Norway (NOK) | ✅ | ❌ | ❌ | | Oman (OMR) | ✅ | ❌ | ❌ | | Peru (PEN) | ✅ | ❌ | ❌ | | Philippines (PHP) | ✅ | ❌ | ❌ | | Poland (PLN) | ✅ | ❌ | ❌ | | Portugal (EUR) | ✅ | ❌ | ❌ | | Romania (RON) | ✅ | ❌ | ❌ | | San Marino (EUR) | ✅ | ❌ | ❌ | | Singapore (SGD) | ✅ | ❌ | ❌ | | Slovakia (EUR) | ✅ | ❌ | ❌ | | Slovenia (EUR) | ✅ | ❌ | ❌ | | South Africa (ZAR) | ✅ | ❌ | ❌ | | Spain (EUR) | ✅ | ❌ | ❌ | | Sweden (SEK) | ✅ | ❌ | ❌ | | Switzerland (CHF) | ✅ | ❌ | ❌ | | Thailand (THB) | ✅ | ❌ | ❌ | | Timor-Leste (USD) | ✅ | ❌ | ❌ | | Turkey (TRY) | ✅ | ❌ | ❌ | | Tuvalu (AUD) | ✅ | ❌ | ❌ | | Ukraine (UAH) | ✅ | ❌ | ❌ | | United Arab Emirates (AED) | ✅ | ❌ | ❌ | | United Kingdom (GBP) | ✅ | ❌ | ❌ | | United States (USD) | ✅ | ❌ | ❌ | | Viet Nam (VND) | ✅ | ❌ | ❌ | We are actively working to add support for more networks, currencies and tokens. If you have specific requests, please reach out to our team via [contact@horuslabs.co](mailto:contact@horuslabs.co). You can also track upcoming releases [here](../changelog/upcoming). # Settlement Modes Source: https://docs.chainrails.io/essentials/settlements Understanding Instant and Standard settlement options Chainrails supports two settlement modes optimized for different transaction sizes and use cases. The mode is automatically selected based on the transaction amount and available routes. ## Settlement Types ### Instant Settlement (Fast-Fill) For smaller transfers, Chainrails uses prefunded liquidity to deliver funds on the destination chain immediately—typically within seconds. **Key Features:** * **Available for:** Transfers up to **\$3,000** * **Speed:** Instant delivery in seconds * **How it works:** Funds are prefunded by Chainrails relayers and finalized asynchronously This mode prioritizes speed while maintaining strong reliability guarantees. Funds arrive instantly while the underlying cross-chain settlement happens in the background. ### Standard Settlement For larger transfers, Chainrails defaults to standard settlement using canonical cross-chain bridges and protocols. **Key Features:** * **Used for:** Transfers **above \$3,000** * **Speed:** Settlement time varies by bridge (typically 2-15 minutes) * **How it works:** Funds settle once the underlying bridge or protocol finalizes While slightly slower, standard settlement minimizes risk for large amounts by using battle-tested canonical bridges. ## Comparison | Feature | Instant Settlement | Standard Settlement | | ---------------- | -------------------- | ------------------------- | | **Amount Limit** | Up to \$3,000 | Above \$3,000 | | **Speed** | Seconds | 2-15 minutes | | **Mechanism** | Prefunded liquidity | Canonical bridges | | **Risk Profile** | Low (relayer-backed) | Minimal (protocol-backed) | ## Why This Design? Instant settlement relies on prefunded liquidity from Chainrails relayers. To ensure reliability and protect users from partial fills or failed transfers, we apply a conservative fast-fill limit. ### This Approach Enables Us To: Provide instant settlement where it matters most—for everyday transactions and consumer payments Maintain healthy liquidity pools without over-extending capital across chains Ensure reliable and predictable payment experiences for all transaction sizes Grow settlement capacity sustainably as the network matures As Chainrails scales and our relayer network becomes more efficiently decentralized, instant settlement limits will increase to serve larger transactions. ## FAQ Currently, Chainrails automatically optimizes for the fastest settlement mode available. For amounts under \$3,000, instant settlement is always preferred when available. If instant settlement isn't available for any reason, your transaction will automatically fall back to standard settlement. You'll be notified of the expected settlement time. No, fees are calculated based on the underlying bridge costs not the settlement mode. Yes! As our relayer network grows and becomes more decentralized, we plan to increase instant settlement limits to support larger transactions. # Mini-Apps Source: https://docs.chainrails.io/guides/mini-apps Integrate Chainrails into Farcaster/Base MiniApps Mini-apps are lightweight web applications that run inside social applications. Chainrails enables seamless cross-chain payments within these constrained environments, allowing users to pay with any token from any chain without leaving the app context. ## Overview Mini-apps present unique integration challenges: * **Constrained viewport**: Limited screen real estate requires compact UI components * **Embedded context**: Apps run inside Farcaster, Telegram or other platforms * **Simplified UX**: Users expect one-tap or minimal-interaction flows * **Platform constraints**: Must adhere to platform-specific guidelines and limitations Chainrails addresses these challenges through: * **Pre-built Payment Modal**: Compact, responsive UI that works in constrained viewports * **Session-based Authentication**: Secure, stateless payment sessions * **Deep Linking Support**: Seamless handoff between mini-app and wallet apps * **Platform SDKs**: Native integration with Farcaster SDKs *** ## Farcaster MiniApps This guide walks you through integrating Chainrails payments into a Farcaster MiniApp using the React SDK. ### Overview Farcaster MiniApps are web applications that run within the Farcaster ecosystem. Chainrails provides a React SDK that works seamlessly with MiniApps to accept cross-chain payments. ## Prerequisites * A Farcaster MiniApp project * Chainrails API key (get one from [dashboard.chainrails.io](https://dashboard.chainrails.io)) * A backend server to create session tokens ## Step 1: Install the SDK ```bash theme={null} npm install @chainrails/react @chainrails/sdk ``` ## Step 2: Set Up Session Endpoint Create a backend endpoint that generates secure session tokens. This protects your API key. ```javascript theme={null} // server.js (Node.js/Express example) const express = require("express"); const { Chainrails, crapi } = require("@chainrails/sdk"); const app = express(); Chainrails.config({ api_key: process.env.CHAINRAILS_API_KEY, }); app.get("/create-session", async (req, res) => { const session = await crapi.auth.getSessionToken({ amount: "10", // Payment amount or leave empty for user input recipient: "0xYourWalletAddress", destinationChain: "BASE_MAINNET", token: "USDC", }); res.json(session); }); ``` Deploy this server and add the URL to your MiniApp's manifest or environment configuration. ## Step 3: Initialize the Payment Modal In your MiniApp, initialize the Chainrails payment modal: ```jsx theme={null} // App.jsx import { usePaymentModal, PaymentModal } from "@chainrails/react"; import { sdk } from "@farcaster/miniapp-sdk"; export default function App() { const cr = usePaymentModal({ sessionToken: null, onCancel: () => { toast.info("Payment Cancelled"); }, onSuccess: (result?: { transactionHash?: string }) => { console.log(result); toast.success("Payment Successful", { description: result?.transactionHash, }); }, }); useEffect(() => { const run = async () => { sdk.actions.ready(); }; run(); }, []); const [loading, setLoading] = useState(false); async function pay() { setLoading(true); const res = await fetch(`https://server.url/create-session`,); const data = await res.json(); cr.updateSession(data); setLoading(false); cr.open(); } return (
); } ``` *** ## Best Practices 1. **Never expose API keys client-side**: Always use a backend session endpoint 2. **Validate all inputs**: Check recipient addresses, chains, tokens, and amounts 3. **Use HTTPS**: Ensure all communications are encrypted 4. **Implement rate limiting**: Prevent session endpoint abuse ## Additional Notes 1. Live API keys cannot be used with test networks. In test environments you can use supported mainnets and testnets, but once you switch to a live API key you must use mainnet networks only. 2. Testnets also do not have indexing support. If you are testing the modal on a testnet, users must click **I have made payment** after funding. If you are using API-driven flows, you must manually call `POST /api/v1/intents/{intent_address}/trigger-processing` to process the intent. Check out our Github demo repository for a mini-app example. # Mobile Development Source: https://docs.chainrails.io/guides/mobile-development Build mobile payment flows with Chainrails in React Native This guide shows how to integrate Chainrails into a React Native app so users can complete cross-chain payments on mobile. ## Overview Mobile payment flows have a few requirements that differ from desktop web integrations: * **Smaller screens**: Payment flows must stay compact and easy to complete on one device * **Wallet handoff**: Users may move between your app and a wallet app during the payment flow * **Secure backend usage**: Session tokens must still be created server-side to keep your API key private Chainrails supports mobile through the React Native SDK. This provides the same session-based payment flow as the web SDK, but with a mobile-optimized UI and wallet handoff support. * `@chainrails/react-native` for the mobile payment modal and hooks * `@chainrails/sdk` on your backend to create payment sessions If you need a broader overview of the session flow, see the [Quickstart](/quickstart) and the [Payment Modal reference](/sdk-reference/components/payment-modal). ## React Native This guide uses React Native, but the same backend session endpoint pattern applies to any mobile app using the Chainrails SDK surface. ### Prerequisites Before you begin, make sure you have: 1. A React Native project 2. A Chainrails API key from [dashboard.chainrails.io](https://dashboard.chainrails.io) 3. A backend service where you can create session tokens securely 4. At least one mobile wallet installed for testing ### Step 1: Install the SDK Install the React Native UI package in your app and the core SDK on your backend. ```bash theme={null} npm install @chainrails/react-native ``` ```bash theme={null} npm install @chainrails/sdk ``` The mobile app uses `@chainrails/react-native` to present the payment flow. Your server uses `@chainrails/sdk` to create session tokens. ### Step 2: Set Up Session Endpoint Create a backend endpoint that generates secure session tokens. The mobile app should call this endpoint right before opening the payment modal. ```javascript theme={null} // server.js (Node.js/Express example) const express = require("express"); const { Chainrails, crapi } = require("@chainrails/sdk"); const app = express(); app.use(express.json()); Chainrails.config({ api_key: process.env.CHAINRAILS_API_KEY, }); app.post("/create-session", async (req, res) => { try { const { amount, recipient, destinationChain, token } = req.body; const session = await crapi.auth.getSessionToken({ amount: amount ?? "10", recipient, destinationChain, token, }); res.json(session); } catch (error) { res.status(500).json({ message: "Failed to create payment session", error: error instanceof Error ? error.message : "Unknown error", }); } }); ``` At minimum, validate the `recipient`, `destinationChain`, `token`, and `amount` fields before creating a session. ### Step 3: Initialize the Payment Modal In your app, fetch a session from your backend and open the payment modal only after the session is ready. ```jsx theme={null} // App.jsx import { useState } from "react"; import { Alert, Button, View } from "react-native"; import { PaymentModal, usePaymentModal } from "@chainrails/react-native"; export default function App() { const [loading, setLoading] = useState(false); const cr = usePaymentModal({ sessionToken: null, onCancel: () => { Alert.alert("Payment cancelled"); }, onSuccess: (result) => { Alert.alert("Payment successful", result?.transactionHash ?? "Transaction completed"); }, }); async function pay() { setLoading(true); try { const res = await fetch("https://your-server.com/create-session", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ amount: "10", recipient: "0xYourWalletAddress", destinationChain: "BASE_MAINNET", token: "USDC", }), }); if (!res.ok) { throw new Error("Could not create payment session"); } const session = await res.json(); cr.updateSession(session); cr.open(); } catch (error) { Alert.alert("Unable to start payment", error instanceof Error ? error.message : "Something went wrong"); } finally { setLoading(false); } } return ( ); } ``` **Parameters:** * `session_url`: Your server endpoint for creating payment sessions. * `excludeChains` (optional): Array of chains to exclude from payment options. For deeper configuration options, see the [Payment Modal documentation](/sdk-reference/components/payment-modal). ## What happens next? When a user opens the modal: 1. The SDK fetches a secure session token from your backend 2. The modal presents available payment methods 3. Users can complete a crypto deposit from supported chains/tokens or a fiat deposit through supported ramp providers 4. Your `onSuccess` callback fires when the transaction completes 5. Funds settle to your configured `recipient` and destination chain ## Additional Notes 1. Live API keys cannot be used with test networks. In test environments you can use supported mainnets and testnets, but live API keys must use mainnet networks only. 2. Testnets do not have indexing support. In modal flows, users must click **I have made payment** after funding on testnets. In API-driven flows, use `POST /api/v1/intents/{intent_address}/trigger-processing` to process the intent manually. Explore a complete Payment Modal example in our Github repository. # Get Supported Chains Source: https://docs.chainrails.io/sdk-reference/chains/get-supported Retrieve all supported blockchain networks, optionally filtered by network type Retrieves all supported blockchain networks, optionally filtered by network type. **Supported chains include:** * **Ethereum**: `ETHEREUM_MAINNET`, `ETHEREUM_TESTNET` * **Arbitrum**: `ARBITRUM_MAINNET`, `ARBITRUM_TESTNET` * **Base**: `BASE_MAINNET`, `BASE_TESTNET` * **Avalanche**: `AVALANCHE_MAINNET`, `AVALANCHE_TESTNET` * **BSC**: `BSC_MAINNET` * **Starknet**: `STARKNET_MAINNET`, `STARKNET_TESTNET` * **Polygon**: `POLYGON_MAINNET`, `POLYGON_TESTNET` * **Optimism**: `OPTIMISM_MAINNET`, `OPTIMISM_TESTNET` * **Monad**: `MONAD_MAINNET`, `MONAD_TESTNET` * **HyperEVM**: `HYPEREVM_MAINNET`, `HYPEREVM_TESTNET` * **Lisk**: `LISK_MAINNET`, `LISK_TESTNET` ```typescript theme={null} import { crapi, Chainrails } from "@chainrails/sdk" Chainrails.config({ api_key: "your_api_key_here" }) // Get all chains const allChains = await crapi.chains.getSupported() console.log("All chains:", allChains) // Get only mainnet chains const mainnetChains = await crapi.chains.getSupported({ network: "mainnet" }) console.log("Mainnet chains:", mainnetChains) // Get only testnet chains const testnetChains = await crapi.chains.getSupported({ network: "testnet" }) console.log("Testnet chains:", testnetChains) ``` ```json theme={null} [ "ARBITRUM_MAINNET", "ARBITRUM_TESTNET", "AVALANCHE_MAINNET", "AVALANCHE_TESTNET", "BASE_MAINNET", "BASE_TESTNET", "STARKNET_MAINNET", "STARKNET_TESTNET", "BSC_MAINNET", "ETHEREUM_MAINNET", "ETHEREUM_TESTNET", "POLYGON_MAINNET", "POLYGON_TESTNET", "OPTIMISM_MAINNET", "OPTIMISM_TESTNET", "MONAD_MAINNET", "MONAD_TESTNET", "HYPEREVM_MAINNET", "HYPEREVM_TESTNET", "LISK_MAINNET", "LISK_TESTNET" ] ``` # Get Supported Tokens for Chain Source: https://docs.chainrails.io/sdk-reference/chains/get-supported-tokens Retrieve all supported tokens available on a specified blockchain network Retrieves all supported tokens available on a specified blockchain network. Chainrails supports multiple tokens across chains including: USDC, USDT, DAI, BUSD, EURC, ETH, WETH, BNB, STRK, and LORDS. ```typescript theme={null} import { crapi, Chainrails } from "@chainrails/sdk"; Chainrails.config({ api_key: "your_api_key_here", }); const tokens = await crapi.chains.getSupported({ chain: "BASE_MAINNET", }); console.log("Supported tokens:", tokens); ``` ```json theme={null} [ { "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "symbol": "USDC", "name": "USD Coin", "decimals": 6 }, { "address": "0x4200000000000000000000000000000000000006", "symbol": "WETH", "name": "Wrapped Ether", "decimals": 18 }, { "address": "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb", "symbol": "DAI", "name": "Dai Stablecoin", "decimals": 18 }, { "address": "0x1234567890abcdef1234567890abcdef12345678", "symbol": "EURC", "name": "Euro Coin", "decimals": 6 }, { "address": "0x4200000000000000000000000000000000000006", "symbol": "ETH", "name": "Ether", "decimals": 18 } ] ``` # Get Client Info Source: https://docs.chainrails.io/sdk-reference/client/get-client-info Retrieve information about the authenticated client Retrieves information about the authenticated client. ```typescript theme={null} import { crapi, Chainrails } from "@chainrails/sdk" Chainrails.config({ api_key: "your_api_key_here" }) const clientInfo = await crapi.client.getClientInfo() console.log("Client info:", clientInfo) ``` ```json theme={null} { "id": "e1ee3675-cb26-4a76-8206-a84f86e85862", "name": "My Application", "created_at": "2025-01-01T00:00:00.000Z", "updated_at": "2025-11-11T01:31:23.390Z" } ``` # PaymentModal Source: https://docs.chainrails.io/sdk-reference/components/payment-modal Drop-in payment modal and hooks for Chainrails web and mobile integrations. The Payment Modal component and hooks let you integrate Chainrails payments into React web and React Native apps. Choose the hook pattern that best matches how you want to manage payment sessions. ## Overview Chainrails provides UI SDK packages for both supported app environments: * `@chainrails/react`: Payment modal hooks and components for React web apps * `@chainrails/react-native`: Payment modal hooks and components for React Native apps The web and mobile SDKs follow the same session-based integration model: * **`usePaymentSession`**: Automatic session management with server-side URL * **`usePaymentModal`**: Manual session token control for advanced use cases For both cases, the `` component requires a server-generated session token to function. We've provided a Github repository with a curated Github template to help you get started quickly: Chainrails Demo Server Alternatively, you can also create a session without the SDK by calling the API endpoint directly if in a non-javascript environment. Refer to the API reference for more details: Create Modal Session ## Option 1: usePaymentSession Hook (Recommended) The `usePaymentSession` hook is ideal for React web implementations where your session URL is known upfront. The hook handles session creation automatically. ### When to Use * You have a static session endpoint * You want minimal setup and automatic session management * You don't need to fetch additional data before opening the modal ### Parameters * `session_url` (string, required): Your server endpoint for creating payment sessions * `onSuccess` (function, optional): Callback fired when payment completes successfully * `onCancel` (function, optional): Callback fired when user cancels the payment * `styles` (object, optional): Available styling (e.g., `{ accentColor: "#FF6B6B", theme: "dark" }`) * `excludeChains` (array, optional): Array of chains to exclude from payment options (e.g., `[chains.BASE_TESTNET, chains.STARKNET_TESTNET]`) ### Example Implementation ```javascript theme={null} import { PaymentModal, usePaymentSession, chains } from "@chainrails/react"; function App() { const cr = usePaymentSession({ session_url: "https://your-server.com/create-session", onCancel: () => { console.log("Payment Cancelled"); }, onSuccess: () => { console.log("Payment Successful"); }, }); return (
); } export default App; ``` ### Hook Return Value The `usePaymentSession` hook returns an object with: * `open()`: Function to open the payment modal * `close()`: Function to close the payment modal * `isOpen`: Boolean indicating if modal is currently open * `sessionToken`: The current session token (automatically managed) *** ## Option 2: usePaymentModal Hook (Advanced) The `usePaymentModal` hook provides manual control over session token management. Use this when you need to fetch session data dynamically, set custom amounts, coordinate the modal with other operations, or integrate in React Native. ### When to Use * You need to fetch session data from your server dynamically * You want to display custom amounts or user-specific information * You need to perform additional operations before opening the modal * You want explicit control over the session lifecycle * You are building a React Native integration ### Parameters * `sessionToken` (string | null, required): Session token obtained from your server * `onSuccess` (function, optional): Callback fired when payment completes successfully * `onCancel` (function, optional): Callback fired when user cancels the payment * `styles` (object, optional): Available styling (e.g., `{ accentColor: "#FF6B6B", theme: "dark" }`) * `excludeChains` (array, optional): Array of chains to exclude from payment options ### Example Implementation ```javascript theme={null} import { useState } from "react"; import { PaymentModal, usePaymentModal } from "@chainrails/react"; function App() { const [amount, setAmount] = useState(0); const [sessionToken, setSessionToken] = (useState < string) | (null > null); const [loading, setLoading] = useState(false); const cr = usePaymentModal({ sessionToken: sessionToken, onCancel: () => { console.log("Payment Cancelled"); }, onSuccess: () => { console.log("Payment Successful"); }, }); async function pay() { setLoading(true); try { const res = await fetch("https://your-server.com/create-session"); const data = await res.json(); cr.updateSession(data); cr.open(); } catch (error) { console.error("Error creating session:", error); } finally { setLoading(false); } } return (
); } export default App; ``` ### React Native Example ```javascript theme={null} import { useState } from "react"; import { Button, View } from "react-native"; import { PaymentModal, usePaymentModal } from "@chainrails/react-native"; function App() { const [loading, setLoading] = useState(false); const cr = usePaymentModal({ sessionToken: null, onCancel: () => { console.log("Payment Cancelled"); }, onSuccess: () => { console.log("Payment Successful"); }, }); async function pay() { setLoading(true); try { const res = await fetch("https://your-server.com/create-session"); const data = await res.json(); cr.updateSession(data); cr.open(); } catch (error) { console.error("Error creating session:", error); } finally { setLoading(false); } } return ( ); } ``` For more details on the SDK, check out our [SDK Reference](/sdk-reference/introduction) and [Quickstart](/quickstart) guides. ## The API The Chainrails API gives you direct access to the underlying infrastructure — perfect if you want full control over how requests, authentication, and responses are handled. You’ll interact with our endpoints directly using your preferred language or HTTP client. **We recommend using the API for:** * Server-side integrations * Advanced use cases requiring fine-grained control * Teams working in non-JavaScript environments ### Sample request to create a cross-chain intent ```bash theme={null} curl -X POST "https://api.chainrails.io/api/v1/intents" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54", "amount": "1000000", "amountSymbol": "USDC", "tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "source_chain": "BASE_TESTNET", "destination_chain": "ARBITRUM_TESTNET", "recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", "refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", "metadata": { "description": "Cross-chain USDC transfer", "priority": "normal" } }' ``` ```javascript theme={null} const fetch = require("node-fetch"); const url = "https://api.chainrails.io/api/v1/intents"; const apiKey = "YOUR_API_KEY"; const payload = { sender: "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54", amount: "1000000", amountSymbol: "USDC", tokenIn: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", source_chain: "BASE_TESTNET", destination_chain: "ARBITRUM_TESTNET", recipient: "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", refund_address: "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", metadata: { description: "Cross-chain USDC transfer", priority: "normal", }, }; async function createIntent() { const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify(payload), }); const data = await res.json(); console.log("Response:", data); } createIntent().catch(console.error); ``` ```php theme={null} "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54", "amount" => 1000000, "amountSymbol" => "USDC", "tokenIn" => "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "source_chain" => "BASE_TESTNET", "destination_chain" => "ARBITRUM_TESTNET", "recipient" => "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", "refund_address" => "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e", "metadata" => [ "description" => "Cross-chain USDC transfer", "priority" => "normal" ] ]; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "Authorization: Bearer $apiKey" ], CURLOPT_POSTFIELDS => json_encode($data), ]); $response = curl_exec($ch); if (curl_errno($ch)) { echo 'Error: ' . curl_error($ch); } else { echo "Response: " . $response; } curl_close($ch); ?> ``` For more details on the API, check out our [API Reference](/api-reference/introduction).