# `@xchainjs/xchain-ethereum`

发布: (2025年12月20日 GMT+8 00:42)
3 min read
原文: Dev.to

Source: Dev.to

包概览

  • Ethereum(EVM)客户端实现
  • 地址生成与校验
  • 余额与交易历史查询
  • 交易创建、签名与广播
  • Gas 与费用估算工具

功能特性

  • ✅ TypeScript 优先的 Ethereum SDK
  • ✅ 支持 EVM 兼容链
  • ✅ 从助记词派生地址
  • ✅ 地址校验
  • ✅ 余额与交易历史查询
  • ✅ ETH 与 ERC‑20 转账
  • ✅ Gas 价格与费用估算
  • ✅ 与其他 XChainJS 客户端保持统一的 API

工作原理

  • 基于 ethers.js 与 Ethereum RPC 交互
  • 使用共享的 XChainJS 抽象和类型
  • 设计上与其他链客户端(BTC、LTC、THORChain 等)保持一致

核心依赖

  • ethers
  • @xchainjs/xchain-client
  • @xchainjs/xchain-util

文档

  • 工作原理:
  • 使用方法:

安装

安装包

npm install @xchainjs/xchain-ethereum

同行依赖

npm install @xchainjs/xchain-client @xchainjs/xchain-util ethers

基本使用示例

创建 Ethereum 客户端

import { Client } from '@xchainjs/xchain-ethereum'
import { Network } from '@xchainjs/xchain-client'

const phrase = 'your mnemonic phrase here'

const ethClient = new Client({
  phrase,
  network: Network.Mainnet,
})

获取地址并校验

const address = ethClient.getAddress()
console.log('Address:', address)

const isValid = ethClient.validateAddress(address)
console.log('Valid:', isValid)

获取余额

const balances = await ethClient.getBalance(address)
console.log(balances)

余额以基础单位返回,可使用 @xchainjs/xchain-util 中的工具进行转换。

转账 ETH

import { assetAmount, assetToBase } from '@xchainjs/xchain-util'

const recipient = '0xRecipientAddressHere'
const amount = assetToBase(assetAmount(0.01))

const txHash = await ethClient.transfer({
  recipient,
  amount,
  memo: 'ETH transfer',
})

console.log('TX hash:', txHash)
console.log('Explorer:', ethClient.getExplorerTxUrl(txHash))

转账 ERC‑20 代币

const tokenAddress = '0xTokenContractAddress'
const txHash = await ethClient.transfer({
  recipient,
  amount,
  asset: {
    chain: 'ETH',
    symbol: `USDT-${tokenAddress}`,
    ticker: 'USDT',
  },
})

获取交易数据

const txHash = '0xTransactionHash'
const txData = await ethClient.getTransactionData(txHash)
console.log(txData)

何时使用此包

如果您正在:

  • 构建加密钱包
  • 与 Ethereum 或其他 EVM 兼容链交互
  • 处理 ETH 与 ERC‑20 转账
  • 构建 DeFi 前端或后端
  • 使用 XChainJS 开发多链应用

则可以使用 @xchainjs/xchain-ethereum

总结

@xchainjs/xchain-ethereum 为 XChainJS 生态系统提供了 干净、统一、可直接用于生产 的 Ethereum 客户端。它让开发者能够使用与其他区块链相同的抽象来操作 Ethereum,简化了 跨链 应用的开发。

Back to Blog

相关文章

阅读更多 »

# `@xchainjs/xchain-litecoin`

Litecoin LTC 客户端和 XChainJS 实用工具:轻量级 TypeScript SDK,用于构建跨链钱包、加密支付流程和 DeFi 工具。

Vue + XChainJS 示例

Vue + XChainJS 示例的封面图片 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads...

# XChainJS 检查交易示例

此示例演示如何使用 XChainJS 检查和跟踪区块链交易。实时演示与源代码 - 实时演示 CodeSandbox: - 源代码 GitHub:...