Package Exports
- @avalanche-sdk/client
- @avalanche-sdk/client/accounts
- @avalanche-sdk/client/chains
- @avalanche-sdk/client/methods
- @avalanche-sdk/client/methods/admin
- @avalanche-sdk/client/methods/cChain
- @avalanche-sdk/client/methods/health
- @avalanche-sdk/client/methods/index
- @avalanche-sdk/client/methods/info
- @avalanche-sdk/client/methods/pChain
- @avalanche-sdk/client/methods/public
- @avalanche-sdk/client/methods/wallet
- @avalanche-sdk/client/methods/wallet/cChain
- @avalanche-sdk/client/methods/wallet/pChain
- @avalanche-sdk/client/methods/wallet/xChain
- @avalanche-sdk/client/methods/xChain
- @avalanche-sdk/client/node
- @avalanche-sdk/client/nonce
- @avalanche-sdk/client/package.json
- @avalanche-sdk/client/serializable
- @avalanche-sdk/client/siwe
- @avalanche-sdk/client/utils
- @avalanche-sdk/client/window
Readme
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.
Installation
npm install @avalanche-sdk/client
# or
yarn add @avalanche-sdk/client
# or
pnpm add @avalanche-sdk/clientQuick Start
Avalanche Client Usage
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()Wallet Client Usage
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"
})Chain-Specific Wallet Operations
// 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"
})Features
- 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
Available Clients
Chain Clients
- P-Chain Client: Platform Chain operations
- X-Chain Client: Exchange Chain operations
- C-Chain Client: Contract Chain operations
API Clients
- 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
Wallet Clients
- 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
Configuration
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
})Transport Configuration
The SDK supports multiple transport types for connecting to Avalanche nodes. Each transport type has specific configuration options:
HTTP Transport (Recommended)
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-keyheader whenapiKeyis provided - Rate Limit Support: Automatically adds
rlTokenheader whenrlTokenis provided
WebSocket Transport
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
Custom Transport
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
Fallback Transport
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
Advanced Configuration Examples
Custom HTTP Headers and Timeouts
const client = createAvalancheClient({
chain: avalanche,
transport: {
type: "http",
config: {
fetchOptions: {
headers: {
"X-Custom-Header": "custom-value"
},
}
}
}
})Multiple Fallback Endpoints
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
}
}
})WebSocket with Custom Configuration
const client = createAvalancheClient({
chain: avalanche,
transport: {
type: "ws",
config: {
retryCount: 5,
retryDelay: 2000,
maxRetryDelay: 30000
}
}
})Transport Selection Guidelines
- 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
Environment Considerations
- 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
Exported Modules and Utilities
Main Exports
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'Account Management
import {
privateKeyToAvalancheAccount,
memonicsToAvalancheAccount,
hdKeyToAvalancheAccount,
privateKeyToXPAddress,
publicKeyToXPAddress,
// ... and more
} from '@avalanche-sdk/client/accounts'Chain Configurations
import {
avalanche,
avalancheFuji,
// ... and more
} from '@avalanche-sdk/client/chains'Methods
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'Utilities
import {
CB58ToHex,
hexToCB58,
getTxFromBytes,
getUnsignedTxFromBytes,
getUtxoFromBytes,
getUtxosForAddress,
// All viem utilities
formatEther,
parseEther,
keccak256,
// ... and many more
} from '@avalanche-sdk/client/utils'Additional Modules
// 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'Available Methods
P-Chain Methods
getBalance- Returns the balance of an address on the Platform Chain. DocsgetBlock- Gets a block by its ID. DocsgetBlockByHeight- Gets a block by its height. DocsgetBlockchainStatus- Returns the status of a blockchain. DocsgetBlockchains- Returns all the blockchains that exist (excluding the P-Chain). DocsgetCurrentSupply- Returns the current supply of AVAX in the system. DocsgetCurrentValidators- Returns the current validators of the given Subnet. DocsgetFeeConfig- Returns the fee configuration for the P-Chain. DocsgetFeeState- Returns the current fee state of the P-Chain. DocsgetHeight- Returns the height of the most recent block. DocsgetL1Validator- Returns information about an L1 validator. DocsgetMinStake- Returns the minimum amount of nAVAX required to validate the requested Subnet. DocsgetProposedHeight- Returns the proposed height of the most recent block. DocsgetRewardUTXOs- Returns the reward UTXOs for a list of address:utxo_index pairs. DocsgetStake- Returns the amount of nAVAX staked by a set of addresses. DocsgetStakingAssetID- Returns the assetID of the asset used for staking on the requested Subnet. DocsgetSubnet- Returns information about a Subnet. DocsgetSubnets- Returns all the blockchains that exist (excluding the P-Chain). DocsgetTimestamp- Returns the current timestamp of the P-Chain. DocsgetTotalStake- Returns the total amount staked on the requested Subnet. DocsgetTx- Returns the specified transaction. DocsgetTxStatus- Returns the status of the specified transaction. DocsgetUTXOs- Returns the UTXOs that reference a given address. DocsgetValidatorsAt- Returns the validators and their weights of a Subnet at the specified height. DocsissueTx- Issues a transaction to the Platform Chain. DocssampleValidators- Samples validators from the specified Subnet. DocsvalidatedBy- Gets the Subnet that validates a given blockchain. Docsvalidates- Gets the IDs of the blockchains a Subnet validates. Docs
X-Chain Methods
buildGenesis- Builds a genesis block for the X-Chain. DocsgetAllBalances- Returns all balances for a given address. DocsgetAssetDescription- Returns information about an asset. DocsgetBalance- Returns the balance of an asset held by an address. DocsgetBlock- Gets a block by its ID. DocsgetBlockByHeight- Gets a block by its height. DocsgetHeight- Returns the height of the most recent block. DocsgetTx- Returns the specified transaction. DocsgetTxFee- Returns the fee for the specified transaction. DocsgetTxStatus- Returns the status of the specified transaction. DocsgetUTXOs- Returns the UTXOs that reference a given address. DocsissueTx- Issues a transaction to the X-Chain. Docs
C-Chain Methods
getAtomicTx- Returns the specified atomic transaction. DocsgetAtomicTxStatus- Returns the status of the specified atomic transaction. DocsgetUTXOs- Returns the UTXOs that reference a given address. DocsissueTx- Issues a transaction to the C-Chain. Docs
Wallet Methods
getAccountPubKey- Get the public key of the current account. Docssend- Send a transaction using the wallet. DocssendXPTransaction- Sign and Send a transaction on X-Chain or P-Chain. DocssignXPMessage- Sign a message on X-Chain or P-Chain. DocssignXPTransaction- Sign a transaction on X-Chain or P-Chain. DocswaitForTxn- Wait for a transaction to be accepted. Docs
P-Chain Wallet Methods
prepareAddPermissionlessDelegatorTx- Prepare an add permissionless delegator transaction. DocsprepareAddPermissionlessValidatorTxn- Prepare an add permissionless validator transaction. DocsprepareAddSubnetValidatorTxn- Prepare an add subnet validator transaction. DocsprepareBaseTxn- Prepare a base transaction. DocsprepareConvertSubnetToL1Txn- Prepare a convert subnet to L1 transaction. DocsprepareCreateChainTxn- Prepare a create chain transaction. DocsprepareCreateSubnetTxn- Prepare a create subnet transaction. DocsprepareDisableL1ValidatorTxn- Prepare a disable L1 validator transaction. DocsprepareExportTxn- Prepare an export transaction. DocsprepareImportTxn- Prepare an import transaction. DocsprepareIncreaseL1ValidatorBalanceTxn- Prepare an increase L1 validator balance transaction. DocsprepareRegisterL1ValidatorTxn- Prepare a register L1 validator transaction. DocsprepareRemoveSubnetValidatorTxn- Prepare a remove subnet validator transaction. DocsprepareSetL1ValidatorWeightTxn- Prepare a set L1 validator weight transaction. Docs
X-Chain Wallet Methods
prepareBaseTxn- Prepare a base transaction for the X-Chain. DocsprepareExportTxn- Prepare an export transaction for the X-Chain. DocsprepareImportTxn- Prepare an import transaction for the X-Chain. Docs
C-Chain Wallet Methods
prepareExportTxn- Prepare an export transaction from C-Chain to another chain. DocsprepareImportTxn- Prepare an import transaction from another chain to C-Chain. Docs
Public Methods
baseFee- Returns the base fee for the next block. DocsgetChainConfig- Returns the chain configuration. DocsmaxPriorityFeePerGas- Returns the maximum priority fee per gas. DocsfeeConfig- Returns the fee configuration for the specified block. DocsgetActiveRulesAt- Returns the active rules at the specified timestamp. Docs
Admin Methods
alias- Assign an API endpoint an alias. DocsaliasChain- Give a blockchain an alias. DocsgetChainAliases- Returns the aliases of the chain. DocsgetLoggerLevel- Returns log and display levels of loggers. DocsloadVMs- Dynamically loads any virtual machines installed on the node as plugins. DocslockProfile- Writes a profile of mutex statistics to lock.profile. DocsmemoryProfile- Writes a memory profile to mem.profile. DocssetLoggerLevel- Sets log and display levels of loggers. DocsstartCPUProfiler- Start profiling the CPU utilization of the node. DocsstopCPUProfiler- Stop the CPU profile that was previously started. Docs
Info Methods
acps- Returns peer preferences for Avalanche Community Proposals (ACPs). DocsgetBlockchainID- Given a blockchain's alias, get its ID. DocsgetNetworkID- Get the ID of the network this node is participating in. DocsgetNetworkName- Get the name of the network this node is participating in. DocsgetNodeID- Get the ID, the BLS key, and the proof of possession of this node. DocsgetNodeIP- Get the IP of this node. DocsgetNodeVersion- Get the version of this node. DocsgetTxFee- Get the transaction fee for the specified transaction type. DocsgetVMs- Get the virtual machines supported by this node. DocsisBootstrapped- Check whether a given chain is done bootstrapping. Docspeers- Get a description of peer connections. Docsuptime- Returns the network's observed uptime of this node. Docsupgrades- Returns the upgrade history and configuration of the network. Docs
Health Methods
health- Returns the last set of health check results. Docsliveness- Returns healthy once the endpoint is available. Docsreadiness- Returns healthy once the node has finished initializing. Docs
Index Methods
getContainerByID- Get container by ID. DocsgetContainerByIndex- Get container by index. DocsgetContainerRange- Get containers by index range. DocsgetIndex- Get the index of a container. DocsgetLastAccepted- Get the last accepted container. DocsisAccepted- Returns true if the container is in this index. Docs
Examples
Note: Make sure to create your own
.envfile by copying the.env.examplefile and updating the values. You'll also need to modify theconfig.tsfile to point to your.envfile path. By default, the examples use the values from.env.example, and the test addresses mentioned in the examples as comments (like0x76Dd3d7b2f635c2547B861e55aE8A374E587742DandX-fuji19fc97zn3mzmwr827j4d3n45refkksgms4y2yzz) are derived from the private key values in that file.
Check out the examples folder for comprehensive usage examples:
Basic Examples
sendAvax.ts- Basic example of sending AVAX using the SDK
Primary Network Transaction Examples
The prepare-primary-network-txns folder contains examples for preparing various types of transactions:
Cross-Chain Transfer Examples
transfer-avax-from-x-chain-to-p-chain.ts- Transfer AVAX from X-Chain to P-Chaintransfer-avax-from-p-chain-to-x-chain.ts- Transfer AVAX from P-Chain to X-Chaintransfer-avax-from-x-chain-to-c-chain.ts- Transfer AVAX from X-Chain to C-Chaintransfer-avax-from-c-chain-to-x-chain.ts- Transfer AVAX from C-Chain to X-Chaintransfer-avax-from-p-chain-to-c-chain.ts- Transfer AVAX from P-Chain to C-Chaintransfer-avax-from-c-chain-to-p-chain.ts- Transfer AVAX from C-Chain to P-Chain
X-Chain Transaction Examples
exportTx.ts- Prepare X-Chain export transactionimportTx.ts- Prepare X-Chain import transaction
P-Chain Transaction Examples
addSubnetValidatorTx.ts- Add subnet validator transactionbaseTx.ts- Base transaction exampleconvertSubnetToL1Tx.ts- Convert subnet to L1 transactioncreateChainTx.ts- Create chain transactioncreateSubnetTx.ts- Create subnet transactionexportTx.ts- Prepare P-Chain export transactionimportTx.ts- Prepare P-Chain import transactionremoveSubnetValidatorTx.ts- Remove subnet validator transaction
C-Chain Transaction Examples
exportTx.ts- Prepare C-Chain export transactionimportTx.ts- Prepare C-Chain import transaction
For more detailed information about each example, see the examples README.
Contributing
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.
License
This project is licensed under the BSD 3-Clause License - see the [LICENSE]../(LICENSE) file for details.
Support
If you encounter any issues or have questions, please:
- Check the documentation
- Open an issue
- Join our community channels for help