本文介绍利用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);
});