# 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 (
);
}
```
This pattern keeps your API key on the server, gives you a clear point to validate payment parameters, and lets the mobile app open the modal only when a valid session exists.
## 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.
## Next Steps
* See the [Payment Modal reference](/sdk-reference/components/payment-modal) for hook behavior and parameters
* See the [Quickstart](/quickstart) for the shared session model used across web and mobile
Check out our Github demo repository for an integration example.
# A Full Intent Lifecycle
Source: https://docs.chainrails.io/guides/payments
Implement Chainrails cross-chain payment flow from start to finish
This guide walks you through the complete payment lifecycle using Chainrails, from generating a payment intent, funding it, to confirming its success using the APIs.
## Step 1 — Request a Quote
Before creating a payment intent, you need to request for quotes to help the user understand the costs for the multiple cross-chain routes available.
* We often recommend using the multi-source quote endpoint to get quotes from multiple source chains for a given destination chain. This fetches the best quotes for multiple source chains, providing more options for the user. See [Multi-Source Quotes](/api-reference/quotes/get-quotes-from-all-source-chains-to-destination) for more details.
But you can also request a single quote for a specific source chain, bridge option etc. if you decide to. See the Api Reference for all available quote endpoints.
Some quote endpoints take in an optional `amountSymbol` parameter which can be used to specify the denomination of the amount you want to send. For quotes in USD, you can either set `amountSymbol` to USDC (or leave it empty).
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```curl theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/quotes/multi-source?destinationChain=ARBITRUM_TESTNET&amount=1.5&tokenOut=0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const fetch = require("node-fetch");
const url = new URL("https://api.chainrails.xyz/api/v1/quotes/multi-source");
url.search = new URLSearchParams({
destinationChain: "ARBITRUM_TESTNET",
amount: "1.5",
tokenOut: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
}).toString();
(async () => {
const res = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer YOUR_API_KEY`,
},
});
const data = await res.json();
console.log("Quotes from multiple sources:", data);
})();
```
```php theme={null}
"ARBITRUM_TESTNET",
"amount" => "1.5",
"tokenOut" => "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
]);
$url = "$baseUrl?$params";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $apiKey"
],
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "Response: " . $response;
}
curl_close($ch);
```
## Step 2 — Curate a Payment Intent
Once the user chooses a route (from the generated quotes), prepare a payment intent payload that defines:
* The selected route/chain
* The total amount to be sent
* The denomination of the amount (e.g. USDC, DAI, ETH etc.)
* The destination chain and recipient
This object will be used to initialize the intent on Chainrails.
```json Payment Intent theme={null}
{
"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",
"reason": "sales invoice #1234",
}
}
```
## Step 3 — Create the Payment Intent
Call the `POST /api/v1/intents` endpoint with the curated payment intent.
```curl theme={null}
curl --request POST \
--url https://api.chainrails.io/api/v1/intents \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"sender": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"amount": "1000000",
"amountSymbol": "USDC",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"metadata": {
"orderId": "12345"
}
}'
```
```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: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
amount: "1000000",
amountSymbol: "USDC",
tokenIn: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
source_chain: "BASE_TESTNET",
destination_chain: "ARBITRUM_TESTNET",
recipient: "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
refund_address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
metadata: {
orderId: "12345",
},
};
(async () => {
const res = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const data = await res.json();
console.log("Intent Created:", data);
})();
```
```php theme={null}
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"amount" => 1000000,
"amountSymbol" => "USDC",
"tokenIn" => "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"source_chain" => "BASE_TESTNET",
"destination_chain" => "ARBITRUM_TESTNET",
"recipient" => "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address" => "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"metadata" => [
"orderId" => "12345"
]
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode($payload),
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "Response: " . $response;
}
curl_close($ch);
```
#### Sample Response
```json theme={null}
{
"id": 2,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees_in_usd": "500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f400000000000000000000000000000000000000000000000000000000000003e8000000000000000000000000000000000000000000000000000000000000000300000000000000000000000075faf114eafb1bdbe2f0316df893fd58ce46aa4d",
"intent_nonce": 4267684716645197,
"intent_status": "PENDING",
"tx_hash": null,
"needs_relay": false,
"expires_at": "2025-11-11T02:31:23.000Z",
"metadata": {
"priority": "normal",
"description": "Cross-chain USDC transfer"
},
"created_at": "2025-11-11T01:31:23.390Z",
"updated_at": "2025-11-11T01:31:23.390Z"
}
```
## Step 4 — User Funds the Payment Intent
Display the intent deposit address to the user on your payment screen.
The user should send the exact `totalAmount` from their wallet on the selected source chain.
Once the funds are detected on-chain, the Chainrails protocol takes over.
## Step 5 - Automated execution
After the deposit is confirmed, Chainrails:
1. Starts the intent automatically
2. Prefills the transaction on the destination chain for the end user
3. Refunds the relayer, who provided the liquidity to prefill the cross-chain execution, or
4. Refunds the user if the intent expired without initiating.
At this stage, you do not need to take any further action — the entire bridging and execution process is handled by the protocol.
**NB:** You can however trigger the intent processing flow manually, if the indexer goes down for any reason or missed a transaction, using the `POST /api/v1/intents/{intent_address}/trigger-processing` endpoint.
## Step 6 - Track Status via Webhooks
You can subscribe to webhooks to receive real-time updates on the intent’s lifecycle, including:
* `intent_funded`
* `intent_initiated`
* `intent_completed`
* `intent_refunded`
You can find setup instructions in the [Webhook Section](./webhooks)
### Additional Tips
1. Intent addresses are like **one-off account numbers**, they can't be reused, so a new one is generated for every intent.
2. If the user under-funds the intent, the transaction will fail to start, and the user can either top up the balance of the intent address, or a refund will be processed after intent expiration.
3. If the user over-pays an intent, the excess is refunded on intent initiation.
4. API keys have a rate limit of 250 rps, contact the team if you need modifications to this.
5. 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.
6. Testnets also do not have indexing support. You must manually call
`POST /api/v1/intents/{intent_address}/trigger-processing` to process the intent.
Check out our Github demo repository for copy-paste code examples.
# Cross-chain Quotes & Routing
Source: https://docs.chainrails.io/guides/quotes
Retrieve quotes and find optimal routes for cross-chain transfers
Before initiating a cross-chain transfer or creating an intent, you can request a quote from Chainrails.
The quote engine provides comprehensive information about how a transaction will be executed — including the route, estimated fees, and destination amount.
This allows your app to show users exactly what to expect before they fund the transaction.
## Requesting Quotes
The quote engine provides comprehensive cross-chain transfer quotes from a single bridge, multiple bridges or even multiple source chains. You can retrieve:
Some quote endpoints take in an optional `amountSymbol` parameter which can be used to specify the denomination of the amount you want to send. For quotes in USD, you can either set `amountSymbol` to USDC (or leave it empty).
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
### A single quote for a specific route
```curl theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/quotes/single?tokenIn=0x036CbD53842c5426634e7929541eC2318f3dCF7e&tokenOut=0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d&sourceChain=BASE_TESTNET&destinationChain=ARBITRUM_TESTNET&amount=1000000&bridge=CCTP" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const fetch = require("node-fetch");
const url = new URL("https://api.chainrails.io/api/v1/quotes/single");
url.search = new URLSearchParams({
tokenIn: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
tokenOut: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
sourceChain: "BASE_TESTNET",
destinationChain: "ARBITRUM_TESTNET",
amount: "1000000",
bridge: "CCTP",
}).toString();
(async () => {
const res = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer YOUR_API_KEY`,
},
});
const data = await res.json();
console.log("Quote:", data);
})();
```
```php theme={null}
"0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut" => "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"sourceChain" => "BASE_TESTNET",
"destinationChain" => "ARBITRUM_TESTNET",
"amount" => "1000000",
"bridge" => "CCTP",
]);
$url = "$baseUrl?$params";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $apiKey"
],
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "Response: " . $response;
}
curl_close($ch);
```
### Or a multi-source quote for a given destination chain
Useful for when you want to show users all source options and their respective fees to send funds to a specific destination chain.
```curl theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/quotes/multi-source?destinationChain=ARBITRUM_TESTNET&amount=1.5&tokenOut=0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const fetch = require("node-fetch");
const url = new URL("https://api.chainrails.xyz/api/v1/quotes/multi-source");
url.search = new URLSearchParams({
destinationChain: "ARBITRUM_TESTNET",
amount: "1.5",
tokenOut: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
}).toString();
(async () => {
const res = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bearer YOUR_API_KEY`,
},
});
const data = await res.json();
console.log("Quotes from multiple sources:", data);
})();
```
```php theme={null}
"ARBITRUM_TESTNET",
"amount" => "1.5",
"tokenOut" => "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
]);
$url = "$baseUrl?$params";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $apiKey"
],
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
} else {
echo "Response: " . $response;
}
curl_close($ch);
```
You can also get quotes from multiple bridges for a specific route, filter for best quotes and more. See the [API reference](../api-reference/introduction) for all available quote endpoints.
For most cases, you would want to use the multi-source quoting as it shows the user all the best quotes to choose from.
***
## The Routing Engine
The Routing Engine provides extensive details about supported bridges, their available routes, and the optimal route for a given transfer intent. For most use cases, the quote engine is sufficient but if you want more fine grained control over bridge selection, you can use the routing engine directly.
You can consult the [API reference](../api-reference/introduction) for all available routing endpoints.
## Parameters Reference
| Parameter | Type | Required | Description | Example |
| -------------------- | -------- | ------------------------------ | -------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| **tokenIn** | `string` | ✅ Yes *(for `/quotes/single`)* | Address of the input token on the source chain. This is the token the user will send. | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` |
| **tokenOut** | `string` | ✅ Yes | Address of the output token on the destination chain. | `0x06ef8BFf21a47c8E15944D1f4A68F9F95f66A34` |
| **sourceChain** | `string` | ✅ Yes *(for `/quotes/single`)* | The blockchain where the user is sending funds **from**. Must be one of the supported chain identifiers. | `BASE_TESTNET` |
| **destinationChain** | `string` | ✅ Yes | The blockchain where the funds should arrive. Must be one of the supported chain identifiers. | `ARBITRUM_TESTNET` |
| **amount** | `string` | ✅ Yes | Amount to transfer, in token units. Supports decimals. | `"1.5"` |
| **bridge** | `string` | ✅ Yes *(for `/quotes/single`)* | The specific bridge protocol to use for the quote. | `ACROSS` |
| **recipient** | `string` | ❌ Optional | Address of the final recipient of the transfer. | `0xb79541Be080a59fdcE6C0b43219ba56c725eC65e` |
# Complete Ramping Guide
Source: https://docs.chainrails.io/guides/ramping
Build fiat on-ramp and off-ramp flows with Chainrails, including headless KYC and hosted provider widgets
This guide walks through a complete Chainrails ramp integration: discovering supported corridors, requesting quotes, completing KYC when required, creating an order, presenting payment instructions or a hosted widget, and monitoring the order until completion.
## Overview
Chainrails aggregates fiat ramp providers behind one API. A user can on-ramp fiat into USDC on a supported destination chain, or off-ramp supported tokens from a source chain into local fiat.
There are two execution flows:
| Flow | How to identify it | KYC owner | User experience |
| --------------- | ----------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------- |
| Headless/direct | The selected quote's payment channel has `transferType: "direct"` | Chainrails | You collect the required fields, complete Chainrails KYC, and show payment or deposit instructions in your interface. |
| Widget/redirect | The selected quote's payment channel has `transferType: "widget"` | Ramp provider | Create the order, redirect the user to `widgetUrl`, and let the provider collect KYC and payment details. |
For headless providers, Chainrails has been built to minimize KYC friction. You only need to KYC once per user to access multiple liquidity providers, and you can submit only the fields that are missing or insufficient for each selected provider.
## Before you begin
You need:
* a Chainrails account;
* a test or live API key from the Chainrails dashboard;
* completed Chainrails KYB to access live fiat endpoints;
All examples use:
```text theme={null}
Base URL: https://api.chainrails.io
Authorization: Bearer YOUR_API_KEY
```
Keep API keys on your server. Do not expose them in browser or mobile application code.
## End-to-end flow
The integration sequence is:
1. Retrieve supported countries for the requested direction and amount.
2. Request quotes using the selected country and currency.
3. Select a quote and inspect its `transferType` and `fieldsRequired`.
4. For a headless quote, complete the Chainrails KYC loop.
5. Create the ramp order using the selected provider.
6. Show `transferInstructions` for a headless order or open `widgetUrl` for a hosted order.
7. Poll the order until it reaches a terminal status.
## 1. Retrieve supported countries
Use the countries endpoint to build your country and currency selector:
```http theme={null}
GET /api/v1/ramp/countries
```
Recommended query parameters:
| Parameter | Required | Description |
| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------- |
| `type` | Recommended | `on-ramp` or `off-ramp`. Off-ramp returns only countries with direct off-ramp support. |
| `amount` | Recommended | Intended crypto amount in USD/USDC terms. Filters out currencies whose configured minimum exceeds the amount. |
| `currency` | No | ISO 4217 currency filter such as `NGN` or `XOF`. |
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/countries?type=on-ramp&amount=25" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch(
"https://api.chainrails.io/api/v1/ramp/countries?type=on-ramp&amount=25",
{ headers: { Authorization: "Bearer YOUR_API_KEY" } },
);
const countries = await response.json();
```
```php theme={null}
true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"],
]);
$countries = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Example response:
```json theme={null}
[
{
"countryCode": "NG",
"name": "Nigeria",
"currency": {
"code": "NGN",
"name": "Nigerian Naira",
"symbol": "₦",
"minAmount": 1,
"providers": ["YELLOW_CARD", "FONBNK", "ONRAMP_MONEY"]
}
}
]
```
Use the countries endpoint instead of deriving a country from a currency. Multiple countries can share a currency, while provider availability and KYC requirements can differ by country.
You can also inspect currencies directly:
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/currencies?type=on-ramp" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch(
"https://api.chainrails.io/api/v1/ramp/currencies?type=on-ramp",
{ headers: { Authorization: "Bearer YOUR_API_KEY" } },
);
const currencies = await response.json();
```
```php theme={null}
true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"],
]);
$currencies = json_decode(curl_exec($curl), true);
curl_close($curl);
```
## 2. Request quotes
```http theme={null}
GET /api/v1/ramp/quotes
```
### On-ramp quote
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/quotes?type=on-ramp&fiatCurrency=NGN&cryptoAmount=25&destinationChain=BASE_MAINNET&countryCode=NG&userEmail=user@example.com" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const params = new URLSearchParams({
type: "on-ramp", fiatCurrency: "NGN", cryptoAmount: "25",
destinationChain: "BASE_MAINNET", countryCode: "NG",
userEmail: "user@example.com",
});
const response = await fetch(`https://api.chainrails.io/api/v1/ramp/quotes?${params}`, {
headers: { Authorization: "Bearer YOUR_API_KEY" },
});
const quotes = await response.json();
```
```php theme={null}
"on-ramp", "fiatCurrency" => "NGN", "cryptoAmount" => 25,
"destinationChain" => "BASE_MAINNET", "countryCode" => "NG",
"userEmail" => "user@example.com",
]);
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/quotes?$query");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$quotes = json_decode(curl_exec($curl), true);
curl_close($curl);
```
### Off-ramp quote
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/quotes?type=off-ramp&fiatCurrency=NGN&cryptoAmount=25&sourceChain=BASE_MAINNET&amountSymbol=USDC&countryCode=NG&userEmail=user@example.com" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const params = new URLSearchParams({
type: "off-ramp", fiatCurrency: "NGN", cryptoAmount: "25",
sourceChain: "BASE_MAINNET", amountSymbol: "USDC", countryCode: "NG",
userEmail: "user@example.com",
});
const response = await fetch(`https://api.chainrails.io/api/v1/ramp/quotes?${params}`, {
headers: { Authorization: "Bearer YOUR_API_KEY" },
});
const quotes = await response.json();
```
```php theme={null}
"off-ramp", "fiatCurrency" => "NGN", "cryptoAmount" => 25,
"sourceChain" => "BASE_MAINNET", "amountSymbol" => "USDC",
"countryCode" => "NG", "userEmail" => "user@example.com",
]);
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/quotes?$query");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$quotes = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Quote parameters:
| Parameter | On-ramp | Off-ramp | Description |
| ------------------ | ----------- | ----------- | ------------------------------------------------------------------------------------------- |
| `type` | Required | Required | `on-ramp` or `off-ramp`. |
| `fiatCurrency` | Required | Required | ISO 4217 fiat currency. |
| `cryptoAmount` | Required | Required | Amount the user receives for on-ramp or sells for off-ramp. |
| `destinationChain` | Required | — | Final chain for on-ramped USDC. |
| `sourceChain` | — | Required | Chain where the off-ramp asset is held. |
| `amountSymbol` | — | Optional | Token represented by `cryptoAmount`; defaults to `USDC`. |
| `countryCode` | Recommended | Recommended | Transaction corridor country. Required for shared currencies such as XOF, EUR. |
| `userEmail` | Recommended | Recommended | Allows recommendations to filter for provider with least KYC friction for the user profile. |
| `directOnly` | Optional | Optional | Set to `true` to exclude widget/redirect quotes. |
An abbreviated quote response looks like this:
```json theme={null}
{
"recommended": {
"provider": "YELLOW_CARD",
"fiatCurrency": "NGN",
"fiatAmount": 35000,
"cryptoCurrency": "USDC",
"cryptoAmount": 25,
"totalFeesUsd": 0.25,
"paymentChannels": [
{
"channel": "bank_transfer",
"transferType": "direct",
"directTransferDetails": {
"fieldsRequired": [
{
"key": "accountNumber",
"label": "Bank account number",
"type": "string",
"required": false
}
]
}
}
]
},
"quotes": [
{
"provider": "YELLOW_CARD",
"fiatCurrency": "NGN",
"fiatAmount": 35000,
"cryptoCurrency": "USDC",
"cryptoAmount": 25,
"totalFeesUsd": 0.25,
"paymentChannels": [
{
"channel": "bank_transfer",
"transferType": "direct",
"directTransferDetails": {
"fieldsRequired": [
{
"key": "accountNumber",
"label": "Bank account number",
"type": "string",
"required": false
}
]
}
}
]
}
],
"providersQueried": 3
}
```
The real response includes the full quote list. The chosen `recommended` quote creates a balance between price, remaining KYC friction, pending or blocked KYC state, and direct-flow availability.
## 3. Determine whether KYC is required
Inspect the selected quote's payment channel:
```json theme={null}
{
"transferType": "direct"
}
```
For a direct/headless quote, check Chainrails KYC before creating the order.
For the underlying profile model, assurance levels, and verification states, see [Know Your Customer (KYC)](/essentials/kyc).
```json theme={null}
{
"transferType": "widget"
}
```
For a widget quote, skip the Chainrails KYC endpoints. Create the order and redirect the user to the returned `widgetUrl`; the provider owns the verification flow.
### Inspect provider requirements
This endpoint describes the applicable policy without inspecting a user:
```http theme={null}
GET /api/v1/ramp/kyc/requirements
```
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/kyc/requirements?provider=YELLOW_CARD&countryCode=NG&fiatCurrency=NGN" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const params = new URLSearchParams({ provider: "YELLOW_CARD", countryCode: "NG", fiatCurrency: "NGN" });
const response = await fetch(`https://api.chainrails.io/api/v1/ramp/kyc/requirements?${params}`, {
headers: { Authorization: "Bearer YOUR_API_KEY" },
});
const requirements = await response.json();
```
```php theme={null}
"YELLOW_CARD", "countryCode" => "NG", "fiatCurrency" => "NGN"]);
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/kyc/requirements?$query");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$requirements = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Example response:
```json theme={null}
{
"provider": "YELLOW_CARD",
"requiredFields": [
{ "key": "email", "assurance": "provided" },
{ "key": "first_name", "assurance": "verified" },
{ "key": "last_name", "assurance": "verified" },
{ "key": "phone", "assurance": "provided" },
{ "key": "country", "assurance": "provided" },
{ "key": "address", "assurance": "provided" },
{ "key": "date_of_birth", "assurance": "verified" },
{ "key": "nin", "assurance": "verified" },
{ "key": "bvn", "assurance": "verified" }
],
"requiredCapabilities": [],
"validationMethods": ["text", "external"],
"textDocuments": ["bvn", "nin"],
"maxTransactionAmountUsd": null
}
```
`assurance: "provided"` means Chainrails needs a stored value. `assurance: "verified"` means the field must be validated by an accepted verification source.
### Get the user's KYC state
```http theme={null}
GET /api/v1/ramp/kyc
```
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/kyc?provider=YELLOW_CARD&countryCode=NG&fiatCurrency=NGN&userEmail=user@example.com&cryptoAmount=25" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const params = new URLSearchParams({
provider: "YELLOW_CARD", countryCode: "NG", fiatCurrency: "NGN",
userEmail: "user@example.com", cryptoAmount: "25",
});
const response = await fetch(`https://api.chainrails.io/api/v1/ramp/kyc?${params}`, {
headers: { Authorization: "Bearer YOUR_API_KEY" },
});
const state = await response.json();
```
```php theme={null}
"YELLOW_CARD", "countryCode" => "NG", "fiatCurrency" => "NGN", "userEmail" => "user@example.com", "cryptoAmount" => 25]);
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/kyc?$query");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$state = json_decode(curl_exec($curl), true);
curl_close($curl);
```
The state response separates requirements into actionable groups:
| Property | Meaning |
| -------------------------- | --------------------------------------------------------------------------------- |
| `missingRequirements` | No value or verification exists yet. |
| `insufficientRequirements` | A value exists, but its assurance is lower than the policy requires. |
| `pendingRequirements` | Verification is still processing. |
| `rejectedRequirements` | The latest verification was rejected. Correct the relevant input before retrying. |
| `blockedRequirements` | Manual review is required. Normal submission cannot resolve the state. |
| `satisfiedRequirements` | Field requirements already fulfilled. |
| `requiredCapabilities` | Verification capabilities still required. |
| `satisfiedCapabilities` | Completed capabilities, such as `external_verification`. |
Continue directly to order creation when:
```json theme={null}
{
"canProceed": true,
"blocked": false
}
```
When `blocked` is `true`, show a message asking the user to contact support. Do not repeatedly resubmit the same identity data.
## 4. Complete headless KYC
KYC submission uses one endpoint for profile creation, field storage, text-document checks, and hosted external verification:
```http theme={null}
POST /api/v1/ramp/kyc
```
Only `userEmail`, `provider`, `countryCode`, and `fiatCurrency` are required. Include any user information you already have/can obtain in `fields` (derived from checking provider's requirements); the engine determines what can be stored, validated, or sent to an external verification flow.
`countryCode` is the transaction corridor country. `fields.country` is the user's current country of residence. They are intentionally separate and do not always need to match.
### Text verification flow
The text verification flow provides the least friction. Currently available for just Nigeria, but will be expanded to more countries in the future. Submit the available profile fields and required text documents:
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/kyc" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"userEmail": "user@example.com",
"provider": "YELLOW_CARD",
"countryCode": "NG",
"fiatCurrency": "NGN",
"cryptoAmount": 25,
"fields": {
"first_name": "Ada",
"last_name": "Okafor",
"phone": "+2348012345678",
"date_of_birth": "1994-06-15",
"country": "NG",
"address": "12 Example Street, Lagos",
"BVN": "12345678901",
"NIN": "98765432109"
}
}'
```
```javascript theme={null}
const payload = {
userEmail: "user@example.com", provider: "YELLOW_CARD", countryCode: "NG",
fiatCurrency: "NGN", cryptoAmount: 25,
fields: {
first_name: "Ada", last_name: "Okafor", phone: "+2348012345678",
date_of_birth: "1994-06-15", country: "NG", address: "12 Example Street, Lagos",
BVN: "12345678901", NIN: "98765432109",
},
};
const response = await fetch("https://api.chainrails.io/api/v1/ramp/kyc", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const result = await response.json();
```
```php theme={null}
"user@example.com", "provider" => "YELLOW_CARD",
"countryCode" => "NG", "fiatCurrency" => "NGN", "cryptoAmount" => 25,
"fields" => ["first_name" => "Ada", "last_name" => "Okafor", "phone" => "+2348012345678", "date_of_birth" => "1994-06-15", "country" => "NG", "address" => "12 Example Street, Lagos", "BVN" => "12345678901", "NIN" => "98765432109"],
];
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/kyc");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($payload)]);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Use uppercase `BVN` and `NIN` in the public submission payload. Both values must contain exactly 11 digits.
Chainrails validates the documents and compares the returned identity against the submitted names and DOB. Phone and address are mutable fields and do not need an exact registry match.
### External document and biometric verification
Outside Nigeria, Chainrails requires the `external_verification` capability. You can start with only the fields you already have:
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/kyc" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"userEmail": "user@example.com",
"provider": "YELLOW_CARD",
"countryCode": "KE",
"fiatCurrency": "KES",
"cryptoAmount": 25,
"callbackUrl": "https://app.example.com/kyc/complete",
"fields": {
"country": "KE",
"address": "1 Example Road, Nairobi"
}
}'
```
```javascript theme={null}
const payload = {
userEmail: "user@example.com", provider: "YELLOW_CARD", countryCode: "KE",
fiatCurrency: "KES", cryptoAmount: 25,
callbackUrl: "https://app.example.com/kyc/complete",
fields: { country: "KE", address: "1 Example Road, Nairobi" },
};
const response = await fetch("https://api.chainrails.io/api/v1/ramp/kyc", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const result = await response.json();
```
```php theme={null}
"user@example.com", "provider" => "YELLOW_CARD",
"countryCode" => "KE", "fiatCurrency" => "KES", "cryptoAmount" => 25,
"callbackUrl" => "https://app.example.com/kyc/complete",
"fields" => ["country" => "KE", "address" => "1 Example Road, Nairobi"],
];
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/kyc");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($payload)]);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
```
When external verification is required, the response includes:
```json theme={null}
{
"profileId": "profile-id",
"fields": [],
"state": {
"canProceed": false,
"requiredCapabilities": ["external_verification"]
},
"verification": {
"method": "external",
"sessionId": "session-id",
"url": "https://verify.didit.me/session/example",
"status": "not_started"
}
}
```
Open `verification.url` in the same tab, a new tab, or an embedded browser appropriate for your application. `callbackUrl` controls where the hosted flow returns the user.
Chainrails receives the provider webhook asynchronously. Returning to `callbackUrl` does not by itself mean KYC is approved. Poll `GET /api/v1/ramp/kyc` until one of these outcomes occurs:
* `canProceed: true` — continue to order creation;
* `pendingRequirements` is non-empty — keep waiting and poll again;
* `blocked: true` — stop and direct the user to support;
* missing or insufficient fields remain — collect and submit only those fields.
### Progressive KYC loop
Do not render one large static form. Build the next form from the latest state:
1. Read `missingRequirements`, `rejectedRequirements`, and `insufficientRequirements`.
2. Ask only for those field requirements, dependent on what the provider needs.
3. Submit the fields to `/api/v1/ramp/kyc` with the same provider and corridor context.
4. If a verification URL is returned, send the user through it.
5. Poll `/api/v1/ramp/kyc`.
6. Continue when `canProceed` is true.
The profile is keyed by normalized email and reused across future transactions. Email ownership verification is the responsibility of your application; the KYC API does not send or validate an email OTP.
## 5. Create the ramp order
```http theme={null}
POST /api/v1/ramp/orders
```
The provider must come from the selected quote. Chainrails fetches a fresh quote during order creation, so you do not pass the previous `quoteId`.
### Headless on-ramp order
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/orders" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"type": "on-ramp",
"provider": "YELLOW_CARD",
"fiatCurrency": "NGN",
"cryptoAmount": 25,
"destinationChain": "BASE_MAINNET",
"recipientAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"countryCode": "NG",
"userEmail": "user@example.com",
"fields": {
"accountNumber": "0123456789"
}
}'
```
```javascript theme={null}
const payload = {
type: "on-ramp", provider: "YELLOW_CARD", fiatCurrency: "NGN", cryptoAmount: 25,
destinationChain: "BASE_MAINNET",
recipientAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
countryCode: "NG", userEmail: "user@example.com",
fields: { accountNumber: "0123456789" },
};
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const order = await response.json();
```
```php theme={null}
"on-ramp", "provider" => "YELLOW_CARD", "fiatCurrency" => "NGN", "cryptoAmount" => 25,
"destinationChain" => "BASE_MAINNET", "recipientAddress" => "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"countryCode" => "NG", "userEmail" => "user@example.com", "fields" => ["accountNumber" => "0123456789"],
];
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/orders");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($payload)]);
$order = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Only include keys requested by the selected quote's `fieldsRequired`. A field with `required: false` can be omitted.
Example headless response:
```json theme={null}
{
"id": 475,
"direction": "ON_RAMP",
"status": "ORDER_INITIATED",
"provider": "YELLOW_CARD",
"providerOrderId": "provider-order-id",
"fiatCurrency": "NGN",
"fiatAmount": 35000,
"cryptoCurrency": "USDC",
"cryptoAmount": 25,
"paymentChannel": "bank_transfer",
"transferInstructions": {
"type": "bank_transfer",
"bankName": "Example Bank",
"accountName": "Example Account",
"accountNumber": "0123456789",
"reference": "ABC123"
},
"widgetUrl": null,
"expiresAt": "2026-08-12T01:30:00.000Z",
"destinationChain": "BASE_MAINNET",
"recipientAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
}
```
Show the transfer instructions and expiry to the user. The user should send the exact fiat amount and include the reference when one is provided.
### Widget on-ramp order
For a quote with `transferType: "widget"`, do not call the Chainrails KYC endpoints first:
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/orders" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"type": "on-ramp",
"provider": "FONBNK",
"fiatCurrency": "NGN",
"cryptoAmount": 25,
"destinationChain": "BASE_MAINNET",
"recipientAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"countryCode": "NG"
}'
```
```javascript theme={null}
const payload = {
type: "on-ramp", provider: "FONBNK", fiatCurrency: "NGN", cryptoAmount: 25,
destinationChain: "BASE_MAINNET", recipientAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
countryCode: "NG",
};
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const order = await response.json();
```
```php theme={null}
"on-ramp", "provider" => "FONBNK", "fiatCurrency" => "NGN", "cryptoAmount" => 25, "destinationChain" => "BASE_MAINNET", "recipientAddress" => "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", "countryCode" => "NG"];
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/orders");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($payload)]);
$order = json_decode(curl_exec($curl), true);
curl_close($curl);
```
The response contains a hosted URL:
```json theme={null}
{
"id": 476,
"status": "ORDER_INITIATED",
"provider": "FONBNK",
"transferInstructions": null,
"widgetUrl": "https://provider.example/checkout/..."
}
```
Redirect the user to `widgetUrl`. The provider collects its own KYC and payment information there. Do not send Chainrails KYC documents through the order `fields` object.
### Headless off-ramp order
Off-ramp quotes expose payout fields and, where applicable, selectable `networkId` options. Use the option values exactly as returned by the quote.
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/orders" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"type": "off-ramp",
"provider": "YELLOW_CARD",
"fiatCurrency": "NGN",
"cryptoAmount": 25,
"sourceChain": "BASE_MAINNET",
"amountSymbol": "USDC",
"senderAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"countryCode": "NG",
"userEmail": "user@example.com",
"fields": {
"accountNumber": "0123456789",
"accountName": "Ada Okafor",
"networkId": "NETWORK_ID_FROM_QUOTE"
}
}'
```
```javascript theme={null}
const payload = {
type: "off-ramp", provider: "YELLOW_CARD", fiatCurrency: "NGN", cryptoAmount: 25,
sourceChain: "BASE_MAINNET", amountSymbol: "USDC",
senderAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
countryCode: "NG", userEmail: "user@example.com",
fields: { accountNumber: "0123456789", accountName: "Ada Okafor", networkId: "NETWORK_ID_FROM_QUOTE" },
};
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const order = await response.json();
```
```php theme={null}
"off-ramp", "provider" => "YELLOW_CARD", "fiatCurrency" => "NGN", "cryptoAmount" => 25, "sourceChain" => "BASE_MAINNET", "amountSymbol" => "USDC", "senderAddress" => "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", "countryCode" => "NG", "userEmail" => "user@example.com", "fields" => ["accountNumber" => "0123456789", "accountName" => "Ada Okafor", "networkId" => "NETWORK_ID_FROM_QUOTE"]];
$curl = curl_init("https://api.chainrails.io/api/v1/ramp/orders");
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($payload)]);
$order = json_decode(curl_exec($curl), true);
curl_close($curl);
```
The response tells the user how to fund the Chainrails intent:
```json theme={null}
{
"id": 477,
"direction": "OFF_RAMP",
"status": "ORDER_INITIATED",
"provider": "YELLOW_CARD",
"providerOrderId": "provider-order-id",
"fiatCurrency": "NGN",
"cryptoCurrency": "USDC",
"paymentChannel": "bank_transfer",
"transferInstructions": {
"type": "intent_deposit",
"instructionsText": "Send exactly 25.25 USDC to the intent address below on BASE_MAINNET",
"transferDetails": [
{
"id": "depositAddress",
"label": "Intent deposit address",
"value": "0xIntentAddress"
},
{
"id": "amountToSend",
"label": "Amount to send",
"value": "25.25"
}
]
},
"widgetUrl": null
}
```
The user must send the exact token and amount to the returned intent address on the specified source chain. Chainrails then routes the funds and coordinates fiat payout.
## 6. Handle KYC order errors
Order creation revalidates KYC against the selected provider. This protects against stale frontend state.
If KYC is incomplete, the order endpoint returns a `400` response with:
```json theme={null}
{
"code": "KYC_REQUIRED",
"message": "Additional KYC information is required",
"profileId": "profile-id",
"blocked": false,
"missingRequirements": [],
"pendingRequirements": [],
"rejectedRequirements": [],
"insufficientRequirements": [],
"requiredCapabilities": ["external_verification"]
}
```
Return to the KYC state and submission loop, then retry order creation.
If the response code is `KYC_BLOCKED`, stop automatic retries and ask the user to contact support.
## 7. Monitor the order
### Get one order
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/orders/475" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders/475", { headers: { Authorization: "Bearer YOUR_API_KEY" } });
const order = await response.json();
```
```php theme={null}
true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$order = json_decode(curl_exec($curl), true);
curl_close($curl);
```
### Get an on-ramp order by intent address
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/orders/by-intent/0xIntentAddress" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders/by-intent/0xIntentAddress", { headers: { Authorization: "Bearer YOUR_API_KEY" } });
const order = await response.json();
```
```php theme={null}
true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$order = json_decode(curl_exec($curl), true);
curl_close($curl);
```
### List orders
```bash theme={null}
curl --request GET \
--url "https://api.chainrails.io/api/v1/ramp/orders?type=on-ramp" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders?type=on-ramp", { headers: { Authorization: "Bearer YOUR_API_KEY" } });
const orders = await response.json();
```
```php theme={null}
true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$orders = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Order statuses progress forward:
| Status | Meaning |
| -------------------- | ------------------------------------------------------------------------- |
| `ORDER_INITIATED` | The order exists and is waiting for the user's payment or deposit. |
| `DEPOSIT_SUCCESSFUL` | The provider recognized the user's initial deposit. |
| `PAYMENT_RECEIVED` | Crypto reached the Chainrails intent or the provider payout was received. |
| `COMPLETED` | Funds reached the final destination. |
| `PAYMENT_FAILED` | Provider processing failed. |
| `PAYMENT_EXPIRED` | The payment window expired. |
| `CANCELLED` | The order was cancelled before completion. |
Poll every few seconds or subscribe to the ramp order webhooks to receive status updates.
## Optional order actions
### Cancel an order
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/orders/475/cancel" \
--header "Authorization: Bearer YOUR_API_KEY"
```
```javascript theme={null}
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders/475/cancel", { method: "POST", headers: { Authorization: "Bearer YOUR_API_KEY" } });
const result = await response.json();
```
```php theme={null}
true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY"]]);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Cancellation succeeds only while the provider and Chainrails order state remain cancellable.
### Confirm an order
Some provider flows can require explicit confirmation after the user completes a deposit action:
```bash theme={null}
curl --request POST \
--url "https://api.chainrails.io/api/v1/ramp/orders/475/confirm" \
--header "Authorization: Bearer YOUR_API_KEY" \
--header "Content-Type: application/json" \
--data '{ "fields": {} }'
```
```javascript theme={null}
const response = await fetch("https://api.chainrails.io/api/v1/ramp/orders/475/confirm", {
method: "POST",
headers: { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" },
body: JSON.stringify({ fields: {} }),
});
const result = await response.json();
```
```php theme={null}
true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => ["Authorization: Bearer YOUR_API_KEY", "Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode(["fields" => []])]);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
```
Do not call this endpoint automatically for every order. Most headless orders progress through payment/deposit instructions and webhook-driven status updates without a routine client confirmation call.
## Implementation checklist
* Use `/ramp/countries` with `type` and `amount` to build corridor selection.
* Request quotes with `countryCode` and `userEmail`.
* Select the provider from the quote response rather than hardcoding one.
* Inspect `transferType` to choose the headless or widget flow.
* For headless ramp flows, poll `/ramp/kyc` and submit only outstanding requirements.
* Treat `countryCode` as transaction geography and `fields.country` as residence.
* Redirect users through `verification.url` when external verification is required.
* Wait for `canProceed: true` before creating a headless order.
* Send only quote-defined payment fields in the order `fields` object.
* For widget flows, redirect to `widgetUrl` and let the provider own KYC.
* Display exact transfer instructions and expiry values from the order response.
* Poll the order until a terminal status is reached.
## Using the Chainrails Modal
If you do not need a custom interface, the easiest way to get started is the Chainrails Modal, which implements country and currency selection, quote retrieval, progressive KYC, hosted verification redirects, order creation, and status monitoring for you.
See the [Payment Modal documentation](/sdk-reference/components/payment-modal) for setup instructions.
# Seeker Mobile Guide
Source: https://docs.chainrails.io/guides/seeker-mobile-guide
Integrate Chainrails into a React Native app for Solana Seeker devices
Chainrails offers a React Native SDK for integrating payments into Solana Seeker mobile apps, with built-in access to the Seeker dApp wallet, the Seeker theme, and features designed specifically for Seeker devices.
This guide walks you through the complete end-to-end setup to get Chainrails payments working in your Solana Seeker mobile app.
## Overview
This guide uses `@chainrails/react-native` on the app side for the payment modal and hooks, and `@chainrails/sdk` on your backend to create session tokens. For the broader React Native integration, see [Mobile Development](./mobile-development).
## 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
## 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
```
## Step 2: Set Up Session Endpoint
Create a backend endpoint that generates secure session tokens. The mobile app calls 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 `recipient`, `destinationChain`, `token`, and `amount` before creating a session. For a Seeker-targeted flow, the destination chain is typically `SOLANA`.
## Step 3: Open 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 { useCallback, useState } from "react";
import { Button, SafeAreaView, StatusBar, StyleSheet, Text, View } from "react-native";
import { PaymentModal, usePaymentModal } from "@chainrails/react-native";
export default function App() {
const [status, setStatus] = useState("Ready");
const cr = usePaymentModal({
sessionToken: null,
onCancel: () => setStatus("Payment cancelled"),
onSuccess: (result) =>
setStatus(result?.transactionHash ? `Payment successful — ${result.transactionHash}` : "Payment successful"),
});
const pay = useCallback(async () => {
setStatus("Creating session…");
try {
const res = await fetch("https://your-server.com/create-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
amount: "10",
recipient: "YourSolanaWalletAddress",
destinationChain: "SOLANA",
token: "USDC",
}),
});
if (!res.ok) throw new Error("Could not create payment session");
const data = await res.json();
cr.updateSession({ sessionToken: data.sessionToken, amount: data.amount });
setStatus("Session ready — opening payment modal");
cr.open();
} catch (err) {
setStatus("an error occured");
}
}, [cr]);
return (
Pay with Chainrails{status}
);
}
const styles = StyleSheet.create({
root: { flex: 1, backgroundColor: "#111", padding: 20, gap: 16 },
title: { color: "#fff", fontSize: 22, fontWeight: "700" },
actions: { gap: 10 },
status: { color: "#9ad", fontSize: 12 },
});
```
Run it with:
```bash theme={null}
npx expo run:android
```
## 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.
## Next Steps
* See the [Mobile Development guide](./mobile-development) for the broader React Native integration details
* See the [Payment Modal reference](/sdk-reference/components/payment-modal) for hook behaviour and parameters
Check out our Github demo repository for a full React Native example.
# Webhooks
Source: https://docs.chainrails.io/guides/webhooks
Instant notifications about events in your application
## Overview
Chainrails webhooks allow you to receive real-time notifications for both cross-chain intents and ramp orders. Instead of polling the API for status updates, webhooks push event data to your server when significant state changes occur.
## Quick Start
### 1. Create a Webhook
You'd rarely need to do this manually, as you can create webhooks directly from the [Dashboard](https://dashboard.chainrails.io/webhooks). But if you want to create one programmatically, here's how:
```bash theme={null}
curl -X POST https://api.chainrails.io/api/v1/client/webhooks \
-H "Authorization: Bearer CLIENT_JWT_AUTH" \
-H "Content-Type: application/json" \
-d '{
"url": "https://api.example.com/webhooks/chainrails",
"events": [
"intent.funded",
"intent.completed",
"ramp.order.initiated",
"ramp.order.completed"
],
"environment": "live",
"is_active": true
}'
```
**Response:**
```json theme={null}
{
"webhook_id": "wh_abc123...",
"client_id": "client_xyz...",
"url": "https://api.example.com/webhooks/chainrails",
"events": [
"intent.funded",
"intent.completed",
"ramp.order.initiated",
"ramp.order.completed"
],
"is_active": true,
"environment": "live",
"secret": "whsec_1234567890abcdef...",
"created_at": "2025-12-07T10:00:00Z",
"updated_at": "2025-12-07T10:00:00Z"
}
```
**⚠️ Important:** Save the `secret` value - it's only returned once when creating or regenerating the webhook. You'll need it to verify webhook signatures.
### 2. Implement Your Webhook Endpoint
Your webhook endpoint must:
* Accept `POST` requests
* Respond with `200 OK` within 5 seconds
* Verify the signature (instructions below)
* Be publicly accessible (HTTPS required for live webhooks)
For local testing, you can use tools like [ngrok](https://ngrok.com) to expose your local server to the internet.
***
## Event Types
Subscribe to the events relevant to your use case:
### Intent Events
| Event Type | Description | When It's Triggered |
| ------------------ | ------------------------------- | ------------------------------------------------ |
| `intent.created` | Intent was created | When a new intent is created |
| `intent.funded` | User funded the intent address | When tokens are detected on the intent address |
| `intent.initiated` | Bridge transaction started | When Chainrails initiates the bridge transaction |
| `intent.completed` | Transfer successfully completed | When tokens arrive on destination chain |
| `intent.expired` | Intent expired without funding | When intent funding deadline passes |
| `intent.refunded` | Funds returned to sender | When transfer fails and funds are refunded |
### Ramp Order Events
| Event Type | Description | When It's Triggered |
| ---------------------- | ---------------------- | ---------------------------------------------- |
| `ramp.order.initiated` | Ramp order started | When a ramp order is initiated with a provider |
| `ramp.order.funded` | User funding confirmed | When payment is received for the ramp order |
| `ramp.order.completed` | Ramp order completed | When the ramp flow settles successfully |
| `ramp.order.failed` | Ramp order failed | When the provider reports payment failure |
| `ramp.order.expired` | Ramp order expired | When the ramp payment window expires |
| `ramp.order.cancelled` | Ramp order cancelled | When the order is cancelled before completion |
Ramp webhooks expose a provider-agnostic lifecycle. Provider-specific intermediate statuses are normalized into the event set above.
***
## Webhook Payload Structure
All webhook events follow this structure:
```typescript theme={null}
{
"id": "evt_1234567890abcdef",
"type": "intent.completed",
"created_at": "2025-12-07T10:30:00Z",
"data": {
"intent_id": 12345,
"intent_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"source_chain": "ARBITRUM_MAINNET",
"destination_chain": "BASE_MAINNET",
"status": "COMPLETED",
"tx_hash": "0xabc123...",
"sender": "0x1234...",
"recipient": "0x5678...",
"amount": "1000000",
"token_in": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
"token_out": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"metadata": {
"custom_field": "value"
}
},
"previous_attributes": {
"status": "INITIATED"
}
}
```
### Ramp Event Example
Ramp events follow the same top-level shape, but with ramp order fields in `data`:
```typescript theme={null}
{
"id": "evt_1234567890abcdef",
"type": "ramp.order.completed",
"created_at": "2025-12-07T10:30:00Z",
"data": {
"ramp_order_id": 987,
"order_ref": "cr_ramp_01JABC...",
"ramp_direction": "on-ramp",
"ramp_status": "COMPLETED",
"fiat_currency": "NGN",
"fiat_amount": "15000",
"crypto_amount": "10",
"crypto_currency": "USDC",
"payment_channel": "bank_transfer",
"ramp_provider": "FONBNK",
"intent_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
}
}
```
### Field Descriptions
* **`id`**: Unique identifier for this webhook event (idempotency key)
* **`type`**: One of the [event types](#event-types)
* **`created_at`**: When the event occurred (UTC, ISO 8601)
* **`data`**: Event-specific payload (intent fields for intent events, ramp fields for ramp events)
* **`previous_attributes`**: What changed (only for update events)
### Ramp Data Fields
* **`ramp_order_id`**: Internal ramp order ID
* **`order_ref`**: Client-facing order reference
* **`ramp_direction`**: `on-ramp` or `off-ramp`
* **`ramp_status`**: Current normalized ramp status
* **`fiat_currency`**: Fiat currency code (ISO 4217)
* **`fiat_amount`**: Fiat amount for the order
* **`crypto_amount`**: Crypto amount involved in the order
* **`crypto_currency`**: Crypto asset symbol (for example `USDC`)
* **`payment_channel`**: Payment channel used by the provider
* **`ramp_provider`**: Provider handling the order
* **`intent_address`**: Linked intent address (when available)
***
## Security & Signature Verification
**All webhook payloads are signed using HMAC-SHA256.** Always verify signatures to ensure the webhook came from Chainrails.
### How Signing Works
1. Chainrails generates a signature using your webhook secret
2. Signature is sent in the `X-Chainrails-Signature` header
3. Timestamp is sent in the `X-Chainrails-Timestamp` header
4. You verify the signature matches what you compute
### Signature Format
The signature is computed as:
```
HMAC-SHA256(secret, timestamp + "." + request_body)
```
### Verification Example (Node.js)
```typescript theme={null}
import { createHmac } from 'crypto';
function verifyWebhookSignature(
payload: string,
signature: string,
timestamp: string,
secret: string
): boolean {
// Check timestamp to prevent replay attacks (max 5 minutes old)
const eventTime = parseInt(timestamp, 10) * 1000;
const currentTime = Date.now();
const timeDiff = Math.abs(currentTime - eventTime);
if (timeDiff > 5 * 60 * 1000) {
console.error('Webhook timestamp too old');
return false;
}
// Compute expected signature
const signedPayload = `${timestamp}.${payload}`;
const expectedSignature = createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Compare signatures (constant-time comparison recommended)
return signature === expectedSignature;
}
```
***
## Delivery & Retries
### Delivery Behavior
* **Timeout**: Webhooks must respond within **5 seconds**
* **Success**: Any `2xx` status code (200, 201, 204, etc.)
* **Failure**: Timeouts, network errors, or non-2xx responses
* **Retries**: Automatic retry with exponential backoff
### Retry Schedule
Failed deliveries are automatically retried:
| Attempt | Delay After Failure |
| ------- | ------------------- |
| 1 | Immediate |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 15 minutes |
| 5 | 1 hour |
| 6 | 6 hours |
| 7 | 24 hours |
**After 7 attempts**, the delivery is marked as permanently failed.
***
## Sample Implementation
```typescript theme={null}
app.post('/webhooks/chainrails', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-chainrails-signature'];
const timestamp = req.headers['x-chainrails-timestamp'];
const rawBody = req.body.toString();
// Verify signature
const isValid = verifyWebhookSignature(
rawBody,
signature,
timestamp,
process.env.CHAINRAILS_WEBHOOK_SECRET
);
if (!isValid) {
console.error('Invalid webhook signature');
return res.status(401).json({ error: 'Invalid signature' });
}
// Parse and process the event
const event = JSON.parse(rawBody);
console.log('Received event:', event.type);
// Handle the event
handleWebhookEvent(event);
// Always respond with 200 OK
res.status(200).json({ received: true });
});
```
# Introduction
Source: https://docs.chainrails.io/index
The easiest way to let users fund your app with crypto or fiat — instantly.
## Welcome to Chainrails
Chainrails helps developers build apps that anyone can fund. With a single API/SDK integration, your users can deposit using:
* Any token across 12+ different chains
* Cards, bank transfers, and other fiat payment methods across 70+ countries
While your application receives funds exactly where you want them, in the form you want them — whether that's crypto or fiat, on-chain or off-chain.
## Why Chainrails?
Every developer building a Web3 app today wants the same thing — Letting users fund their app regardless of what they hold, crypto or fiat. Unfortunately, this is harder than it should be.
Crypto users live across different blockchains, and each chain has its own token standards, liquidity silos, and developer tools. Meanwhile, fiat users are served by a fragmented ecosystem of payment processors, each with their own compliance requirements, latency, coverage and fees.
Instead of stitching all these together yourself, you can integrate Chainrails once and we handle the routing, bridging, swapping, ramping, and settlement for you. Your users can fund your app with whatever they have, and you receive funds exactly where you want them.
## What can you build?
Chainrails works anywhere users need to move money in or out of your application. Common usecases include:
* Wallet funding
* Gaming deposits
* Prediction markets
* NFT marketplaces
* Consumer apps
* DeFi applications
* Exchanges
and many more.
## Get Started
Start accepting payments in 10 minutes.
Explore the Chainrails API.
Explore the Chainrails SDKs.
Integrate Chainrails directly with your smart contracts.
Find all supported blockchains and tokens.
# Quickstart
Source: https://docs.chainrails.io/quickstart
Get up and running with Chainrails in minutes.
## Overview
Chainrails gives you a single payment modal that supports both:
* Crypto deposits from supported chains and tokens
* Fiat deposits from 70+ countries
This quickstart is focused on getting the modal live in minutes. You will install the SDK, create a secure session endpoint, and open the modal from your app.
## Get started in three steps
This quickstart uses the React web SDK. If you're building for React Native, use `@chainrails/react-native` with the same backend
session endpoint pattern described below.
Install the UI SDK for your app and the core SDK for your backend session endpoint.
```bash theme={null}
npm install @chainrails/react @chainrails/sdk
```
```bash theme={null}
npm install @chainrails/react-native @chainrails/sdk
```
Create a backend endpoint that generates secure session tokens. This keeps your API key private and lets you control payment defaults.
Here's a curated Github template to help you get started quickly: Chainrails Demo Server
```javascript theme={null}
import { Chainrails, crapi } from "@chainrails/sdk";
app.get("/create-session", async (req, res) => {
const api_key = process.env.CHAINRAILS_API_KEY;
const amount = "100";
const recipient = "0x...";
const destinationChain = "BASE_MAINNET";
const token = "USDC";
Chainrails.config({
api_key,
});
const session = await crapi.auth.getSessionToken({
amount: amount,
recipient: recipient,
destinationChain: destinationChain,
token: token,
});
res.send(session);
});
```
Where:
* `recipient`: Wallet address that receives settled funds.
* `amount`: Target amount. Leave empty or set to `0` to let users enter an amount in the modal.
* `destinationChain`: Chain where funds should settle.
* `token`: Asset to receive on settlement.
These defaults work for both crypto and fiat deposit journeys in the modal.
Initialize the modal in your app and trigger it from a button.
```javascript theme={null}
import { PaymentModal, usePaymentSession } from "@chainrails/react";
function App() {
const cr = usePaymentSession({
session_url: "https://your-server.com/create-session",
onSuccess: () => {
console.log("Payment completed");
},
});
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 (
);
}
export default App;
```
### Hook Return Value
The `usePaymentModal` 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 (pass this to the hook)
***
## PaymentModal Component Props
The `` component accepts the following props:
| Prop | Type | Description |
| --------------- | -------- | ---------------------------------------------------------------------------- |
| `open` | function | Opens the modal |
| `close` | function | Closes the modal |
| `isOpen` | boolean | Current modal visibility state |
| `sessionToken` | string | Active session token for the payment |
| `styles` | object | Custom styling object with options like `accentColor`, `theme` |
| `amount` | number | (Optional) Display amount in the modal |
| `excludeChains` | array | (Optional) Array of chains to exclude from the modal (e.g., `[chains.BASE]`) |
The same modal session flow is available in React Native through `@chainrails/react-native`, with platform-native presentation handled by the mobile SDK.
***
## Styling
Both hooks accept a `styles` object to customize the modal appearance:
```javascript theme={null}
const cr = usePaymentSession({
session_url: "https://your-server.com/create-session",
// ... other options
});
return (
);
```
Available style options include:
* `accentColor`: Primary color for buttons and highlights
* `theme`: "light", "dark", or "system" for automatic theme switching
***
## Callbacks
### onSuccess
Fired when the payment completes successfully. Use this to:
* Update user balance
* Show success message
* Redirect to confirmation page
```javascript theme={null}
onSuccess: () => {
console.log("Payment processed successfully");
// Handle successful payment
};
```
### onCancel
Fired when the user closes or cancels the payment modal. Use this to:
* Log analytics
* Show informational message
* Clean up UI state
```javascript theme={null}
onCancel: () => {
console.log("User cancelled payment");
// Handle cancellation
};
```
***
## Quick Comparison
| Feature | usePaymentSession | usePaymentModal |
| ------------------------- | ----------------- | ----------------- |
| **Setup Complexity** | Simple | Moderate |
| **Session Management** | Automatic | Manual |
| **Dynamic Data Fetching** | Limited | Full Control |
| **Best For** | Standard flows | Complex workflows |
# Create Intent
Source: https://docs.chainrails.io/sdk-reference/intents/create
Create a new payment intent with cross-chain transfer parameters
Creates a new payment intent with cross-chain transfer parameters.
**Parameters:**
* `sender` (required): Sender wallet address on the source chain
* `amount` (required): Amount to transfer in smallest unit (e.g., wei for ETH)
* `amountSymbol` (required): The denomination of the amount (e.g., USDC, DAI, ETH)
* `tokenIn` (required): Token address on the source chain
* `source_chain` (required): Source blockchain network
* `destination_chain` (required): Destination blockchain network
* `recipient` (required): Recipient wallet address on the destination chain
* `refund_address` (optional): Refund address if intent fails (defaults to sender)
* `metadata` (optional): Additional metadata for the intent
The `amountSymbol` parameter is used to specify the denomination of the amount you want to send. For quotes in USD, you need to set `amountSymbol` to USDC.
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const intent = await crapi.intents.create({
sender: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
amount: "1000000",
amountSymbol: "USDC",
tokenIn: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
source_chain: "ETHEREUM_MAINNET",
destination_chain: "STARKNET_MAINNET",
recipient: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
refund_address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
metadata: {
orderId: "12345",
userId: "user-abc"
}
})
console.log("Intent created:", intent)
```
```json theme={null}
{
"id": 2,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees_in_usd": "500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f400000000000000000000000000000000000000000000000000000000000003e8000000000000000000000000000000000000000000000000000000000000000300000000000000000000000075faf114eafb1bdbe2f0316df893fd58ce46aa4d",
"intent_nonce": 4267684716645197,
"intent_status": "PENDING",
"tx_hash": null,
"needs_relay": false,
"expires_at": "2025-11-11T02:31:23.000Z",
"metadata": {
"priority": "normal",
"description": "Cross-chain USDC transfer"
},
"created_at": "2025-11-11T01:31:23.390Z",
"updated_at": "2025-11-11T01:31:23.390Z"
}
```
# Get All Client Intents
Source: https://docs.chainrails.io/sdk-reference/intents/get-all
Retrieve all intents for the authenticated client with pagination and filtering
Retrieves all intents for the authenticated client with pagination and filtering.
**Parameters:**
* `limit` (optional): Number of intents to return (default: 50, max: 100)
* `offset` (optional): Number of intents to skip (default: 0)
* `status` (optional): Filter by intent status ("pending", "processing", "completed", "failed")
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const intents = await crapi.intents.getAll({
limit: 50,
offset: 0,
status: "PENDING"
})
console.log("Intents:", intents)
```
```json theme={null}
{
"intents": [
{
"id": 1,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees_in_usd": "10500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"destination_intent_address": "0x5F70e12374E750fE0E087158f29E3591Ge97B011",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f4",
"intent_nonce": 4267684716645197,
"intent_status": "PENDING",
"tx_hash": null,
"needs_relay": false,
"relayer_claimed": false,
"paymaster_used": false,
"mode": "test",
"expires_at": "2025-12-13T03:31:23.000Z",
"metadata": {
"orderId": "12345"
},
"created_at": "2025-12-13T02:31:23.390Z",
"updated_at": "2025-12-13T02:31:23.390Z"
}
],
"total": 100,
"limit": 50,
"offset": 0
}
```
# Get Intent by ID
Source: https://docs.chainrails.io/sdk-reference/intents/get-by-id
Retrieve information about a specific intent
Retrieves information about a specific intent.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const intent = await crapi.intents.getById("123")
console.log("Intent:", intent)
```
```json theme={null}
{
"id": 6,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees": "10500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"destination_intent_address": "0x5F70e12374E750fE0E087158f29E3591Ge97B011",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f4",
"intent_nonce": 4267684716645197,
"intent_status": "PENDING",
"tx_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"needs_relay": false,
"relayer_claimed": false,
"paymaster_used": false,
"mode": "test",
"expires_at": "2025-12-13T03:31:23.000Z",
"metadata": {
"orderId": "12345"
},
"created_at": "2025-12-13T02:31:23.390Z",
"updated_at": "2025-12-13T02:31:23.390Z"
}
```
# Get Intent by Address
Source: https://docs.chainrails.io/sdk-reference/intents/get-for-address
Retrieve an intent using its contract address
Retrieves an intent using its contract address.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const intent = await crapi.intents.getForAddress("0x4E60e01263E750eD9D087157e19D2480Fd86A900")
console.log("Intent:", intent)
```
```json theme={null}
{
"id": 3,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees_in_usd": "10500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"destination_intent_address": "0x5F70e12374E750fE0E087158f29E3591Ge97B011",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f4",
"intent_nonce": 4267684716645197,
"intent_status": "FUNDED",
"tx_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"needs_relay": false,
"relayer_claimed": false,
"paymaster_used": false,
"mode": "test",
"expires_at": "2025-12-13T03:31:23.000Z",
"metadata": {
"orderId": "12345"
},
"created_at": "2025-12-13T02:31:23.390Z",
"updated_at": "2025-12-13T02:33:15.120Z"
}
```
# Get Intents for Sender
Source: https://docs.chainrails.io/sdk-reference/intents/get-for-sender
Retrieve all intents created by a specific user address
Retrieves all intents created by a specific user address.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const userIntents = await crapi.intents.getForSender("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")
console.log("User intents:", userIntents)
```
```json theme={null}
[
{
"id": 1,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"initialAmount": "1000000",
"fees_in_usd": "10500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"destination_intent_address": "0x5F70e12374E750fE0E087158f29E3591Ge97B011",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f4",
"intent_nonce": 4267684716645197,
"intent_status": "COMPLETED",
"tx_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"needs_relay": false,
"relayer_claimed": true,
"paymaster_used": false,
"mode": "test",
"expires_at": "2025-12-13T03:31:23.000Z",
"metadata": {
"orderId": "12345"
},
"created_at": "2025-12-13T02:31:23.390Z",
"updated_at": "2025-12-13T02:35:10.220Z"
}
]
```
# Update Intent Status
Source: https://docs.chainrails.io/sdk-reference/intents/update
Update the status of an existing intent
Updates the status of an existing intent.
**Status values:** `"PENDING"`, `"FUNDED"`, `"INITIATED"`, `"COMPLETED"`, `"EXPIRED"`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const updated = await crapi.intents.update("123", {
status: "COMPLETED"
})
console.log("Updated intent:", updated)
```
```json theme={null}
{
"id": 6,
"client_id": "e1ee3675-cb26-4a76-8206-a84f86e85862",
"sender": "0xdA3ECb2E5362295E2b802669dD47127A61d9Ce54",
"initialAmount": "1000000",
"fees_in_usd": "10500",
"app_fee_in_usd": "1000",
"total_amount_in_usd": "1010500",
"total_amount_in_asset_token": "1000500",
"fees_in_asset_token": "500",
"app_fee_in_asset_token": "0",
"asset_token_symbol": "USDC",
"asset_token_decimals": 6,
"slippage": "0.5",
"tokenIn": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tokenOut": "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
"intent_address": "0x4E60e01263E750eD9D087157e19D2480Fd86A900",
"destination_intent_address": "0x5F70e12374E750fE0E087158f29E3591Ge97B011",
"source_chain": "BASE_TESTNET",
"destination_chain": "ARBITRUM_TESTNET",
"recipient": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"refund_address": "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e",
"relayer": "",
"coordinator": "0x989f47053F188778575113DcF39dB8960Fc450e2",
"bridger": "0xa1c943058a631D5506eb7d96036eAbF6968e2338",
"bridgeExtraData": "0x00000000000000000000000000000000000000000000000000000000000001f4",
"intent_nonce": 4267684716645197,
"intent_status": "COMPLETED",
"tx_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"needs_relay": false,
"relayer_claimed": true,
"paymaster_used": false,
"mode": "test",
"expires_at": "2025-12-13T03:31:23.000Z",
"metadata": {
"orderId": "12345"
},
"created_at": "2025-12-13T02:31:23.390Z",
"updated_at": "2025-12-13T02:40:05.550Z"
}
```
# Introduction
Source: https://docs.chainrails.io/sdk-reference/introduction
SDK Reference for Chainrails client SDKs for web and mobile cross-chain payments
You need an API Key to use the Chainrails SDK. 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 provides client SDKs for web and mobile applications:
* `@chainrails/sdk`: Core TypeScript SDK for interacting with the Chainrails API
* `@chainrails/react`: React components and hooks for web integrations
* `@chainrails/react-native`: React Native components and hooks for mobile integrations
Together, these packages handle authentication, request formatting, UI integration, and error handling so you can focus on building your application.
## Installation
```bash theme={null}
npm install @chainrails/sdk
```
```bash theme={null}
npm install @chainrails/react @chainrails/sdk
```
```bash theme={null}
npm install @chainrails/react-native @chainrails/sdk
```
## SDK Modules
The SDK is organized into the following modules:
### [Intents](/sdk-reference/intents)
Create and manage cross-chain transfer intents, track payment status, and retrieve intent information.
### [Router](/sdk-reference/router)
Find optimal routes and analyze bridge availability for cross-chain transfers.
### [Quotes](/sdk-reference/quotes)
Get real-time quotes for cross-chain transfers from various bridge providers.
### [Chains](/sdk-reference/chains)
Retrieve information about supported blockchain networks and tokens.
### [Client](/sdk-reference/client)
Retrieve authenticated client information.
### [Ramp](/sdk-reference/ramp)
Allow users make payment using local fiat currencies.
## Platform Support
Chainrails SDK support is currently available for **TypeScript/JavaScript**, with UI integrations for **React web** and **React Native**.
## Recommended Package by Use Case
* Use `@chainrails/sdk` for server-side integrations and direct API access from TypeScript/JavaScript
* Use `@chainrails/react` for web apps that need the Payment Modal and session hooks
* Use `@chainrails/react-native` for React Native apps that need mobile payment flows
## Authentication
The SDK uses API key-based authentication. Configure your API key once at startup:
```typescript theme={null}
import { Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: process.env.CHAINRAILS_API_KEY
})
```
The API key is automatically included in all requests via the `Authorization: Bearer` header.
## Error Handling
The SDK throws errors for failed requests. Wrap SDK calls in try-catch blocks:
```typescript theme={null}
try {
const intent = await crapi.intents.create({...})
} catch (error) {
if (error instanceof Error) {
console.error("Failed to create intent:", error.message)
}
}
```
## Type Definitions
The SDK includes full TypeScript type definitions for all requests and responses, providing autocomplete and type safety in your IDE.
## 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 also 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.
# Get Quotes from All Source Chains
Source: https://docs.chainrails.io/sdk-reference/quotes/get-all
Show all options to send money to a specific destination chain
Shows all options to send money to a specific destination chain, including same-chain transfers.
**Parameters:**
* `destinationChain` (required): Destination blockchain
* `amount` (required): Amount in human readable format (supports decimals like "1.5", "100", "0.001")
* `tokenOut` (required): Output token address
* `recipient` (optional): Recipient address
* `excludeChains` (optional): Comma-separated chains to exclude from results (e.g., "BASE\_TESTNET,STARKNET\_TESTNET")
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const multiSourceQuotes = await crapi.quotes.getAll({
destinationChain: "ARBITRUM_MAINNET",
amount: "1.5",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})
console.log("Multi-source quotes:", multiSourceQuotes)
```
```json theme={null}
[
{
"sourceChain": "BASE_MAINNET",
"bridge": "ACROSS",
"tokenIn": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "1500000",
"amountOut": "1497750",
"fee": "2250",
"estimatedTime": 300
},
{
"sourceChain": "ETHEREUM_MAINNET",
"bridge": "CCTP",
"tokenIn": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "1500000",
"amountOut": "1495000",
"fee": "5000",
"estimatedTime": 600
}
]
```
# Get Best Quote Across All Bridges
Source: https://docs.chainrails.io/sdk-reference/quotes/get-best-across-bridges
Retrieve the best quote (lowest total fee) from all supported bridge protocols
Retrieves the best quote (lowest total fee) from all supported bridge protocols.
**Parameters:**
* `tokenIn` (required): Input token address
* `tokenOut` (required): Output token address
* `sourceChain` (required): Source blockchain
* `destinationChain` (required): Destination blockchain
* `amount` (required): Amount in token units
* `amountSymbol` (optional): The denomination of the amount (e.g., USDC, DAI, ETH).
* `excludeBridges` (optional): Comma-separated bridges to exclude
* `recipient` (optional): Recipient address
The `amountSymbol` parameter is used to specify the denomination of the amount you want to send. For quotes in USD, you need to set `amountSymbol` to USDC (or leave empty).
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const bestQuote = await crapi.quotes.getBestAcrossBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
amountSymbol: "USDC",
excludeBridges: "GATEWAY",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})
console.log("Best quote:", bestQuote)
```
```json theme={null}
{
"bridge": "ACROSS",
"tokenIn": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "10000000",
"amountOut": "9985000",
"fee": "15000",
"estimatedTime": 300,
"recipient": "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
}
```
# Get Quotes from All Bridges
Source: https://docs.chainrails.io/sdk-reference/quotes/get-from-all-bridges
Retrieve quotes from all supported bridge protocols for comparison
Retrieves quotes from all supported bridge protocols for comparison.
**Parameters:**
* `tokenIn` (required): Input token address
* `tokenOut` (required): Output token address
* `sourceChain` (required): Source blockchain
* `destinationChain` (required): Destination blockchain
* `amount` (required): Amount in token units
* `amountSymbol` (optional): The denomination of the amount (e.g., USDC, DAI, ETH).
* `excludeBridges` (optional): Comma-separated bridges to exclude
* `excludeChains` (optional): Comma-separated chains to exclude from results (e.g., "BASE\_TESTNET,STARKNET\_TESTNET")
* `recipient` (optional): Recipient address
The `amountSymbol` parameter is used to specify the denomination of the amount you want to send. For quotes in USD, you need to set `amountSymbol` to USDC (or leave empty).
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here",
})
const quotes = await crapi.quotes.getFromAllBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
excludeBridges: "GATEWAY,CCTP",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})
console.log("Quotes from all bridges:", quotes)
```
```json theme={null}
[
{
"bridge": "ACROSS",
"tokenIn": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "10000000",
"amountOut": "9985000",
"fee": "15000",
"estimatedTime": 300
},
{
"bridge": "RHINOFI",
"tokenIn": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "10000000",
"amountOut": "9970000",
"fee": "30000",
"estimatedTime": 450
}
]
```
# Get Quote from Specific Bridge
Source: https://docs.chainrails.io/sdk-reference/quotes/get-from-specific-bridge
Retrieve a cross-chain transfer quote from a specific bridge protocol
Retrieves a cross-chain transfer quote from a specific bridge protocol.
**Parameters:**
* `tokenIn` (required): Input token address
* `tokenOut` (required): Output token address
* `sourceChain` (required): Source blockchain
* `destinationChain` (required): Destination blockchain
* `amount` (required): Amount in token units
* `amountSymbol` (optional): The denomination of the amount (e.g., USDC, DAI, ETH).
* `bridge` (required): Bridge to use (e.g `ACROSS`, `CCTP`, `GATEWAY`, `RHINOFI`)
* `recipient` (optional): Recipient address
The `amountSymbol` parameter is used to specify the denomination of the amount you want to send. For quotes in USD, you need to set `amountSymbol` to USDC (or leave empty).
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const quote = await crapi.quotes.getFromSpecificBridge({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
bridge: "ACROSS",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})
console.log("Quote:", quote)
```
```json theme={null}
{
"bridge": "ACROSS",
"tokenIn": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"tokenOut": "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "10000000",
"amountOut": "9985000",
"fee": "15000",
"estimatedTime": 300,
"recipient": "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
}
```
# Cancel Order
Source: https://docs.chainrails.io/sdk-reference/ramp/cancel-order
Cancel an order before completion
Cancels a ramp order if it is still in a cancellable state.
## Parameters
* `id` (required): Ramp order ID
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
const order = await crapi.ramp.cancelOrder({
id: 422,
});
console.log("order 422:", order);
```
# Confirm Order
Source: https://docs.chainrails.io/sdk-reference/ramp/confirm-order
Confirm order after user completes deposit
Confirms a ramp order after the user has completed their deposit action.
## Parameters
* `id` (required): Ramp order ID
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
const order = await crapi.ramp.confirmOrder({
id: 422,
});
console.log("order 422:", order);
```
# Create Order
Source: https://docs.chainrails.io/sdk-reference/ramp/create-order
Create a fiat-to-crypto order and get a provider widget URL
Initiates a fiat-to-crypto purchase by creating an order with a selected quote. Returns a provider widget URL that you redirect the user to for completing payment.
* `provider`: RampProvider;
* `fiatCurrency`: string;
* `cryptoAmount`: number;
* `destinationChain`: string;
* `recipientAddress`: string;
* `countryCode`: string;
* `paymentChannelId`?: string;
* `email`?: string;
* `phoneNumber`?: string;
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
// Get quotes for spending $100 USD
const order = await crapi.ramp.createOrder({
provider: "ONRAMP_MONEY";
fiatCurrency: "USD";
cryptoAmount: 10;
destinationChain: "BASE_MAINNET",
recipientAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
countryCode: "US",
});
```
## Widget Integration
The `widgetUrl` returned is a fully-hosted checkout page. Redirect your users there:
```typescript theme={null}
// Full page redirect
window.location.href = order.widgetUrl;
// Or open in popup
const popup = window.open(order.widgetUrl, "RampCheckout", "width=480,height=800");
```
# Get Countries
Source: https://docs.chainrails.io/sdk-reference/ramp/get-countries
List all supported countries with currency details
Returns all enabled countries with currency details. Optionally filter by fiat currency code and/or minimum crypto (USDC) amount.
## Parameters
* `currency` (optional): ISO 4217 fiat currency code (e.g., USD, EUR, GBP)
* `amount` (optional): Amount to receive in USD/USDC
## Response
List of supported countries with currency info
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
// Filter by provider
const countries = await crapi.ramp.getCountries({
currency: "USD",
});
console.log("Supported countries:", countries);
```
# Get Currencies
Source: https://docs.chainrails.io/sdk-reference/ramp/get-currencies
List all supported on-ramp currencies
Returns all enabled fiat currencies. Optionally filter by a specific ramp provider.
## Parameters
* `provider` (optional): Filter by specific provider
## Response
Returns all enabled fiat currencies. Optionally filter by a specific ramp provider.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
const currencies = await crapi.ramp.getCurrencies({
provider: "ONRAMP_MONEY",
});
console.log("Supported currencies:", currencies);
```
# Get Order
Source: https://docs.chainrails.io/sdk-reference/ramp/get-order
Retrieve a specific order details by it's id
Returns the full details of a ramp order, scoped to the authenticated client.
## Parameters
* `id` (required): Ramp order ID
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
const order = await crapi.ramp.getOrder({
id: 422,
});
console.log("order 422:", order);
```
# Get Quotes
Source: https://docs.chainrails.io/sdk-reference/ramp/get-quotes
Get aggregated fiat-to-crypto quotes from all eligible providers
Fetches real-time quotes from multiple on-ramp providers, automatically selecting the cheapest path for your users. This method fans out to all supported providers and aggregates their rates, fees, and delivery times.
## Parameters
* `fiatCurrency` (required): ISO 4217 fiat currency code (e.g., USD, EUR, GBP)
* `cryptoAmount` (required): Amount of crypto to receive
* `destinationChain` (required): Destination blockchain where user wants funds
* `countryCode` (optional): ISO 3166-1 alpha-2 country code of the user. Required for multi-country currencies. Falls back to the currency's default country if omitted.
* `directOnly` (optional): If true, only return quotes with direct transfer channels
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
// Get quotes for spending $100 USD
const quotes = await crapi.ramp.getQuotes({
fiatCurrency: "USD";
cryptoAmount: 10;
destinationChain: "BASE_MAINNET";
countryCode: US;
directOnly: FALSE;
})
console.log("Best quote:", quotes.recommended)
```
# Introduction
Source: https://docs.chainrails.io/sdk-reference/ramp/introduction
Allow users make payment using local fiat currencies
The Ramp module enables seamless fiat-to-crypto conversions, allowing users make payment with traditional payment methods like credit cards, bank transfers, and local payment options and you receive it in your preferred token and chain.
## Overview
Chainrails aggregates multiple on-ramp providers to offer your users the best rates and widest coverage. The Ramp module handles the entire flow from quote discovery to order completion, including:
* **Quote Aggregation**: Compare rates across multiple providers in real-time
* **Global Coverage**: Support for 35+ countries and 20+ fiat currencies
* **Multiple Payment Methods**: Cards, bank transfers, Apple Pay, Google Pay, and local options
## Quick Start
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
// Get quotes for buying crypto with fiat
const quotes = await crapi.ramp.getQuotes({
fiatCurrency: "USD";
cryptoAmount: 10;
destinationChain: "BASE_MAINNET";
countryCode: US;
directOnly: FALSE;
});
// Create an order with the best quote
const order = await crapi.ramp.createOrder({
provider: "ONRAMP_MONEY";
fiatCurrency: "USD";
cryptoAmount: 10;
destinationChain: "BASE_MAINNET",
recipientAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
countryCode: "US",
});
// Redirect user to provider widget
window.location.href = order.widgetUrl;
```
## Available Methods
List all supported countries with currency details
List all supported on-ramp currencies
Compare fiat-to-crypto rates across all providers
Initiate a fiat-to-crypto purchase
List all orders
Retrieve a specific order details by it's id
Confirm order after user completes deposit
Cancel an order before completion
## Order Lifecycle
1. **CREATED**: Order initialized, awaiting user action
2. **PENDING**: User redirected to provider widget
3. **PROCESSING**: Payment received, crypto being delivered
4. **COMPLETED**: Crypto successfully deposited to wallet
5. **CANCELLED**: Order cancelled by user or system
6. **EXPIRED**: Quote expired before completion
7. **FAILED**: Payment or delivery failed
8. **REFUNDED**: User has been refunded
# List Orders
Source: https://docs.chainrails.io/sdk-reference/ramp/list-orders
List all orders
Returns all ramp orders for the authenticated client, newest first.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk";
Chainrails.config({
api_key: "your_api_key_here",
});
const orders = await crapi.ramp.listOrders();
console.log("all orders:", orders);
```
# Get All Supported Bridges
Source: https://docs.chainrails.io/sdk-reference/router/get-all-supported-bridges
Return all bridges and their supported routes
Returns all bridges and their supported routes.
**Supported bridges:** `ACROSS`, `CCTP`, `GATEWAY`, `RHINOFI`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const bridges = await crapi.router.getAllSupportedBridges()
console.log("Supported bridges:", bridges)
```
```json theme={null}
{
"ACROSS": [
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET"
},
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ETHEREUM_MAINNET"
}
],
"CCTP": [
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET"
}
],
"GATEWAY": [
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "STARKNET_MAINNET"
}
],
"RHINOFI": [
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET"
}
]
}
```
# Get Optimal Routes
Source: https://docs.chainrails.io/sdk-reference/router/get-optimal-routes
Analyze available bridges and return the optimal route with best pricing
Analyzes available bridges and returns the optimal route with best pricing.
**Parameters:**
* `tokenIn` (required): Input token contract address
* `tokenOut` (required): Output token contract address
* `sourceChain` (required): Source blockchain
* `destinationChain` (required): Destination blockchain
* `amount` (required): Transfer amount in token units (wei for ETH)
* `amountSymbol` (required): The denomination of the amount (e.g., USDC, DAI, ETH).
* `recipient` (optional): Recipient address (required for some bridges like RhinoFi)
The `amountSymbol` parameter is used to specify the denomination of the amount you want to send. For quotes in USD, you need to set `amountSymbol` to USDC.
You can quote in a different denomination than the token you want to send. For example, you can set `amountSymbol` to USDC, while sending ETH as `tokenIn`
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const route = await crapi.router.getOptimalRoutes({
tokenIn: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
tokenOut: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "1000000000000000000",
amountSymbol: "USDC",
recipient: "0x742d35cc6634c0532925a3b8d7389d8c5b7cf15b"
})
console.log("Optimal route:", route)
```
```json theme={null}
{
"bridge": "ACROSS",
"tokenIn": "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
"tokenOut": "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET",
"amountIn": "1000000000000000000",
"amountOut": "998500000000000000",
"fee": "1500000000000000",
"estimatedTime": 300,
"recipient": "0x742d35cc6634c0532925a3b8d7389d8c5b7cf15b"
}
```
# Get Supported Bridges for Route
Source: https://docs.chainrails.io/sdk-reference/router/get-supported-bridges
Return all bridges that support transfers between specific source and destination chains
Returns all bridges that support transfers between specific source and destination chains.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const supportedBridges = await crapi.router.getSupportedBridges({
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET"
})
console.log("Supported bridges for route:", supportedBridges)
```
```json theme={null}
[
"ACROSS",
"CCTP",
"GATEWAY"
]
```
# Get Supported Routes for Bridge
Source: https://docs.chainrails.io/sdk-reference/router/get-supported-routes
Return all source/destination chain pairs supported by a specific bridge
Returns all source/destination chain pairs supported by a specific bridge.
```typescript theme={null}
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({
api_key: "your_api_key_here"
})
const routes = await crapi.router.getSupportedRoutes("ACROSS")
console.log("Supported routes:", routes)
```
```json theme={null}
[
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ARBITRUM_MAINNET"
},
{
"sourceChain": "BASE_MAINNET",
"destinationChain": "ETHEREUM_MAINNET"
},
{
"sourceChain": "ARBITRUM_MAINNET",
"destinationChain": "BASE_MAINNET"
}
]
```
# SDK vs API
Source: https://docs.chainrails.io/sdk-vs-api
When to use the SDK vs the API
Chainrails offers both client SDKs and a RESTful API, each designed for different needs and levels of abstraction.
## The SDK
Chainrails SDKs provide the fastest way to integrate payments in TypeScript/JavaScript applications. They wrap our APIs and handle authentication, retries, UI flows, and session-based payment experiences for you.
**We recommend using the SDK for:**
* Web applications and dApps that requires a pre-built modal
* React Native mobile applications that also don't mind a pre-built modal
* Quick prototyping
* JavaScript/TypeScript projects
* Reducing boilerplate (no need to manually handle HTTP or auth)
The SDK surface includes:
* `@chainrails/sdk` for core API access
* `@chainrails/react` for React web integrations
* `@chainrails/react-native` for React Native integrations
### Sample integration
**Installation**
```bash theme={null}
npm install @chainrails/react @chainrails/sdk
```
For React Native apps:
```bash theme={null}
npm install @chainrails/react-native @chainrails/sdk
```
**Usage**
First, create a server endpoint for session creation:
```javascript theme={null}
// Example with Express.js
import { Chainrails, crapi } from "@chainrails/sdk";
app.get("/create-session", async (req, res) => {
const api_key = process.env.CHAINRAILS_API_KEY;
const amount = "100";
const recipient = "0x...";
const destinationChain = "BASE";
const token = "USDC";
Chainrails.config({
api_key: process.env.CHAINRAILS_API_KEY
});
const session = await crapi.auth.getSessionToken({
amount: amount,
recipient: recipient,
destinationChain: destinationChain,
token: token,
});
res.send(session);
});
```
Then use the SDK on the client:
```javascript theme={null}
import { chains, tokens, PaymentModal, usePaymentSession } from "@chainrails/react";
function App() {
const cr = usePaymentSession({
session_url: "https://your-server.com/create-session",
onSuccess: () => {
console.log("Payment Successful");
},
});
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).