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合约 - 总结

相关推荐
超级架构师3 小时前
【区块链技术】区块链101:比特币是什么?
人工智能·区块链·比特币
维克兜率天5 小时前
4.3.2.1 日常监控:上线只是开始
服务器·数据库·python·区块链·php·量化
磐链科技2 天前
交易所开发核心:钱包提现引擎的设计——从风控拦截、多级审批到自动广播上链
web3·区块链
2601_962077982 天前
阿里二面,前端开发在web3.0中该如何应用,记录面经
区块链·前端开发·web3.0·技术趋势·学习准备
baopixiaoz2 天前
BeeQuant × BeeAgent:AI驱动智能交易
大数据·人工智能·python·区块链
ZDGJ60993 天前
恒指期货什么意思,恒指期货怎么看
区块链
综合简报3 天前
东南亚发稿多少钱一篇?预算怎么规划?如何选到高性价比服务商?
区块链
磐链科技3 天前
区块链开发入门实战:用 Hardhat 与 Ethers.js 搭建你的第一个 DApp
开发语言·javascript·区块链
磐链科技3 天前
Web3钱包开发中的交易风控体系:模拟执行、沙盒隔离与授权拦截
web3·区块链
liuze4083 天前
区块链连接调用完成数据上链
区块链