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

相关推荐
ATMQuant1 天前
量化指标解码13:WaveTrend波浪趋势 - 震荡行情的超买超卖捕手
人工智能·ai·金融·区块链·量化交易·vnpy
Web3VentureView1 天前
SYNBO 协议亮相 ChainThink “Meme 回归” AMA:市场奖励机制深度剖析
网络·金融·web3·区块链·加密货币
企业对冲系统官2 天前
基差风险管理系统集成说明与接口规范
大数据·运维·python·算法·区块链·github
企业对冲系统官2 天前
大宗商品风险对冲系统统计分析功能的技术实现
运维·python·算法·区块链·github·pygame
焦点链创研究所2 天前
智慧协议:关于人类秩序最终形态的链上探索
科技·web3·去中心化·区块链
电报号dapp1193 天前
DApp定制开发与源码交付:打造专属区块链应用的核心战略
web3·去中心化·区块链·智能合约
电报号dapp1193 天前
交易所定制化开发:拒绝模板化与源码交付的战略价值
金融·web3·去中心化·区块链·智能合约
TechubNews3 天前
《每周策略通》1.15
区块链
MQLYES3 天前
07-BTC-挖矿难度
区块链
电报号dapp1193 天前
质押挖矿DAPP与Swap交易所开发:构建DeFi新基建的全景指南
web3·去中心化·区块链·智能合约