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

相关推荐
DICOM医学影像4 小时前
9. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 总结
区块链·智能合约·solidity·以太坊·web3.0·hardhat·json-rpc
myan4 小时前
稳定币与 RWA 闭环将成为新的美元护城河
区块链
Gofarlic_oms14 小时前
区块链存证节点搭建:金融行业审计证据链构建指南
运维·人工智能·金融·数据挖掘·区块链·需求分析·devops
DICOM医学影像4 小时前
2. Remix编写、编译、部署、测试Solidity ERC20合约 - 进阶篇
区块链·solidity·以太坊·web3.0·hardhat·erc20
DICOM医学影像4 小时前
7. Hardhat编写、编译、部署、测试Solidity ERC20合约 - 进阶篇 - JSON-RPC调用合约方法
区块链·solidity·以太坊·web3.0·erc20·jsonrpc
Gofarlic_OMS5 小时前
从Adobe到SolidWorks:研发设计软件资产管理的现状分析
数据库·安全·adobe·oracle·金融·区块链
Rockbean5 小时前
3分钟Solidity: 7.6 Yul语言简介
web3·智能合约·solidity
Gofarlic_OMS5 小时前
通过MathWorks API实现许可证管理自动化
大数据·数据库·人工智能·adobe·金融·自动化·区块链
小明的小名叫小明17 小时前
Compound协议(2)
区块链·defi