Avalanche SDK Client
    Preparing search index...

    Avalanche SDK Client

    A TypeScript SDK for interacting with the Avalanche network through JSON-RPC APIs. This SDK provides a comprehensive set of tools to interact with all Avalanche chains (P-Chain, X-Chain, C-Chain) and various APIs, including wallet functionality for transaction signing and management.

    npm install @avalanche-sdk/client
    # or
    yarn add @avalanche-sdk/client
    # or
    pnpm add @avalanche-sdk/client
    import { createAvalancheClient } from '@avalanche-sdk/client'
    import { avalanche } from '@avalanche-sdk/client/chains'

    // Create an Avalanche client
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "http",
    },
    })

    // Access different chain clients
    const pChainClient = client.pChain
    const xChainClient = client.xChain
    const cChainClient = client.cChain

    // Access API clients
    const adminClient = client.admin
    const infoClient = client.info
    const healthClient = client.health
    const indexPChainBlockClient = client.indexPChainBlock

    // Example: Get the latest block number
    const blockNumber = await pChainClient.getBlockNumber()

    // Example: Get base fee
    const baseFee = await client.getBaseFee()
    import { createAvalancheWalletClient, privateKeyToAvalancheAccount } from '@avalanche-sdk/client'
    import { avalanche } from '@avalanche-sdk/client/chains'

    // Create an account from private key
    const account = privateKeyToAvalancheAccount("0x1234567890123456789012345678901234567890123456789012345678901234")

    // Get P chain Address and Evm Address
    const evmAddress = account.getEVMAddress()
    const pchainAddress = account.getXPAddress("P", "fuji")

    // Create a wallet client
    const walletClient = createAvalancheWalletClient({
    account,
    chain: avalanche,
    transport: {
    type: "http",
    },
    })

    // Prepare a txn request
    const xChainExportTxnRequest = await walletClient.xChain.prepareExportTxn({
    exportedOutputs: [
    {
    addresses: [account.getXPAddress("X", "fuji")], // X-fuji19fc97zn3mzmwr827j4d3n45refkksgms4y2yzz
    amount: 0.001,
    },
    ],
    destinationChain: "P",
    });

    // Send an XP transaction
    const result = await walletClient.sendXPTransaction(xChainExportTxnRequest)

    // Sign a message
    const signedMessage = await walletClient.signXPMessage({
    message: "Hello Avalanche",
    })

    // Get account public key
    const pubKey = await walletClient.getAccountPubKey()

    // Wait for transaction confirmation
    await walletClient.waitForTxn({
    txID: "2QouvMUbQ6oy7yQ9tLvL3L8tGQG2QK1wJ1q1wJ1q1wJ1q1wJ1q1wJ1q1wJ1",
    chainAlias: "X"
    })
    // P-Chain wallet operations
    const pChainWallet = walletClient.pChain

    // Prepare add validator transaction
    const validatorTx = await pChainWallet.prepareAddPermissionlessValidatorTxn({
    nodeId: "NodeID-7Xhw2mDxuDS44j42TCB6U5579esbSt3Lg",
    stakeInAvax: 1,
    end: 1716441600,
    rewardAddresses: ["P-fuji19fc97zn3mzmwr827j4d3n45refkksgms4y2yzz"],
    threshold: 1,
    publicKey: "0x1234567890123456789012345678901234567890",
    signature: "0x1234567890123456789012345678901234567890",
    locktime: 1716441600,
    delegatorRewardPercentage: 2.5,
    delegatorRewardAddresses: ["P-fuji19fc97zn3mzmwr827j4d3n45refkksgms4y2yzz"],
    })

    // X-Chain wallet operations
    const xChainWallet = walletClient.xChain

    // Prepare base transaction
    const baseTx = await xChainWallet.prepareBaseTxn({
    outputs: [{
    addresses: ["X-avax18jma8ppw3nhx5r4ap8clazz0dps7rv5ukulre5"],
    amount: 1000000000, // 1 AVAX
    }],
    })

    // C-Chain wallet operations
    const cChainWallet = walletClient.cChain

    // Prepare export transaction
    const exportTx = await cChainWallet.prepareExportTxn({
    to: "P-fuji1j2zllfqv4mgg7ytn9m2u2x0q3h3jqkzq8q8q8q8",
    amount: "1000000000000000000", // 1 AVAX in wei
    destinationChain: "X"
    })
    • Multi-Chain Support: Interact with all Avalanche chains:
      • P-Chain (Platform Chain)
      • X-Chain (Exchange Chain)
      • C-Chain (Contract Chain)
    • Wallet Functionality: Complete wallet operations including:
      • Transaction signing and sending
      • Message signing
      • Account management
      • Chain-specific transaction preparation
    • API Clients:
      • Admin API
      • Info API
      • Health API
      • Index API
    • TypeScript Support: Full TypeScript support with type definitions
    • Modular Design: Access specific functionality through dedicated clients
    • P-Chain Client: Platform Chain operations
    • X-Chain Client: Exchange Chain operations
    • C-Chain Client: Contract Chain operations
    • Admin Client: Administrative operations
    • Info Client: Network information
    • Health Client: Health check endpoints
    • Index Clients:
      • Index P-Chain Block
      • Index C-Chain Block
      • Index X-Chain Block
      • Index X-Chain Transaction
    • Avalanche Wallet Client: General wallet operations
    • P-Chain Wallet Client: P-Chain specific wallet operations
    • X-Chain Wallet Client: X-Chain specific wallet operations
    • C-Chain Wallet Client: C-Chain specific wallet operations

    The SDK can be configured with various options:

    const client = createAvalancheClient({
    chain: avalanche, // Chain configuration
    transport: {
    type: "<transportType>", // Transport type
    url: "<url>",
    config: {
    // Transport-specific configuration
    }
    },
    apiKey: "", // Optional API key
    rlToken: "", // Optional rate limit token
    })

    The SDK supports multiple transport types for connecting to Avalanche nodes. Each transport type has specific configuration options:

    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "http",
    url: "https://api.avax.network/ext/bc/C/rpc", // Optional custom RPC URL
    config: {
    // HTTP-specific configuration
    fetchOptions: {
    headers: {
    "Custom-Header": "value"
    },
    }
    retryCount: 3,
    retryDelay: 1000,
    timeout: 5000
    }
    }
    })

    HTTP Transport Features:

    • Automatic URL Resolution: If no URL is provided, uses the chain's default RPC endpoint
    • Custom Headers: Support for custom HTTP headers via fetchOptions.headers
    • API Key Support: Automatically adds x-glacier-api-key header when apiKey is provided
    • Rate Limit Support: Automatically adds rlToken header when rlToken is provided
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "ws",
    url: "wss://api.avax.network/ext/bc/C/ws", // Optional custom WebSocket URL
    config: {
    // WebSocket-specific configuration
    retryCount: 3,
    retryDelay: 1000
    }
    }
    })

    WebSocket Transport Features:

    • Real-time Updates: Supports WebSocket connections for live data
    • Automatic Reconnection: Built-in retry logic with configurable retry count and delay
    • Event-driven: Ideal for subscribing to blockchain events and real-time updates
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "custom",
    provider: window.avalanche, // Custom provider implementation
    config: {
    // Custom transport configuration
    }
    }
    })

    Custom Transport Features:

    • Provider Integration: Integrate with custom RPC providers or middleware
    • Flexible Configuration: Full control over transport behavior
    • Wallet Support: Special handling for wallet clients
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "fallback",
    transports: [
    { type: "http", url: "https://primary-rpc.com" },
    { type: "http", url: "https://backup-rpc.com" }
    ],
    config: {
    // Fallback configuration
    retryCount: 3,
    retryDelay: 1000
    }
    }
    })

    Fallback Transport Features:

    • High Availability: Automatic failover between multiple RPC endpoints
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "http",
    config: {
    fetchOptions: {
    headers: {
    "X-Custom-Header": "custom-value"
    },
    }
    }
    }
    })
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "fallback",
    transports: [
    { type: "http", url: "https://api.avax.network/ext/bc/C/rpc" },
    { type: "http", url: "https://rpc.ankr.com/avalanche" },
    { type: "http", url: "https://avalanche.public-rpc.com" }
    ],
    config: {
    retryCount: 5,
    retryDelay: 2000
    }
    }
    })
    const client = createAvalancheClient({
    chain: avalanche,
    transport: {
    type: "ws",
    config: {
    retryCount: 5,
    retryDelay: 2000,
    maxRetryDelay: 30000
    }
    }
    })
    • HTTP Transport: Best for most use cases, simple configuration, wide compatibility
    • WebSocket Transport: Ideal for real-time applications, event subscriptions, live updates
    • Custom Transport: Use when integrating with specific providers or middleware
    • Fallback Transport: Recommended for production applications requiring high availability
    • Browser: HTTP and WebSocket transports are fully supported
    • Node.js: All transport types are supported
    • Mobile: HTTP transport is recommended for mobile applications
    • Production: Consider using fallback transport with multiple RPC endpoints for reliability

    The SDK exports all viem utilities and types, plus Avalanche-specific functionality:

    import { 
    createAvalancheClient,
    createAvalancheWalletClient,
    // All viem exports
    createClient,
    createPublicClient,
    createWalletClient,
    // ... and many more
    } from '@avalanche-sdk/client'
    import { 
    privateKeyToAvalancheAccount,
    memonicsToAvalancheAccount,
    hdKeyToAvalancheAccount,
    privateKeyToXPAddress,
    publicKeyToXPAddress,
    // ... and more
    } from '@avalanche-sdk/client/accounts'
    import { 
    avalanche,
    avalancheFuji,
    // ... and more
    } from '@avalanche-sdk/client/chains'

    Access specific method categories:

    // P-Chain methods
    import { /* P-Chain methods */ } from '@avalanche-sdk/client/methods/pChain'

    // X-Chain methods
    import { /* X-Chain methods */ } from '@avalanche-sdk/client/methods/xChain'

    // C-Chain methods
    import { /* C-Chain methods */ } from '@avalanche-sdk/client/methods/cChain'

    // Wallet methods
    import { /* Wallet methods */ } from '@avalanche-sdk/client/methods/wallet'

    // Public methods
    import { /* Public methods */ } from '@avalanche-sdk/client/methods/public'

    // Admin methods
    import { /* Admin methods */ } from '@avalanche-sdk/client/methods/admin'

    // Info methods
    import { /* Info methods */ } from '@avalanche-sdk/client/methods/info'

    // Health methods
    import { /* Health methods */ } from '@avalanche-sdk/client/methods/health'

    // Index methods
    import { /* Index methods */ } from '@avalanche-sdk/client/methods/index'
    import { 
    CB58ToHex,
    hexToCB58,
    getTxFromBytes,
    getUnsignedTxFromBytes,
    getUtxoFromBytes,
    getUtxosForAddress,
    // All viem utilities
    formatEther,
    parseEther,
    keccak256,
    // ... and many more
    } from '@avalanche-sdk/client/utils'
    // Node utilities
    import { /* Node utilities */ } from '@avalanche-sdk/client/node'

    // Nonce management
    import { /* Nonce utilities */ } from '@avalanche-sdk/client/nonce'

    // Serializable utilities
    import { /* Serializable utilities */ } from '@avalanche-sdk/client/serializable'

    // SIWE (Sign-In with Ethereum)
    import { /* SIWE utilities */ } from '@avalanche-sdk/client/siwe'

    // Window utilities
    import { /* Window utilities */ } from '@avalanche-sdk/client/window'
    • acps - Returns peer preferences for Avalanche Community Proposals (ACPs). Docs
    • getBlockchainID - Given a blockchain's alias, get its ID. Docs
    • getNetworkID - Get the ID of the network this node is participating in. Docs
    • getNetworkName - Get the name of the network this node is participating in. Docs
    • getNodeID - Get the ID, the BLS key, and the proof of possession of this node. Docs
    • getNodeIP - Get the IP of this node. Docs
    • getNodeVersion - Get the version of this node. Docs
    • getTxFee - Get the transaction fee for the specified transaction type. Docs
    • getVMs - Get the virtual machines supported by this node. Docs
    • isBootstrapped - Check whether a given chain is done bootstrapping. Docs
    • peers - Get a description of peer connections. Docs
    • uptime - Returns the network's observed uptime of this node. Docs
    • upgrades - Returns the upgrade history and configuration of the network. Docs
    • health - Returns the last set of health check results. Docs
    • liveness - Returns healthy once the endpoint is available. Docs
    • readiness - Returns healthy once the node has finished initializing. Docs

    Note: Make sure to create your own .env file by copying the .env.example file and updating the values. You'll also need to modify the config.ts file to point to your .env file path. By default, the examples use the values from .env.example, and the test addresses mentioned in the examples as comments (like 0x76Dd3d7b2f635c2547B861e55aE8A374E587742D and X-fuji19fc97zn3mzmwr827j4d3n45refkksgms4y2yzz) are derived from the private key values in that file.

    Check out the examples folder for comprehensive usage examples:

    • sendAvax.ts - Basic example of sending AVAX using the SDK

    The prepare-primary-network-txns folder contains examples for preparing various types of transactions:

    For more detailed information about each example, see the examples README.

    Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

    This project is licensed - see the LICENSE file for details.

    If you encounter any issues or have questions, please:

    1. Check the documentation
    2. Open an issue
    3. Join our community channels for help