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"
})
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:
fetchOptions.headers
x-glacier-api-key
header when apiKey
is providedrlToken
header when rlToken
is providedconst 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:
const client = createAvalancheClient({
chain: avalanche,
transport: {
type: "custom",
provider: window.avalanche, // Custom provider implementation
config: {
// Custom transport configuration
}
}
})
Custom Transport Features:
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:
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
}
}
})
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'
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. DocsbuildGenesis
- 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. DocsgetAtomicTx
- 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. DocsgetAccountPubKey
- 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. DocsprepareAddPermissionlessDelegatorTx
- 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. DocsprepareBaseTxn
- 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. DocsprepareExportTxn
- Prepare an export transaction from C-Chain to another chain. DocsprepareImportTxn
- Prepare an import transaction from another chain to C-Chain. DocsbaseFee
- 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. Docsalias
- 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. Docsacps
- 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. Docshealth
- 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. DocsgetContainerByID
- 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. DocsNote: Make sure to create your own
.env
file by copying the.env.example
file and updating the values. You'll also need to modify theconfig.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 (like0x76Dd3d7b2f635c2547B861e55aE8A374E587742D
andX-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 SDKThe prepare-primary-network-txns
folder contains examples for preparing various types of transactions:
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-ChainexportTx.ts
- Prepare X-Chain export transactionimportTx.ts
- Prepare X-Chain import transactionaddSubnetValidatorTx.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 transactionexportTx.ts
- Prepare C-Chain export transactionimportTx.ts
- Prepare C-Chain import transactionFor 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: