当前位置: 首页 > 后端技术 > Node.js

web3公测版教程(二)——异步基础语法、交易、签名交易、ganache-cli

时间:2023-04-03 11:04:22 Node.js

一、开发环境安装搭建1、安装node,最好v8可以使用ES6语法2、安装ganacheganache简介:虽然真正的发布必须使用上面提到的三种方式geth,parity,或者其他服务商,但是在测试开发环境中,有一个基于本地内存的钱包,不需要等待交易确认,实时生成区块根据操作,非常方便,就是ganache-cli,纳尼?你没听说过,嗯,它的前身是大名鼎鼎的testrpc,不太好用。安装命令:npmiganache-cli-g执行命令:ganache-cli初始状态描述:创建10个以太坊账户,公私钥一一对应。默认每个账户100ETH,http端口为8545。(如果有其他需求可以阅读官方github:https://github.com/trufflesui...)二、基础示例1、创建一个app.js文件,引用web3,设置http接口provider(没错,就是之前的ganche-cli打开的接口)varWeb3=require('web3');varweb3=newWeb3(newWeb3.providers.HttpProvider(“https//本地主机:8545”));说明:很多教程都会这样写,不对,但是有个坑。if(typeofweb3!=='undefined'){web3=newWeb3(web3.currentProvider);}else{//从Web3.providers设置你想要的提供商web3=newWeb3(newWeb3.providers.HttpProvider("http://localhost:8545"));}如果电脑开启了geth或metamask,web3.currentProvider和ethereumProvider会返回geth和metamask,而不是我们设置的8545,尤其是当metamask浏览器自动打开时。2.测试基本语法打印区块高度旧版本命令:console.log(web3.eth.getBlockNumber());新版本指令:web3.eth.getBlockNumber().then(console.log);描述:web3v1。0使用了大量的ES6语法。如果你对ES6前端和node后端不熟悉,赶快补上吧。该方法的1.0版本使用异步并实现了promise语法。then的正常使用是把一个函数的第一个参数作为成功的返回值,第二个参数是失败的返回值,console.log作为一个函数,传入的成功值会直接打印出来。4、创建账户命令:web3.eth.personal.newAccount('!@superpassword').then(console.log);5、简单事务先封装两个异步函数,方便使用,避免进入回调地狱。优雅的写代码发起交易函数asyncfunctionsendTransaction(send,rece,ethNum){awaitweb3.eth.sendTransaction({from:send,to:rece,value:ethNum}).then(function(receipt){console.log(收据);console.log('send:');findEth(send).then(function(result){console.log(result);});console.log('rec:')findEth(rece).then(function(result){console.log(result);});});}使用公钥查询eth函数个数asyncfunctionfindEth(publicKey){varethNum;awaitweb3.eth.getBalance(publicKey).then(function(res){ethNum=web3.utils.fromWei(res,'ether');});returnethNum;}主程序函数直接执行asyncfunctiontList(){varaccountList;awaitweb3.eth.getAccounts().then((res)=>{accountList=res;});等待sendTransaction(accountList[0],accountList[1],5000000000000000);console.log(findEth(accountList[0]));console.log(findEth(accountList[1]));}tList();扩展:由于ganache-cli的账户是解锁账户,如果您自己创建的账户需要解锁才能使用该方法进行交易。解锁方法如下:web3.eth.personal.unlockAccount(myPublicKey,'password',600).then(function(res){})说明:参数为:公钥,密码,解锁时间,单位秒。600秒内无需解锁。默认300秒,可以等待解锁,也可以在then函数中写交易代码。6.签署交易也是一样:封装一个异步函数,实际上签署一个交易分为两步1.签署交易2.将签署的交易发送到区块链。异步函数signTran(sendPri,rec,num){web3.eth.accounts.signTransaction({to:rec,value:num,gas:2000000},sendPri).then(function(res){web3.eth.sendSignedTransaction(res.rawTransaction).on('receipt',console.log);});}web3.eth.accounts.signTransaction参数为json对象to:(optional)receiver的公钥,如果是发布合约,可以为空数据:(可选)调用智能合约所需的数据,也可以为空值:(可选)eth的数量以wei为单位Gas:(可选)最近gas的数量为21000,太浪费了less不能完成gasPrice::gasprice有gas报价和成功率网站。可以参考官链上的私钥。回调将返回带有签名信息的对象。使用web3.eth.sendSignedTransaction发送交易对象下的十六进制编码交易码rawTransaction。:要复制私钥,必须手动在前面加上0x。Ganache不会为您添加陷阱。1:使用ws报错陷阱。官方文档2.ganache-cligithub地址常见错误:Contracthasnotbeendeployedtodetectednetwork小狐狸(metamask)干扰,小狐狸设置了全局的web3变量,关闭小狐狸再做