uni-app eth/bsc dapp转账

2021-11-16  本文已影响0人  THERAIN_

使用uni-app 开发eth/bsc dapp.

1.安装web3.js

npm install web3

2.在页面中使用

<template>
    <view>
        <h1>钱包地址:{{ walletAddress }}</h1>
        <!--  -->
        <button @click="tokenTransfer()"> 代币转账</button>
        <button @click="transfer()"> ETH/BNB转账 </button>
    </view>
</template>

<script>
    import Web3 from 'web3';
    // 合约ABI基本上可以通用
    const contractAbi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"wad","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"deposit","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}],"name":"Withdrawal","type":"event"}];
    
    export default {
        data() {
            return {
                walletAddress:'', // 当前用户钱包地址
            };
        },
        onLoad() {
            //自动检测钱包
            // console.log(window.web3)
            if (window.ethereum) {
              window.ethereum.enable().then((res) => {
                //alert("当前钱包地址:"+res[0])
                this.walletAddress = res[0];
                console.log(this.walletAddress)
              })
            }else{
              alert("请安装MetaMask钱包")
            }
        },
        methods:{
            // 自己发行的代币转账
            
    // 代币转账
async tokenTransfer(){
    //ETH转账
    //合约地址,发布之后在以太坊上生成的合约地址
    let contractAddr = "0x510B7E4966758615F5AA4fc497Ebb85684519173"; // bsc-usdt合约地址
    let fromAddress = this.walletAddress; // fromAddress
    let toAddress = '0x417F36b1A773d7D602A56b9fBB5353E6A07cCafD' // toAddress
    //7、根据abi获取合约
    let web3 = new Web3(window.web3.currentProvider); // 当前网络节点
    let amount = parseInt(10 * Math.pow(10,18)).toString();
    var contract = new web3.eth.Contract(contractAbi, contractAddr);
    console.log(contract,'合约方法')
    contract.methods.balanceOf(fromAddress).call().then((err,result)=> {
        console.log(err,'当前代币余额')
    })
    web3.eth.getAccounts((err, accounts)=> {
        if (accounts.length == 0) {
            alert('Please check if the wallet is unlocked');
            return;
        }
    });
    let gasPrice = await web3.eth.getGasPrice()
    var gs = ((gasPrice * 80000) / (10 ** 18)).toFixed(6)
    // 代币转账  transfer: 合约方法名
    contract.methods.transfer(toAddress, amount).send({
        from:fromAddress,
        gas:81000,
        gasPrice,
    },(err,res)=>{
        console.log(err,res)
        if(!err){
            console.log('转账hash',res)
        }else{
            console.log('转账失败')
        }
    }).then((result)=>{
        console.log('转账结束',result.transactionHash)
    }).catch(err=>{
        console.log('转账取消')
    })
},
    //BNB转账
transfer(){
    let web3 = new Web3(window.web3.currentProvider);
    console.log(web3,'web3 对象')
    // let fromAddress = web3.eth.getAccounts[0];
    let amount = 0.01*Math.pow(10,18);
    let toAddress = "0xeA66e8573e9D03320718AB858B5713686860bE99";
    web3.eth.sendTransaction({
        gas: 21000,
        gasPrice: 5000000000,
        from: this.walletAddress,
        to: toAddress,
        value: amount
    }, (err, result) => {
        console.log("转账Hash=",result)
    })
},
            
            
        }
    }
</script>

<style lang="less">

</style>

上一篇下一篇

猜你喜欢

热点阅读