【web3.js】使用`ethers`包,在以太坊上,利用本地私钥调用智能合约

本文介绍利用ethers,使用本地私钥调用智能合约方法

利用web3.js 结合ethereumjs-tx 来调用合约的方法,见我的另一篇文章
【web3.js】使用私钥调用以太坊智能合约,踩坑记录

为什么要用私钥来调用智能合约?

因为在以太坊私链上进行开发,以太坊1.9.3建议不要使用personal.unlockAccount方法进行解锁账号,这个确实很危险,有一些扫描的服务,会在你解锁的时候,瞬间转走余额,所以需要通过加载私钥来发送交易的方式,调用以太坊合约
by the way , 如果是你自己搭建的私链,只是自己玩一下,还是觉得personal.unlockAccount的方法比较方便的话,只要在私链的启动命令中,加上--allow-insecure-unlock 就可以允许使用啦。

/**
 * 利用ethers,使用本地私钥调用智能合约方法
 */

//英文文档 :https://docs.ethers.io/ethers.js/html/
//中文文档 : https://learnblockchain.cn/docs/ethers.js/api.html 

const ethers = require('ethers');
const abi = require('./build/contracts/ethr-registry.json')
let url = "http://192.168.82.79:8546";
let provider = new ethers.providers.JsonRpcProvider(url);


let privateKey = '0xe096cbf3fd506f950dd323a459bd394b7bf1021607262d10bbde492d43a1f09f';

let wallet = new ethers.Wallet(privateKey, provider);
let address = wallet.address;
console.log("address: ",address)
//查询余额
provider.getBalance(address).then((balance) => {
    // 余额是 BigNumber (in wei); 格式化为 ether 字符串
    let etherString = ethers.utils.formatEther(balance);

    console.log("Balance: " + etherString);
});

//合约地址
let contractAddress =  '0x508bB85453bE637E711c729F60f5990BA059e21b'
//定义合约
let contractWithSigner = new ethers.Contract(contractAddress, abi, wallet)
//发送交易
async function sendTx(){
    let tx = await contractWithSigner.set(8)
    console.log("tx.hash:",tx.hash)
}
sendTx()

//查询合约
async function getTx(){
let newValue = await contractWithSigner.get()
console.log("newValue: ",newValue)
}
getTx()

//转账
let transaction = {
    to: "0x6fC21092DA55B392b045eD78F4732bff3C580e2c",
    value: ethers.utils.parseEther("0.1")
};

// Send the transaction
let sendTransactionPromise = wallet.sendTransaction(transaction);

sendTransactionPromise.then((tx) => {
   console.log(tx);
});
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值