美文网首页
web3js脚本编写

web3js脚本编写

作者: 攻城老狮 | 来源:发表于2020-07-25 14:36 被阅读0次

    转账脚本

    1. 编写转账的js脚本,保存在transactionTest.js文件中
    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
    
    var _from = web3.eth.accounts[0];
    var _to = web3.eth.accounts[1];
    var _value = 2333;
    
    web3.eth.sendTransaction({from:_from,to:_to,value:_value},(err,res)=>{
        if(err){
            console.log("Error:",err);
        }else{
            console.log("Result:",res);
        }
    });
    
    
    1. 在shell中敲如下命令
    $ node transactionTest.js 
    Result: 0xbae4d738ca3501d686781c10ce859b0b3eafefbeb21bf7344508017308a16587
    

    转币合约的调用

    1. 编写solidity程序
    pragma solidity ^0.4.26;
    
    contract Coin{
        address public minter;
        mapping(address=>uint) public balance;
        event Sent(address from,address to,uint account);
        constructor() public{
            minter = msg.sender;        
        }
        
        function mint(address receiver,uint account) public{
            require(msg.sender == minter);
            balance[receiver] += account;
        }
        
        function send(address receiver,uint account) public{
            require(balance[msg.sender] >= account);
            balance[msg.sender] -= account;
            balance[receiver] += account;
            emit Sent(msg.sender,receiver,account);
        }
    }
    
    1. 使用remix部署合约到本地私链
    //部署的合约地址
    0x80f1A59742EF01a913Fe4B43ebaA759B9618B323
    //开账minter
    0x613d104e6D80ce5A06e7987D39Bbd4eE0ccD7656
    //区块号
    26
    //abi
    [{"constant":true,"inputs":[],"name":"minter","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"send","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"account","type":"uint256"}],"name":"Sent","type":"event"}]
    //操作前需要在geth中指定,使msg.sender保证为该用户发起 【可选】
    > eth.defaultAccount = eth.coinbase // 之后就不用输入{from:..}
    
    1. 编写调用的js脚本,保存在sendCoin.js文件中
    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
    
    var _from = web3.eth.accounts[0];
    var _to = web3.eth.accounts[1];
    var amount = 12;
    
    var abi = [{"constant":true,"inputs":[],"name":"minter","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"send","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"account","type":"uint256"}],"name":"Sent","type":"event"}]
    var CoinContract = web3.eth.contract(abi);
    var contractAddr = "0x80f1A59742EF01a913Fe4B43ebaA759B9618B323";
    var contractInstance = CoinContract.at(contractAddr);
    contractInstance.send(_to,amount,{from:_from},(err,res)=>{
        if(err)
            console.log("Error:",err);
        else
            console.log("Result",res);
    });
    
    
    1. 执行shell命令,并检验
    $ node sendCoin.js
    Result 0x1ea44d44b45a25ed18ee1190d52175f66b832403fb121518d67ea56c4dd24025
    
    // 之前的余额信息
    > contractInstance.balance(eth.accounts[1])
    25
    > INFO [05-29|21:07:45.047] Submitted transaction                    fullhash=0x1ea44d44b45a25ed18ee1190d52175f66b832403fb121518d67ea56c4dd24025 recipient=0x80f1A59742EF01a913Fe4B43ebaA759B9618B323
    INFO [05-29|21:07:45.047] Commit new mining work                   number=38 sealhash=12385d…3f2d34 uncles=0 txs=0 gas=0     fees=0          elapsed=41.826µs
    INFO [05-29|21:07:45.048] Sealing paused, waiting for transactions 
    INFO [05-29|21:07:45.048] Commit new mining work                   number=38 sealhash=58cda4…ccb9dc uncles=0 txs=1 gas=35756 fees=3.5756e-14 elapsed=497.6µs
    INFO [05-29|21:07:45.048] Successfully sealed new block            number=38 sealhash=58cda4…ccb9dc hash=9922c2…b07bb9 elapsed=543.138µs
    INFO [05-29|21:07:45.048] 🔨 mined potential block                  number=38 hash=9922c2…b07bb9
    INFO [05-29|21:07:45.048] Commit new mining work                   number=39 sealhash=769859…b5c2b0 uncles=0 txs=0 gas=0     fees=0          elapsed=211.956µs
    INFO [05-29|21:07:45.048] Sealing paused, waiting for transactions 
    INFO [05-29|21:07:45.049] Commit new mining work                   number=39 sealhash=769859…b5c2b0 uncles=0 txs=0 gas=0     fees=0          elapsed=390.635µs
    // 之后的余额信息,可以发现增加了12
    > contractInstance.balance(eth.accounts[1])
    37
    

    (补充)优化上述脚本

    • 实现转币地址和金额可以在命令行指定
    • 实现在脚本中解锁账户(启动geth时候必须指定暴露personal的api接口 --rpcapi personal)

    将下列代码写入 sendCoinPlus.js文件中

    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
    
    //从命令行的第三个参数开始切割,忽略前面的 node sendCoinPlus.js 两个参数
    var arguments = process.argv.splice(2);
    var _from = arguments[0]
    var _to = arguments[1];
    var amount = arguments[2];
    
    var abi = [{"constant":true,"inputs":[],"name":"minter","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"send","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"account","type":"uint256"}],"name":"Sent","type":"event"}]
    var CoinContract = web3.eth.contract(abi);
    var contractAddr = "0x80f1A59742EF01a913Fe4B43ebaA759B9618B323";
    var contractInstance = CoinContract.at(contractAddr);
    
    //解锁账户
    web3.personal.unlockAccount(_from,"199748",(err,res)=>{
        if(err){
            console.log("Error:",err);
        }else{
            contractInstance.send(_to,amount,{from:_from},(err,res)=>{
            if(err)
                console.log("Error:",err);
            else
                console.log("Result",res);
            });
        }
    });
    
    $ node sendCoinPlus.js "0x9f0316428ea5231b7116840df16ae0a768078ffd" "0x613d104e6d80ce5a06e7987d39bbd4ee0ccd7656" 10
    

    事件监听

    1. 实现监听事件的js脚本,保存到 listenContract.js文件中
    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
    
    var abi = [{"constant":true,"inputs":[],"name":"minter","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"mint","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"account","type":"uint256"}],"name":"send","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"account","type":"uint256"}],"name":"Sent","type":"event"}]
    var CoinContract = web3.eth.contract(abi);
    var contractAddr = "0x80f1A59742EF01a913Fe4B43ebaA759B9618B323";
    var contractInstance = CoinContract.at(contractAddr);
    // 监听事件
    contractInstance.Sent("latest",(err,res)=>{
       if(err)
           console.log("Error:",err);
       else
           console.log("Sent Event:",res);
    });
    
    1. 启动监听,并发起一笔监听所在合约的调用
    # 启动监听
    $ node listenContract.js
    
    //发起调用
    > contractInstance.send(eth.accounts[2],10,{from:eth.accounts[0]})
    INFO [05-29|22:25:46.702] Submitted transaction                    fullhash=0x55667599e6a3da27e823508d940e50a374168fa3093e0b20c0af94bc9b4908ed recipient=0x80f1A59742EF01a913Fe4B43ebaA759B9618B323
    "0x55667599e6a3da27e823508d940e50a374168fa3093e0b20c0af94bc9b4908ed"
    > INFO [05-29|22:25:46.716] Commit new mining work                   number=41 sealhash=b8e382…21e5a3 uncles=0 txs=0 gas=0     fees=0          elapsed=88.875µs
    INFO [05-29|22:25:46.716] Sealing paused, waiting for transactions 
    INFO [05-29|22:25:46.716] Commit new mining work                   number=41 sealhash=f31b2e…7f7d92 uncles=0 txs=1 gas=50756 fees=5.0756e-14 elapsed=852.866µs
    INFO [05-29|22:25:46.722] Successfully sealed new block            number=41 sealhash=f31b2e…7f7d92 hash=c5d63e…232a9f elapsed=5.665ms
    INFO [05-29|22:25:46.722] 🔨 mined potential block                  number=41 hash=c5d63e…232a9f
    INFO [05-29|22:25:46.722] Commit new mining work                   number=42 sealhash=3ac604…6a129c uncles=0 txs=0 gas=0     fees=0          elapsed=315.093µs
    INFO [05-29|22:25:46.723] Sealing paused, waiting for transactions 
    INFO [05-29|22:25:46.723] Commit new mining work                   number=42 sealhash=3ac604…6a129c uncles=0 txs=0 gas=0     fees=0          elapsed=616.163µs
    
    $ node listenContract.js
    //可以发现,成功监听到事件
    Sent Event: {
      address: '0x80f1a59742ef01a913fe4b43ebaa759b9618b323',
      blockNumber: 41,
      transactionHash: '0x55667599e6a3da27e823508d940e50a374168fa3093e0b20c0af94bc9b4908ed',
      transactionIndex: 0,
      blockHash: '0xc5d63ece5d0da1a6f3324d4949b4911d2b591217c996563d53857dbb33232a9f',
      logIndex: 0,
      removed: false,
      event: 'Sent',
      args: {
        from: '0x613d104e6d80ce5a06e7987d39bbd4ee0ccd7656',
        to: '0xf0a545c9bd6dbb358990b9bded9086d4bcbccbc3',
        account: BigNumber { s: 1, e: 1, c: [Array] }
      }
    }
    

    相关文章

      网友评论

          本文标题:web3js脚本编写

          本文链接:https://www.haomeiwen.com/subject/jqzplktx.html