web3.js查询和修改链上的合约数据

以BSC测试链为例

1 .使用web3连接BSC测试链

var Web3 = require("web3");
// BSC测试链 RPC URL
var url = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
var web3 = new Web3(url);

2.abi获取

打开remix,粘贴Greeter .sol代码,复制右下角ABI。
ABI
如下

[
	{
    
    
		"inputs": [
			{
    
    
				"internalType": "string",
				"name": "_greeting",
				"type": "string"
			}
		],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
    
    
		"inputs": [],
		"name": "greet",
		"outputs": [
			{
    
    
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
    
    
		"inputs": [
			{
    
    
				"internalType": "string",
				"name": "_greeting",
				"type": "string"
			}
		],
		"name": "setGreeting",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	}
]

3.获取获取合约实例

var Contract = new web3.eth.Contract(abi, address);

回调合约的greet()方法

Contract.methods.greet().call().then(function (data) {
    
    
        console.log('greeting:', data);
    });

4.获取某地址的BNB余额

var account = '0x6278A1E803A76796a3A1f7F6344fE874ebfe94B2';
var balance = await web3.eth.getBalance(account); //单位 wei

单位转换(wei => ‘ether’)

web3.utils.fromWei(balance, 'ether')

5.修改合约状态

async function setData(str) {
    
    
	// account的私钥
	var priKey = '0x00';
	var account = '0x6278A1E803A76796a3A1f7F6344fE874ebfe94B2';
	var Wallet = await web3.eth.accounts.wallet;
	Wallet.add(priKey);
	// get gasPrice
	var gasPrice = await web3.eth.getGasPrice();
	// call function setGreeting
	Contract.methods.setGreeting(str).send({
    
    
		from: account,
		gas: web3.utils.toHex(6000000),
		gasPrice: gasPrice
	}).then(function (data) {
    
    
		console.log('SET', data);
		getData();
	});
}

附:

getData.js

var Web3 = require("web3");
// BSC测试链 RPC URL
var url = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
var web3 = new Web3(url);

// contract address
var address = '0xfdc3a5dF20bb6fcf94eC73199DD26c71000b75Ee';
var abi = [
	{
    
    
		"inputs": [
			{
    
    
				"internalType": "string",
				"name": "_greeting",
				"type": "string"
			}
		],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
    
    
		"inputs": [],
		"name": "greet",
		"outputs": [
			{
    
    
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
    
    
		"inputs": [
			{
    
    
				"internalType": "string",
				"name": "_greeting",
				"type": "string"
			}
		],
		"name": "setGreeting",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	}
];

var Contract = new web3.eth.Contract(abi, address);

async function getData() {
    
    
    // 回调合约的greet()方法
    Contract.methods.greet().call().then(function (data) {
    
    
        console.log('greeting:', data);
    });
}

// set data
async function setData(str) {
    
    
	// account的私钥
	var priKey = '0x00';
	var account = '0x6278A1E803A76796a3A1f7F6344fE874ebfe94B2';
	var Wallet = await web3.eth.accounts.wallet;
	Wallet.add(priKey);
	// get gasPrice
	var gasPrice = await web3.eth.getGasPrice();
	// call function setGreeting
	Contract.methods.setGreeting(str).send({
    
    
		from: account,
		gas: web3.utils.toHex(6000000),
		gasPrice: gasPrice
	}).then(function (data) {
    
    
		console.log('SET', data);
		getData();
	});
}

// get address balance
async function getBalance() {
    
    
    var account = '0x6278A1E803A76796a3A1f7F6344fE874ebfe94B2';
    var balance = await web3.eth.getBalance(account);
    console.log('BNBbalance:', web3.utils.fromWei(balance, 'ether'),'ether');
}
getData();
getBalance();
setData("hello");

Greeter .sol

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "hardhat/console.sol";

contract Greeter {
    
    
    string private greeting;

    constructor(string memory _greeting) {
    
    
        console.log("Deploying a Greeter with greeting:", _greeting);
        greeting = _greeting;
    }

    function greet() public view returns (string memory) {
    
    
        return greeting;
    }

    function setGreeting(string memory _greeting) public {
    
    
        console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
        greeting = _greeting;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43405220/article/details/122346251