以BSC测试链为例
1 .使用web3连接BSC测试链
var Web3 = require("web3");
var url = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
var web3 = new Web3(url);
2.abi获取
打开remix,粘贴Greeter .sol代码,复制右下角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.获取获取合约实例
Contract = await 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 => ‘ether’)
web3.utils.fromWei(balance, 'ether')
附:
getData.js
var Web3 = require("web3");
var url = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
var web3 = new Web3(url);
var Contract;
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"
}
];
async function getData() {
Contract = await new web3.eth.Contract(abi, address);
Contract.methods.greet().call().then(function (data) {
console.log('greeting:', data);
});
}
async function getBalance() {
var account = '0x6278A1E803A76796a3A1f7F6344fE874ebfe94B2';
var balance = await web3.eth.getBalance(account);
console.log('BNBbalance:', web3.utils.fromWei(balance, 'ether'),'ether');
}
getData();
getBalance();
Greeter .sol
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;
}
}
|