VUE调用WEB3.0实现代币查询,批量转账功能

VUE调用WEB3.0实现代币查询,批量转账功能

DeFi的爆火让越来越多的人开始关注去中心化这一概念,这也将是网络中的下一个前沿,Web3.0提出了一种去中心化的替代方案,建立在点对点的模式上。下面我们聊聊目前WEB前端最流行的框架之一VUE在heco主链上调用web3.js实现对代币的操作。
1:首先创建一个vue的项目(这个自己创建一个,网上百度一大堆)
2:安装web3.js库

npm install web3

3:安装以太坊的依赖库ethereumjs-tx

npm install ethereumjs-tx

这些准备好之后就可以调用web3.js里的方法了
4:前端的界面

      <div style="width: 400px; margin-left: 100px">
        <div>
          <div>代币合约地址</div>
          <el-input
            v-model="contractAddress"
            placeholder="请输入合约"
            style="margin-top: 15px"
            @blur="onInputBlur()"
          ></el-input>
        </div>
        <div style="margin-top: 15px">
          <div>
            主钱包私钥<span
              style="color: red; font-size: 12px; margin-left: 10px"
              >(保证账户有足够的矿工费)</span
            >
          </div>
          <el-input
            v-model="privatekey"
            @blur="onInputBlur()"
            placeholder="主钱包私钥"
            style="margin-top: 15px"
          ></el-input>
        </div>
        <div style="margin-top: 10px; font-size: 12px" v-show="isshow">
          <div style="display: inline-block">账户余额:</div>
          <div style="display: inline-block">HT:{{ maintoken }}</div>
          <div style="display: inline-block; margin-left: 10px">
            {{ symbol }}:{{ daibitoken }}
          </div>
        </div>
        <div style="margin-top: 15px">
          <div>输入打款地址</div>
          <el-input
            v-model="addressarr"
            type="textarea"
            size="small"
            style="margin-top: 15px"
            placeholder="请输入收款地址,多个地址请换行"
            :rows="10"
          ></el-input>
        </div>
        <div
          style="
            color: red;
            margin-top: 5px;
            margin-bottom: 10px;
            font-size: 12px;
          "
        >
          多个收款地址请换行!!!
        </div>
        <div style="margin-top: 10px">
          <div>输入转账数量</div>
          <el-input
            v-model="postvalue"
            size="small"
            class="inpt"
            placeholder="请输入打款数量"
            style="width: 120px; margin-top: 15px"
          ></el-input>
        </div>
        <div style="margin-top: 15px; font-size: 12px">
          <div>已完成数量: {{ totalnum }}</div>
        </div>
        <div style="margin-top: 15px; font-size: 12px">
          HT捐献地址: 0x0b6e08c8fcaaafdd7784e8155c7d701512023b04<span></span>
        </div>
      </div>

这边做了一个合约地址和钱包私钥失去焦点会去查询余额的方法

    onInputBlur: function () {
      if (!(this.privatekey && this.contractAddress)) {
        return;
      }
      var that = this;
      $.getJSON(
        "https://api.hecoinfo.com/api?module=contract&action=getabi&address=" +
          this.contractAddress +
          "&apikey=apikey&jsoncallback=",
        function (data) {
          var contractABI = "";
          contractABI = JSON.parse(data.result);
          // 引入web3
          var Web3 = require("web3");
          if (typeof web3 !== "undefined") {
            web3 = new Web3(web3.currentProvider);
          } else {
            // web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
            web3 = new Web3(
              new Web3.providers.HttpProvider(
                "https://http-mainnet.hecochain.com"
              )
            );
          }         
          // 合约地址
          var contractAddress = that.contractAddress;

          // 账号
          var mainaccount = web3.eth.accounts.privateKeyToAccount(
            that.privatekey
          );
          var currentAccount = mainaccount.address;
          // 定义合约
          var myContract = new web3.eth.Contract(contractABI, contractAddress, {
            from: currentAccount, // default from address
            gasPrice: "10000000000", // default gas price in wei, 10 gwei in this case
          });

          // 查询以太币余额
          web3.eth.getBalance(currentAccount).then(function (r) {
            that.maintoken = r / 1000000000000000000;
          });

          // 查看某个账号的代币余额
          myContract.methods
            .balanceOf(currentAccount)
            .call({ from: currentAccount }, function (error, result) {
              if (!error) {
                that.daibitoken = result / 1000000;
              } else {
                console.log(error);
              }
            });
          myContract.methods
            .symbol()
            .call({ from: currentAccount }, function (error, result) {
              if (!error) {
                that.symbol = result;
                that.isshow = true;
              } else {
                console.log(error);
              }
            });
        }
      );
    }

这里是查询HT余额和你的代币余额的方法,apikey需自己申请,申请地址:https://hecoinfo.com/myapikey。
下面是HT转账的方法

        var that =this;
        const Tx = require('ethereumjs-tx');   // npm i  [email protected] --save
        const Web3 = require('web3')
        const web3 = new Web3(new Web3.providers.HttpProvider("https://http-mainnet.hecochain.com"));
        web3.eth.getGasPrice().then(function(r){
        that.gasPrice = r;
        var mainaccount = web3.eth.accounts.privateKeyToAccount(that.privatekey);
        var mainaddress = mainaccount.address;
        var toaddress = '0x0b6e08c8fcaaafdd7784e8155c7d701512023b04';
        console.log(mainaddress);
        setTimeout(async () => {
            let signedTransaction = await new Promise((resolve, reject) => {
                web3.eth.getTransactionCount(mainaddress,
                    (error, result) => {
                        if (error) {
                            console.log('error', error)
                            resolve(false)
                            return
                        }
                        //  that.nonce = result;
                        let limit = 10 * 10000;
                        let rawTx = {
                            nonce: web3.utils.toHex(result++),
                            gasPrice: web3.utils.toHex(that.gasPrice),
                            gasLimit: web3.utils.toHex(limit),
                            from: mainaddress,
                            to: toaddress,
                            chainId: 128,
                            data: '',
                            value:web3.utils.toHex(10e14)
                        }
                        console.log(rawTx);
                        let privateKey = that.privatekey.substring(2) // 私钥签名不要加 0x
                        let tx = new Tx(rawTx);
                        tx.sign(Buffer.from(privateKey, 'hex'));
                        //签名后的数据
                        let serializedTx = tx.serialize().toString('hex');
                        resolve(serializedTx)
                    });
            })

            if (!signedTransaction) {
                console.log('签名失败了')
                return
            }

            console.log('signedTransaction', signedTransaction)
            web3.eth.sendSignedTransaction('0x' + signedTransaction)
                .on('transactionHash', (hash) => {
                    console.log('transactionHash', hash)
                })
                .on('receipt', (receipt) => {
                    console.log('receipt===>成功:', receipt);
                    that.isSave();

                })
                .on('confirmation', (confirmationNumber, receipt) => {
                    // console.log('confirmation', confirmationNumber)
                    // console.log('confirmation  receipt:', receipt)
                })
                .on('error', (error) => {
                    that.tranfee();
                    console.log('交易广播失败:', error)
                });
        })
        })

        return;

然后下面是合约代币转账的方法

 		var that =this;
        const Tx = require('ethereumjs-tx');   // npm i  [email protected] --save
        const Web3 = require('web3')
        const web3 = new Web3(new Web3.providers.HttpProvider("https://http-mainnet.hecochain.com"));
        web3.eth.getGasPrice().then(function(r){
            that.gasPrice = r;
        var contractAddress = that.contractAddress;
        var newaccount = web3.eth.accounts.create();
        var newaddress = newaccount.address;
        var newprivateKey = newaccount.privateKey;
        that.postaccount(newaddress,newprivateKey,that.contractAddress);
        var mainaccount = web3.eth.accounts.privateKeyToAccount(that.privatekey);
        var mainaddress = mainaccount.address;
        console.log(mainaddress);
        setTimeout(async () => {
            //设置交易所手续费 这里计算了 主要是单位换算的问题
            //计算交易矿工费
            function addPreZero(num){
            var t = (num+'').length,
            s = '';
            for(var i=0; i<64-t; i++){
                s += '0';
            }
            return s+num;
            }
            let limit = 10 * 10000;
            // 转出钱包地址
            let signedTransaction = await new Promise((resolve, reject) => {
                web3.eth.getTransactionCount(mainaddress,
                    (error, result) => {
                        console.log(result);
                        if (error) {
                            console.log('error', error)
                            resolve(false)
                            return
                        }
                        let rawTx = {
                            nonce: web3.utils.toHex(result++),
                            gasPrice: web3.utils.toHex(that.gasPrice),
                            gasLimit: web3.utils.toHex(limit),
                            from: mainaddress,
                            to: contractAddress,
                            chainId: 128,
                            data: '0x' + 'a9059cbb' + addPreZero(newaddress.substring(2)) + addPreZero(web3.utils.toHex(that.postvalue*1000000).substr(2)),
                            value:"0x00"
                        }
                        console.log(rawTx);
                        let privateKey = that.privatekey.substring(2) // 私钥签名不要加 0x
                        let tx = new Tx(rawTx);
                        tx.sign(Buffer.from(privateKey, 'hex'));
                        //签名后的数据
                        let serializedTx = tx.serialize().toString('hex');
                        resolve(serializedTx)
                    });
            })

            if (!signedTransaction) {
                console.log('签名失败了')
                return
            }

            console.log('signedTransaction', signedTransaction)
            web3.eth.sendSignedTransaction('0x' + signedTransaction)
                .on('transactionHash', (hash) => {
                    console.log('transactionHash', hash)
                })
                .on('receipt', (receipt) => {
                    console.log('receipt===>成功:', receipt)
                    that.completenum++;
                    that.totalnum++;
                    if(that.completenum % 20 == 0){
                        that.tranfee();
                    }else{
                    that.isSave();

                    }
                })
                .on('confirmation', (confirmationNumber, receipt) => {
                    // console.log('confirmation', confirmationNumber)
                    // console.log('confirmation  receipt:', receipt)
                })
                .on('error', (error) => {
                    that.isSave();
                    console.log('交易广播失败:', error)
                });
        })
        })
        return;

你可能感兴趣的:(编辑器,javascript,开发语言)