Ethereum/SDK和工具/JavaScript/TS

JavaScript/TypeScript工具

JavaScript为以太坊开发提供了几个强大的库,其中web3.js和ethers.js是最受欢迎的选择。

请注意!
嘿!友情提示:此页面旨在为您提供使用 Javascript/Typescript 请求的全面概述。有关实际代码示例,请查看我们的 API Methods documentation ,那里有所有支持语言的即用型示例!

# Web3.js

原始且使用最广泛的以太坊JavaScript API。

import Web3 from 'web3';
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');

// Get balance
const getBalance = async (address) => {
	const balance = await web3.eth.getBalance(address);
	const balanceInEth = web3.utils.fromWei(balance, 'ether');
	return balanceInEth;
};

// Send transaction
const sendTransaction = async (from, to, value) => {
	const tx = {
		from,
		to,
		value: web3.utils.toWei(value, 'ether'),
	};
	return await web3.eth.sendTransaction(tx);
};
  • GitHub: web3.js
  • 文档: web3js.readthedocs.io
  • 特性:
    • 完整的以太坊API覆盖
    • 广泛的社区支持
    • WebSocket支持
    • 合约交互
    • ENS支持

# Ethers.js

现代、完整且紧凑的库。

import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');

// Get balance
const getBalance = async (address) => {
	const balance = await provider.getBalance(address);
	return ethers.formatEther(balance);
};

// Send transaction
const sendTransaction = async (wallet, to, value) => {
	const tx = await wallet.sendTransaction({
		to,
		value: ethers.parseEther(value),
	});
	return await tx.wait();
};
  • GitHub: ethers.js
  • 文档: docs.ethers.org
  • 特性:
    • TypeScript支持
    • 更小的打包体积
    • 更好的安全特性
    • ENS支持
    • 广泛的测试

# TypeScript支持

两个库都提供了出色的TypeScript支持。使用TypeScript时,您可以获得:

  • 开箱即用的类型定义
  • 更好的IDE支持
  • 编译时错误检查
  • 增强的代码文档
import { BigNumber } from 'ethers';

interface TransactionData {
	to: string;
	value: BigNumber;
	gasLimit?: BigNumber;
}

const createTransaction = async (data: TransactionData) => {
	// Your implementation
};

# Node.js用法

这两个库在Node.js环境中都能无缝工作:

// Web3.js in Node.js
const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');

// Ethers.js in Node.js
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');

# 浏览器用法

对于浏览器环境,您可以使用webpack或vite等打包工具与任一库一起使用:

// Using ES modules
import { Web3 } from 'web3';
// or
import { ethers } from 'ethers';

// Using window.ethereum (MetaMask)
const provider = new ethers.BrowserProvider(window.ethereum);

另请参阅

帮助我们变得更好!
分享此页面并帮助我们为您创建更好的产品。