以太坊API接口编写实验报告
xwhb
2026-09-21
实验目的
- 掌握以太坊API接口的基本原理及JSON-RPC协议规范;
- 学会使用Web3.js库与以太坊节点进行交互;
- 实现通过API接口完成账户查询、交易发送、智能合约部署与调用等核心功能;
- 理解以太坊网络中“状态读取”与“状态修改”的操作差异及gas机制。
实验环境
- 硬件环境:Windows 11 操作系统,CPU i5-10400,内存16GB
- 软件环境:
- Node.js 18.17.0(JavaScript运行环境)
- MetaMask(浏览器钱包,用于测试账户管理)
- Ganache 7.4.0(本地以太坊节点,提供10个测试账户,初始余额100 ETH)
- VS Code 1.88.0(开发工具)
- 依赖库:
web3.js4.10.0(以太坊交互库)solc0.8.23(Solidity编译器)
实验原理
以太坊API接口基础
以太坊节点通过JSON-RPC协议暴露接口,允许客户端通过HTTP或WebSocket请求与节点交互,常用接口包括:
eth_getBalance:查询账户余额;eth_sendTransaction:发送交易(修改状态);eth_call:调用合约方法(只读,不修改状态);eth_getTransactionReceipt:查询交易收据。
智能合约交互流程
智能合约需编译为ABI(Application Binary Interface)和字节码后部署到以太坊网络,交互流程为:
- 部署:发送包含字节码的交易,返回合约地址;
- 调用:通过合约地址和ABI,使用
eth_call(读)或eth_sendTransaction(写)与合约交互。
实验步骤
环境搭建
- 安装Node.js,通过命令行初始化项目:
mkdir eth-api-test && cd eth-api-test npm init -y npm install web3@4.10.0
- 启动Ganache本地节点,记录默认账户地址(如
0x5B38Da6a701c568545dCfcB03FcB875f56beddC4)及私钥。
连接以太坊节点
使用Web3.js连接Ganache节点:
const Web3 = require('web3');
const web3 = new Web3('http://127.0.0.1:7545'); // Ganache默认HTTP端口
// 测试连接
web3.eth.getBlockNumber().then(console.log);
运行结果:输出当前区块号(如0x1),确认连接成功。
账户余额查询
查询Ganache默认账户的ETH余额:
const account = '0x5B38Da6a701c568545dCfcB03FcB875f56beddC4';
web3.eth.getBalance(account).then(balance => {
console.log(`账户 ${account} 余额: ${web3.utils.fromWei(balance, 'ether')} ETH`);
});
运行结果:账户 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 余额: 100 ETH。
发送交易(ETH转账)
从账户A向账户B转账0.1 ETH,需指定from、to、value及gas参数:
const accountA = '0x5B38Da6a701c568545dCfcB03FcB875f56beddC4';
const accountB = '0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2';
const privateKey = '0x4f3edf983ac636a65a842ce7c78d9aae4b84e660e6e5aa139ae514898a8e422a'; // 账户A私钥(仅测试用)
// 构建交易
const tx = {
from: accountA,
to: accountB,
value: web3.utils.toWei('0.1', 'ether'),
gas: 21000, // ETH转账固定gas
gasPrice: web3.utils.toWei('20', 'gwei')
};
// 签名并发送
web3.eth.accounts.signTransaction(tx, privateKey).then(signedTx => {
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', receipt => {
console.log('交易收据:', receipt);
})
.on('error', error => {
console.error('交易失败:', error);
});
});
运行结果:输出交易收据(包含transactionHash、blockNumber等),查询账户B余额应增加0.1 ETH。
智能合约部署与调用
(1)编写智能合约(Solidity)
创建SimpleStorage.sol文件:
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private storedData;
function set(uint256 x) public {
storedData = x;
}
function get() public view returns (uint256) {
return storedData;
}
}
(2)编译合约
使用solc编译合约:
npm install solc@0.8.23 --save-dev
编写compile.js脚本:
const solc = require('solc');
const fs = require('fs');
// 读取合约源码
const sourceCode = fs.readFileSync('SimpleStorage.sol', 'utf8');
// 编译
const input = {
language: 'Solidity',
sources: {
'SimpleStorage.sol': {
content: sourceCode 文章版权声明:除非注明,否则均为新文化在线原创文章,转载或复制请以超链接形式并注明出处。
上一篇:亨长的头发,正在悄然生长
推荐阅读