@chainrails/sdk
v0.3.4
Published
A TypeScript SDK for interacting with the Chainrails API - enabling seamless cross-chain token transfers, bridge routing, and intent management across multiple blockchain networks.
Downloads
745
Readme
@chainrails/sdk
A TypeScript SDK for interacting with the Chainrails API - enabling seamless cross-chain token transfers, bridge routing, and intent management across multiple blockchain networks.
Features
- 🔗 Cross-Chain Transfers - Facilitate token transfers between multiple blockchain networks
- 🌉 Bridge Routing - Find optimal routes and pricing across multiple bridge protocols
- 💰 Quote Management - Get real-time quotes from various bridge providers
- 📋 Intent Management - Create and manage cross-chain transfer intents
- 🔐 Session Authentication - Secure session-based auth for modal payment flows (NEW in v0.1.0)
- ⛓️ Chain Support - Support for 11+ blockchain networks including Ethereum, Arbitrum, Base, Starknet, and more
- 🔐 Secure - API key-based authentication with automatic header injection
- 📦 Tree-shakeable - Built with ES modules for optimal bundle sizes
What's New in v0.1.0 (January 2026)
New: Session Token Authentication Module
The Auth module provides secure session-based authentication for modal payment flows:
const session = await crapi.auth.getSessionToken({
recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
destinationChain: "ARBITRUM_MAINNET",
token: "USDC",
amount: "100"
})
// Returns: { sessionToken, sessionId, expiresAt }Use Cases:
- Iframe-based payment modal initialization
- Client-side session management with automatic expiration
- Secure token propagation to frontend applications
Enhanced Intent APIs
New session-aware methods for managing intents within modal context:
// Create intent for session (simplified parameters)
const intent = await crapi.intents.createForSession({
/* minimal parameters */
})
// Get intents associated with a session
const sessionIntents = await crapi.intents.getForSession("0x...")
// Get intent by contract address
const intent = await crapi.intents.getForAddress("0x...")
// Trigger processing within session context
const result = await crapi.intents.triggerProcessingForSession("0x...")Session-Based Quote Queries
Retrieve quotes within a payment session context:
const quotes = await crapi.quotes.getAllForSession({
// session-specific parameters
})Breaking Changes
- Intent Creation: Use
createForSession()for modal flows instead ofcreate() - Response Types: Quote responses now have enhanced types for session context
- Authentication: Session token required for iframe communication
Installation
npm install @chainrails/sdkpnpm add @chainrails/sdkyarn add @chainrails/sdkQuick Start
1. Initialize the SDK
import { crapi, Chainrails} from "@chainrails/sdk"
// Configure with your API key
Chainrails.config({
api_key: "your_api_key_here"
})
// Now use the SDK
const chains = await crapi.chains.getSupported()2. Get Supported Chains
// Get all supported chains
const allChains = await crapi.chains.getSupported()
// Get only mainnet chains
const mainnetChains = await crapi.chains.getSupported({ network: "mainnet" })
// Get only testnet chains
const testnetChains = await crapi.chains.getSupported({ network: "testnet" })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
API Reference
Auth Module (New in v0.1.0)
Manage session-based authentication for modal payment flows.
Get Session Token
Creates a secure session token for iframe-based payment modal initialization.
const session = await crapi.auth.getSessionToken({
recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
destinationChain: "ARBITRUM_MAINNET",
token: "USDC",
amount: "100"
})Parameters:
recipient(required): Recipient wallet address on destination chaindestinationChain(required): Destination blockchain networktoken(required): Token symbol (e.g., "USDC", "ETH")amount(required): Transfer amount (string or number)
Response:
interface getSessionTokenOutput {
sessionToken: string // JWT token for iframe communication
sessionId: string // Unique session identifier
expiresAt: string // ISO 8601 expiration timestamp
}Use Cases:
- Initialize payment modal with secure authentication
- Manage session lifecycle with automatic expiration
- Propagate credentials to iframe securely via postMessage
Intents Module
Manage cross-chain transfer intents.
Create Intent
Creates a new payment intent with cross-chain transfer parameters.
const intent = await crapi.intents.create({
sender: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
amount: 1000000,
tokenIn: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
source_chain: "ETHEREUM_MAINNET",
destination_chain: "STARKNET_MAINNET",
recipient: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
refund_address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
metadata: {
orderId: "12345",
userId: "user-abc"
}
})Parameters:
sender(required): Sender wallet address on the source chainamount(required): Amount to transfer in smallest unit (e.g., wei for ETH)tokenIn(required): Token address on the source chainsource_chain(required): Source blockchain networkdestination_chain(required): Destination blockchain networkrecipient(required): Recipient wallet address on the destination chainrefund_address(optional): Refund address if intent fails (defaults to sender)metadata(optional): Additional metadata for the intent
Response:
interface Intent {
id: number
client_id: string
sender: string
initialAmount: string
fees: string
totalAmount: string
tokenIn: string
tokenOut: string
intent_address: string
source_chain: string
destination_chain: string
recipient: string
refund_address: string
relayer: string
coordinator: string
bridger: string
bridgeExtraData: string
intent_nonce: number
intent_status: "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED"
tx_hash: string | null
needs_relay: boolean
expires_at: string
metadata: object
created_at: string
updated_at: string
}Get Intent by ID
Retrieves information about a specific intent.
const intent = await crapi.intents.getById("123")Get All Client Intents
Retrieves all intents for the authenticated client with pagination and filtering.
const intents = await crapi.intents.getAll({
limit: 50,
offset: 0,
status: "PENDING"
})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")
Get Intents for Sender
Retrieves all intents created by a specific user address.
const userIntents = await crapi.intents.getForSender("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")Get Intent by Address
Retrieves an intent using its contract address.
const intent = await crapi.intents.getForAddress("0x4E60e01263E750eD9D087157e19D2480Fd86A900")Update Intent Status
Updates the status of an existing intent.
const updated = await crapi.intents.update("123", {
status: "COMPLETED"
})Status values: "PENDING", "FUNDED", "INITIATED", "COMPLETED", "EXPIRED"
Create Intent for Session (New in v0.1.0)
Creates an intent specifically for modal-based payment flows with simplified parameters.
const intent = await crapi.intents.createForSession({
// Simplified parameters for session context
// See API documentation for complete parameter list
})Use Case: Use this method when creating intents within a modal payment session context instead of create().
Get Intents for Session (New in v0.1.0)
Retrieves all intents associated with a specific session.
const sessionIntents = await crapi.intents.getForSession("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")Parameters:
address(required): Session address identifier
Trigger Processing for Session (New in v0.1.0)
Triggers payment processing for an intent within a modal session context.
const result = await crapi.intents.triggerProcessingForSession("0x4E60e01263E750eD9D087157e19D2480Fd86A900")Parameters:
intentAddress(required): Contract address of the intent
Response:
interface triggerProcessingOutput {
// Processing status and receipt information
}Router Module
Find optimal routes and analyze bridge availability for cross-chain transfers.
Find Optimal Route
Analyzes available bridges and returns the optimal route with best pricing.
const route = await crapi.router.getOptimalRoutes({
tokenIn: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
tokenOut: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "1000000000000000000",
recipient: "0x742d35cc6634c0532925a3b8d7389d8c5b7cf15b"
})Parameters:
tokenIn(required): Input token contract addresstokenOut(required): Output token contract addresssourceChain(required): Source blockchaindestinationChain(required): Destination blockchainamount(required): Transfer amount in token units (wei for ETH)recipient(optional): Recipient address (required for some bridges like RhinoFi)
Get All Supported Bridges
Returns all bridges and their supported routes.
const bridges = await crapi.router.getAllSupportedBridges()Supported bridges: ACROSS, CCTP, GATEWAY, RHINOFI
Get Supported Bridges for Route
Returns all bridges that support transfers between specific source and destination chains.
const supportedBridges = await crapi.router.getSupportedBridges({
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET"
})Get Supported Routes for Bridge
Returns all source/destination chain pairs supported by a specific bridge.
const routes = await crapi.router.getSupportedRoutes("ACROSS", {
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET"
})Quotes Module
Get real-time quotes for cross-chain transfers from various bridge providers.
Get Quote from Specific Bridge
Retrieves a cross-chain transfer quote from a specific bridge protocol.
const quote = await crapi.quotes.getFromSpecificBridge({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
bridge: "ACROSS",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})Parameters:
tokenIn(required): Input token addresstokenOut(required): Output token addresssourceChain(required): Source blockchaindestinationChain(required): Destination blockchainamount(required): Amount in token unitsbridge(required): Bridge to use for the quote (ACROSS,CCTP,GATEWAY,RHINOFI)recipient(optional): Recipient address
Get Quotes from All Bridges
Retrieves quotes from all supported bridge protocols for comparison.
const quotes = await crapi.quotes.getFromAllBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
excludeBridges: "GATEWAY,CCTP",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})Parameters:
tokenIn(required): Input token addresstokenOut(required): Output token addresssourceChain(required): Source blockchaindestinationChain(required): Destination blockchainamount(required): Amount in token unitsexcludeBridges(optional): Comma-separated bridges to excluderecipient(optional): Recipient address
Get Best Quote Across All Bridges
Retrieves the best quote (lowest total fee) from all supported bridge protocols.
const bestQuote = await crapi.quotes.getBestAcrossBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000",
excludeBridges: "GATEWAY",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})Get Quotes from All Source Chains
Shows all options to send money to a specific destination chain, including same-chain transfers.
const multiSourceQuotes = await crapi.quotes.getAll({
destinationChain: "ARBITRUM_MAINNET",
amount: "1.5",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
recipient: "0x742d35Cc6635C0532925a3b8D62A7fe7B58123D1"
})Parameters:
destinationChain(required): Destination blockchainamount(required): Amount in human readable format (supports decimals like "1.5", "100", "0.001")tokenOut(required): Output token addressrecipient(optional): Recipient address
Get Quotes for Session (New in v0.1.0)
Retrieves all available bridge quotes within a payment session context.
const sessionQuotes = await crapi.quotes.getAllForSession({
// session-specific parameters
})Use Case: Use this method to get quotes when operating within a modal session context. Returns quotes in the same format as getBestAcrossBridges() for consistency.
Chains Module
Retrieve information about supported blockchain networks and tokens.
Get Supported Chains
Retrieves all supported blockchain networks, optionally filtered by network type.
// Get all chains
const allChains = await crapi.chains.getSupported()
// Get only mainnet chains
const mainnetChains = await crapi.chains.getSupported({ network: "mainnet" })
// Get only testnet chains
const testnetChains = await crapi.chains.getSupported({ network: "testnet" })Get Supported Tokens for Chain
Retrieves all supported tokens available on a specified blockchain network.
const tokens = await crapi.chains.getSupported({
chain: "BASE_MAINNET"
})Client Module
Retrieve authenticated client information.
Get Client Info
Retrieves information about the authenticated client.
const clientInfo = await crapi.client.getClientInfo()Type Definitions
// Status types
type Status = "PENDING" | "FUNDED" | "INITIATED" | "COMPLETED" | "EXPIRED"
// Bridge types
type Bridge = "ACROSS" | "CCTP" | "GATEWAY" | "RHINOFI"
// Network types
type Network = "mainnet" | "testnet"
// Supported chains
type Chain =
| "ARBITRUM_MAINNET"
| "ARBITRUM_TESTNET"
| "AVALANCHE_MAINNET"
| "AVALANCHE_TESTNET"
| "BASE_MAINNET"
| "BASE_TESTNET"
| "STARKNET_MAINNET"
| "STARKNET_TESTNET"
| "BSC_MAINNET"
| "ETHEREUM_MAINNET"
| "ETHEREUM_TESTNET"Error Handling
The SDK uses the ky HTTP client which throws errors for failed requests. Wrap SDK calls in try-catch blocks:
try {
const intent = await crapi.intents.create({
sender: "0x...",
amount: 1000000,
tokenIn: "0x...",
source_chain: "ETHEREUM_MAINNET",
destination_chain: "ARBITRUM_MAINNET",
recipient: "0x..."
})
} catch (error) {
if (error instanceof Error) {
console.error("Failed to create intent:", error.message)
}
}Authentication
The SDK uses API key-based authentication. Configure your API key once at startup:
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.
Configuration
Base URL
The SDK defaults to the development API:
https://dev.chainrails.io/api/v1To use a different endpoint, you can modify the request configuration in src/req.ts.
Retry Policy
The SDK automatically retries failed requests up to 2 times.
Examples
Example 1: Create Intent and Monitor Status
import { crapi, Chainrails } from "@chainrails/sdk"
Chainrails.config({ api_key: "your_api_key" })
const intent = await crapi.intents.create({
sender: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
amount: 1000000,
tokenIn: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
source_chain: "ETHEREUM_MAINNET",
destination_chain: "ARBITRUM_MAINNET",
recipient: "0xb79541Be080a59fdcE6C0b43219ba56c725eC65e"
})
console.log("Intent created:", intent.id, intent.intent_status)
// Retrieve updated intent
const updated = await crapi.intents.getById(String(intent.id))
console.log("Updated status:", updated.intent_status)Example 2: Compare Quotes Across Bridges
import { crapi } from "@chainrails/sdk"
const quotes = await crapi.quotes.getFromAllBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000"
})
// Get the best quote
const best = await crapi.quotes.getBestAcrossBridges({
tokenIn: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
tokenOut: "0x06eFdBFf2a14a7c8E15944D1F4A48F9F95F663A4",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "10000000"
})
console.log("Best quote total fee:", best.bestQuote.totalFeeFormatted)Example 3: Find Optimal Route
import { crapi } from "@chainrails/sdk"
const route = await crapi.router.getOptimalRoutes({
tokenIn: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
tokenOut: "0xA0b86a33E6411192B1F4ec3eB801B21EB56",
sourceChain: "BASE_MAINNET",
destinationChain: "ARBITRUM_MAINNET",
amount: "1000000000000000000"
})
console.log("Optimal route:", route)Example 4: List All User Intents
import { crapi } from "@chainrails/sdk"
const userAddress = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
const intents = await crapi.intents.getForSender(userAddress)
intents.forEach(intent => {
console.log(`Intent ${intent.id}:`, {
status: intent.intent_status,
amount: intent.totalAmount,
from: intent.source_chain,
to: intent.destination_chain,
created: intent.created_at
})
})Development
Build
pnpm run buildType Checking
pnpm run check-typesLinting
pnpm run lintClean
pnpm run cleanBrowser Support
The SDK works in modern browsers that support:
- ES2020+ features
- Fetch API
- LocalStorage/SessionStorage
For older browser support, use appropriate transpilation with your bundler.
API Documentation
For complete API documentation, visit: https://dev.chainrails.io/api/v1
License
MIT
Support
For issues, questions, or feature requests, please visit: https://github.com/horuslabsio/chainrails-sdk
Changelog
See CHANGELOG.md for version history and updates.
