8. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用区块链方法

Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用区块链方法

  • [1. 安装依赖](#1. 安装依赖)
  • [2. 启动Hardhat本地节点](#2. 启动Hardhat本地节点)
  • [3. 编写调试代码](#3. 编写调试代码)
  • [4. 合约部署到本地节点](#4. 合约部署到本地节点)

系列文章
1. Remix编写、编译、部署、测试Solidity ERC20合约 - 基础篇
2. Remix编写、编译、部署、测试Solidity ERC20合约 - 进阶篇
3. Metamask导入代币,转账ETH,转账代币
4. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 基础篇
5. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - web3.js调用合约方法
6. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - web3.js调用区块链方法
7. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用合约方法
8. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用区块链方法
9. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 总结

对比系列中的此篇文章
6. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - web3.js调用区块链方法

1. 安装依赖

npm install web3

2. 启动Hardhat本地节点

npx hardhat node

3. 编写调试代码

clike 复制代码
const { ethers } = require("hardhat");
const { default: Web3 } = require('web3');

// 部署合约
async function deploy() {
  // 获取合约工厂(这里期望存在名为 Token 的合约,位于 contracts/ 下)
  // 注意:合约名需与 solidity 文件中合约名一致。
  const myContract = await ethers.getContractFactory("MyToken");
  const token = await myContract.deploy();
// 等待链上确认
  await token.waitForDeployment();
  const address = await token.getAddress();
  console.log("实际合约地址:", address);

  return address;
}

// JSON-RPC调用区块链方法-读操作
async function jsonrpc_read_blockchanin(funcName, address=[]) {
    const name = await http(funcName, address.length==0 ? []: [address, 'latest']);
}

// JSON-RPC调用区块链方法-写操作
async function jsonrpc_write_blockchanin(fromAddress, toAddress, value) {
    const name = await http('eth_sendTransaction', [{
        from: fromAddress,
        to: toAddress,
        value: '0x' + BigInt(value).toString(16).padStart(64, '0'),
        gas: '0x300000'
    }]);
}

async function http(method, params) {
    const response = await fetch('http://localhost:8545', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            jsonrpc: '2.0',
            method,
            params,
            id: 1
        })
    });
    
    const data = await response.json();
    // console.log('JSON-RPC Raw Response:', data);
    if(data.result.length > 66)
        console.log(method + ':', new Web3().eth.abi.decodeParameter('string', data.result));
    else if(BigInt(data.result))
        console.log(method + ':', BigInt(data.result));
}

// JSON-RPC调用区块链方法
async function jsonRpc_transaction() {
    // 读取区块号
    await jsonrpc_read_blockchanin('eth_blockNumber');
    // 读取账户余额
    await jsonrpc_read_blockchanin('eth_getBalance', '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266');
    // 发起转账交易
    await jsonrpc_write_blockchanin('0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', 1000);
}

async function main() {
    var address = await deploy();
    console.log("jsonRpc 发起转账交易:");
    await jsonRpc_transaction();
}

main().then();

JSON-RPC结构:

clike 复制代码
{
	jsonrpc: '2.0',
	method,
	params,
	id: 1
}

读写操作直接调用区块链方法名

将方法名放入method,参数放入params,组装jsonrpc。

读操作不消耗gas,从本地节点直接返回,不组装交易结构,不进行挖矿。所以不需要交易结构中的from、value、gaslimit、gasprice。

写操作消耗gas,广播到区块链上的节点,组装交易结构,进行挖矿。所以需要交易结构中的from、value、gaslimit、gasprice,默认不需要data。

查询区块号的JSON-RPC结构:

clike 复制代码
{
	jsonrpc: '2.0',
	method: 'eth_blockNumber',
	params: [],
	id: 1
}

查询余额的JSON-RPC结构:

clike 复制代码
{
	jsonrpc: '2.0',
	method: 'eth_getBalance',
	params: [address, 'latest'],
	id: 1
}

发起交易的JSON-RPC结构:

clike 复制代码
{
	jsonrpc: '2.0',
	method: 'eth_sendTransaction',
	params: [{
        from: fromAddress,
        to: toAddress,
        value: '0x' + BigInt(value).toString(16).padStart(64, '0'),
        gas: '0x300000'
    }],
	id: 1
}

4. 合约部署到本地节点

npx hardhat run ignition\modules\Mytoken.js --network localhost

hardhat node输出

系列文章
1. Remix编写、编译、部署、测试Solidity ERC20合约 - 基础篇
2. Remix编写、编译、部署、测试Solidity ERC20合约 - 进阶篇
3. Metamask导入代币,转账ETH,转账代币
4. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 基础篇
5. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - web3.js调用合约方法
6. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - web3.js调用区块链方法
7. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用合约方法
8. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用区块链方法
9. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 总结

相关推荐
baopixiaoz2 天前
AI量化策略师|Web3 量化交易研究员
大数据·人工智能·python·区块链
Jiamiren2 天前
WEEX:长鑫科技上市大涨,宇树科技合约同步走高,传统资产交易迎来新路径
人工智能·科技·区块链
黄焖鸡能干四碗3 天前
信息安全保障方案(Word文件)
大数据·网络·人工智能·架构·区块链
Web3李李4 天前
链游想要获得市场认可,核心从来不是极致去中心化
web3·去中心化·区块链·软件开发·链游开发
mykj15514 天前
稳定的DOO算力质押系统DAPP合约底层逻辑
web3·区块链·dapp·rwa·质押挖矿
SoStraw4 天前
Go + webrpc 实战:人在外面,远程查家里 NAS 磁盘和目录
go·p2p·nas·cgo·json-rpc·webrpc·无公网ip
大鱼>4 天前
以太坊Layer2扩容:Optimistic vs ZK-Rollup完整对比
区块链
汇策研习社4 天前
斐波那契均线交易体系:21/55/89三重均线趋势战法详解
大数据·经验分享·金融·区块链·fastbull
同花顺期货通4 天前
期货新手入门品种筛选:2026年低保证金高流动性品种深度解析
区块链
磐链科技4 天前
从Truffle到Hardhat:DApp开发框架的技术演进与工程化最佳实践
区块链