web3.js(二)根据私钥推出地址查询以太数量

安装web3+bignumber.js+ethereumjs-util

 

npm i web3 -s
npm i bignumber.js -s
npm i ethereumjs-util -s

code:

 

const Web3 = require("web3");
const BigNumber = require('bignumber.js');
const Ether = new BigNumber(10e+17);
const EthUtil = require('ethereumjs-util');
let web3 = new Web3(new Web3.providers.HttpProvider('https://api.myetherapi.com/eth'));
let privateKey = '291c09fc38eb9a253ee9e2d8e90c91b4f08cd87aa3d9bf707d5fd54a3b4aa442'
let publicKey = EthUtil.privateToPublic(new Buffer(privateKey, 'hex'));
let addr ="0x"+ EthUtil.publicToAddress(publicKey).toString('hex');
console.log(addr);
web3.eth.getBalance(addr).then(v => {
    let ret = new BigNumber(v);
    return parseFloat(ret.dividedBy(Ether)).toFixed(2);
}).then(sum => {
    console.log(sum);
})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于web3.js调用智能合约,我可以给你一些基本的步骤和代码示例。 首先,你需要连接到以太坊网络,可以使用Web3.js提供的Provider对象,例如: ```javascript const Web3 = require('web3'); const provider = new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/your-project-id'); const web3 = new Web3(provider); ``` 在连接成功后,你需要获取智能合约的ABI和地址,例如: ```javascript const abi = [{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]; const contractAddress = '0x1234567890123456789012345678901234567890'; const contract = new web3.eth.Contract(abi, contractAddress); ``` 接着,你可以使用智能合约的方法,例如: ```javascript contract.methods.owner().call().then(console.log); ``` 这里调用了智能合约的owner方法,并输出结果到控制台。 如果你需要发送交易来执行智能合约的可写方法,可以使用send方法,例如: ```javascript const privateKey = '0x1234567890123456789012345678901234567890123456789012345678901234'; const account = web3.eth.accounts.privateKeyToAccount(privateKey); const value = web3.utils.toWei('1', 'ether'); const gasPrice = web3.utils.toWei('30', 'gwei'); const gasLimit = 200000; contract.methods.transferOwnership('0x9876543210987654321098765432109876543210') .send({ from: account.address, gasPrice: gasPrice, gas: gasLimit, value: value }) .then(console.log); ``` 这里使用私钥生成账户,发送一笔以太币交易,调用智能合约的transferOwnership方法并发送交易,交易的参数包括发送地址、燃气费用、燃气限制和转账金额等。 希望这些代码可以帮助你了解如何使用Web3.js调用智能合约。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值