Extended Ethers.js SDK for Alchemy APIs providing comprehensive blockchain functionality, NFT management, and multi-chain operations
npx @tessl/cli install tessl/npm-alchemy-sdk@3.6.0The Alchemy SDK is a comprehensive TypeScript library that extends Ethers.js to provide enhanced functionality for interacting with blockchains through Alchemy's infrastructure. It supports 70+ blockchain networks including Ethereum, Polygon, Optimism, Arbitrum, Base, and many others, offering standardized APIs for core blockchain operations, NFT management, WebSocket subscriptions, transaction simulation, webhook notifications, and debugging capabilities.
npm install alchemy-sdkimport { Alchemy, Network } from "alchemy-sdk";For CommonJS:
const { Alchemy, Network } = require("alchemy-sdk");Additional imports for specific functionality:
import {
Alchemy,
Network,
Wallet,
Contract,
ContractFactory,
Utils,
BigNumber,
fromHex,
toHex,
isHex,
setLogLevel,
LogLevel
} from "alchemy-sdk";import { Alchemy, Network } from "alchemy-sdk";
// Initialize SDK
const alchemy = new Alchemy({
apiKey: "your-api-key",
network: Network.ETH_MAINNET,
});
// Get latest block number
const blockNumber = await alchemy.core.getBlockNumber();
// Get token balances for an address
const balances = await alchemy.core.getTokenBalances("0x...");
// Get NFTs owned by an address
const nfts = await alchemy.nft.getNftsForOwner("0x...");
// Subscribe to new blocks via WebSocket
alchemy.ws.on("block", (blockNumber) => {
console.log("New block:", blockNumber);
});The Alchemy SDK is organized around several key components:
Alchemy class provides access to all functionality through specialized namespacescore, nft, transact, notify, debug, prices, portfolio, ws)Wallet, Contract, and ContractFactory classes that extend Ethers.js with Alchemy featuresEssential blockchain functionality including block and transaction queries, token operations, and enhanced APIs for asset transfers and metadata.
interface CoreNamespace {
getBlockNumber(): Promise<number>;
getBlock(blockHashOrTag: string | number): Promise<Block>;
getTransaction(transactionHash: string): Promise<TransactionResponse>;
getTokenBalances(address: string, tokenAddresses?: string[]): Promise<TokenBalancesResponse>;
getTokenMetadata(address: string): Promise<TokenMetadata>;
getAssetTransfers(params: AssetTransfersParams): Promise<AssetTransfersResponse>;
}Comprehensive NFT functionality including metadata queries, ownership tracking, sales history, rarity computation, and spam detection.
interface NftNamespace {
getNftMetadata(contractAddress: string, tokenId: string): Promise<Nft>;
getNftsForOwner(owner: string, options?: GetNftsForOwnerOptions): Promise<OwnedNftsResponse>;
getNftSales(options?: GetNftSalesOptions): Promise<GetNftSalesResponse>;
getFloorPrice(contractAddress: string): Promise<GetFloorPriceResponse>;
computeRarity(contractAddress: string, tokenId: string): Promise<ComputeRarityResponse>;
isSpamContract(contractAddress: string): Promise<IsSpamContractResponse>;
}Transaction simulation, private transactions, gas optimization, and asset change analysis for DeFi operations.
interface TransactNamespace {
simulateExecution(request: TransactionRequest): Promise<SimulateExecutionResponse>;
simulateAssetChanges(request: TransactionRequest): Promise<SimulateAssetChangesResponse>;
sendPrivateTransaction(request: TransactionRequest): Promise<string>;
getMaxPriorityFeePerGas(): Promise<string>;
}Real-time webhook system for monitoring blockchain events including address activity, mined transactions, dropped transactions, and custom events.
interface NotifyNamespace {
getAllWebhooks(): Promise<Webhook[]>;
createWebhook(params: WebhookParams): Promise<Webhook>;
updateWebhook(webhookId: string, params: WebhookParams): Promise<void>;
deleteWebhook(webhookId: string): Promise<void>;
getAddresses(webhookId: string): Promise<string[]>;
addAddresses(webhookId: string, addresses: string[]): Promise<void>;
}Advanced debugging capabilities with transaction tracing, call tracing, and block analysis for development and troubleshooting.
interface DebugNamespace {
traceTransaction(transactionHash: string, options?: DebugTracingOptions): Promise<DebugTransaction>;
traceCall(request: TransactionRequest, options?: DebugTracingOptions): Promise<DebugCallTrace>;
traceBlock(blockNumber: number): Promise<DebugTransaction[]>;
}Current and historical token price data with multi-chain support for portfolio valuation and analytics.
interface PricesNamespace {
getTokenPrices(params: GetTokenPricesParams): Promise<GetTokenPricesResponse>;
getHistoricalPrices(params: GetHistoricalPricesParams): Promise<GetHistoricalPricesResponse>;
}Multi-chain portfolio and asset viewing with token balances, transaction history, and cross-chain analytics.
interface PortfolioNamespace {
getTokenBalances(owner: string, options?: GetTokenBalancesOptions): Promise<GetTokenBalancesResponse>;
getTokensForOwner(owner: string, options?: GetTokensForOwnerOptions): Promise<GetTokensForOwnerResponse>;
getTransactions(params: GetTransactionsParams): Promise<GetTransactionsResponse>;
}Real-time event subscriptions with automatic reconnection, filtering, and comprehensive event types for live blockchain monitoring.
interface WebSocketNamespace {
on(eventName: AlchemyEventType, listener: AlchemyEventListener): this;
off(eventName: AlchemyEventType, listener: AlchemyEventListener): this;
removeAllListeners(eventName?: AlchemyEventType): this;
}Collection of utility functions for hex conversion, string operations, hashing, and data manipulation from Ethers.js ecosystem.
// Hex conversion utilities
function fromHex(hexString: string): number;
function toHex(num: number): string;
function isHex(possibleHexString: string): boolean;
// Logging control
function setLogLevel(level: LogLevel): void;
// Utils namespace containing Ethers.js utilities
namespace Utils {
// Hash utilities
function dnsEncode(name: string): string;
function hashMessage(message: string | Uint8Array): string;
function id(text: string): string;
function isValidName(name: string): boolean;
function namehash(name: string): string;
// Bytes utilities
function arrayify(value: BytesLike): Uint8Array;
function concat(items: BytesLike[]): Uint8Array;
function hexConcat(items: BytesLike[]): string;
function hexDataSlice(data: BytesLike, offset: number, endOffset?: number): string;
function hexDataLength(data: BytesLike): number;
function hexlify(value: BytesLike | number | bigint): string;
function hexStripZeros(value: BytesLike): string;
function hexValue(value: BytesLike | number | bigint): string;
function hexZeroPad(value: BytesLike, length: number): string;
function isBytes(value: any): value is Uint8Array;
function isBytesLike(value: any): value is BytesLike;
function isHexString(value: any, length?: number): boolean;
function joinSignature(signature: SignatureLike): string;
function zeroPad(value: BytesLike, length: number): Uint8Array;
function splitSignature(signature: SignatureLike): Signature;
function stripZeros(value: BytesLike): Uint8Array;
// Units utilities
function formatEther(wei: BigNumberish): string;
function parseEther(ether: string): BigNumber;
function parseUnits(value: string, unitType?: string | number): BigNumber;
function formatUnits(value: BigNumberish, unitType?: string | number): string;
// String utilities
function toUtf8Bytes(str: string): Uint8Array;
function toUtf8String(bytes: BytesLike): string;
// ABI utilities
class Interface {
constructor(fragments: string | ReadonlyArray<Fragment | JsonFragment | string>);
}
}Main SDK client providing access to all functionality through namespaces.
class Alchemy {
constructor(config?: AlchemySettings);
readonly config: AlchemyConfig;
readonly core: CoreNamespace;
readonly nft: NftNamespace;
readonly transact: TransactNamespace;
readonly notify: NotifyNamespace;
readonly debug: DebugNamespace;
readonly prices: PricesNamespace;
readonly portfolio: PortfolioNamespace;
readonly ws: WebSocketNamespace;
}
class AlchemyConfig {
readonly apiKey: string;
readonly network: Network;
readonly maxRetries: number;
readonly requestTimeout: number;
constructor(config?: AlchemySettings);
}
interface AlchemySettings {
apiKey?: string;
network?: Network;
maxRetries?: number;
requestTimeout?: number;
}Enhanced Ethers.js wallet with Alchemy provider integration.
class Wallet {
constructor(privateKey: string, alchemy: Alchemy);
sendTransaction(transaction: TransactionRequest): Promise<TransactionResponse>;
signTransaction(transaction: TransactionRequest): Promise<string>;
connect(provider: AlchemyProvider): Wallet;
}Enhanced contract wrappers with Alchemy provider features.
class Contract {
constructor(addressOrName: string, contractInterface: Interface, signerOrProvider: Signer | Provider);
}
class ContractFactory {
constructor(contractInterface: Interface, bytecode: string, signer: Signer);
deploy(...args: any[]): Promise<Contract>;
}/**
* Convert hex string to number
* @param hexString - Hex string to convert
* @returns Converted number
*/
function fromHex(hexString: string): number;
/**
* Convert number to hex string
* @param num - Number to convert to hex
* @returns Hex string representation
*/
function toHex(num: number): string;
/**
* Check if string is valid hex format
* @param possibleHexString - String to validate
* @returns True if valid hex, false otherwise
*/
function isHex(possibleHexString: string): boolean;/**
* Set SDK logging level
* @param level - Log level to set
*/
function setLogLevel(level: LogLevel): void;
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";Core types used throughout the SDK from the Ethers.js ecosystem:
// Bytes and hex types
type BytesLike = ArrayLike<number> | string;
type BigNumberish = string | number | BigNumber;
// Signature types
interface SignatureLike {
r: string;
s: string;
v?: number;
yParity?: number;
compact?: string;
}
interface Signature {
r: string;
s: string;
v: number;
yParity?: number;
recoveryParam?: number;
}
// ABI types
type Fragment = EventFragment | FunctionFragment | ConstructorFragment;
type JsonFragment = JsonFragmentType;
interface EventFragment {
readonly type: "event";
readonly name: string;
readonly inputs: ReadonlyArray<ParamType>;
readonly anonymous: boolean;
}
interface FunctionFragment {
readonly type: "function";
readonly name: string;
readonly inputs: ReadonlyArray<ParamType>;
readonly outputs: ReadonlyArray<ParamType>;
readonly stateMutability: string;
}
interface ConstructorFragment {
readonly type: "constructor";
readonly inputs: ReadonlyArray<ParamType>;
readonly stateMutability: string;
}
interface ParamType {
readonly name: string;
readonly type: string;
readonly baseType: string;
readonly indexed?: boolean;
readonly components?: ReadonlyArray<ParamType>;
readonly arrayLength?: number;
readonly arrayChildren?: ParamType;
}
interface JsonFragmentType {
readonly name?: string;
readonly type?: string;
readonly inputs?: ReadonlyArray<JsonFragmentType>;
readonly outputs?: ReadonlyArray<JsonFragmentType>;
readonly anonymous?: boolean;
readonly payable?: boolean;
readonly constant?: boolean;
readonly stateMutability?: string;
}
// Provider types
interface Signer {
getAddress(): Promise<string>;
signMessage(message: string | Uint8Array): Promise<string>;
signTransaction(transaction: TransactionRequest): Promise<string>;
}
interface Provider {
getNetwork(): Promise<Network>;
getBlockNumber(): Promise<number>;
getBalance(address: string, blockTag?: BlockTag): Promise<BigNumber>;
}
// Core transaction types
interface TransactionRequest {
to?: string;
from?: string;
value?: BigNumberish;
gasLimit?: BigNumberish;
gasPrice?: BigNumberish;
data?: BytesLike;
nonce?: number;
type?: number;
accessList?: AccessListish;
maxFeePerGas?: BigNumberish;
maxPriorityFeePerGas?: BigNumberish;
}
interface TransactionResponse extends TransactionRequest {
hash: string;
blockNumber?: number;
blockHash?: string;
timestamp?: number;
confirmations: number;
from: string;
wait(confirmations?: number): Promise<TransactionReceipt>;
}
type AccessListish = AccessList | Array<[string, Array<string>]> | Record<string, Array<string>>;
interface AccessList extends Array<{ address: string; storageKeys: Array<string> }> {}
type BlockTag = string | number;The SDK supports 70+ blockchain networks through the Network enum:
enum Network {
ETH_MAINNET = "eth-mainnet",
ETH_SEPOLIA = "eth-sepolia",
ETH_HOLESKY = "eth-holesky",
MATIC_MAINNET = "matic-mainnet",
MATIC_MUMBAI = "matic-mumbai",
MATIC_AMOY = "matic-amoy",
OPT_MAINNET = "opt-mainnet",
OPT_SEPOLIA = "opt-sepolia",
ARB_MAINNET = "arb-mainnet",
ARB_SEPOLIA = "arb-sepolia",
BASE_MAINNET = "base-mainnet",
BASE_SEPOLIA = "base-sepolia",
// ... and 50+ more networks
}The SDK provides comprehensive error handling with specific error types:
interface AlchemyError extends Error {
code?: number;
reason?: string;
method?: string;
url?: string;
}The SDK includes extensive TypeScript support with 300+ interfaces, enums, and types organized into logical groups:
All API methods are fully typed with detailed parameter and return type definitions for excellent developer experience and IDE support.