唤醒MetaMask,拿到授权

 linkWallet() {
                if (typeof window.ethereum === "undefined") { //判断浏览器是否支持web3
                    this.$message.info('Looks like you need a Dapp browser to get started')
                } else {
                    this.web3Provider = window.ethereum  //将钱包信息赋值
                    try {
                        window.ethereum.enable(); //唤醒小狐狸 询问是否授权
                    } catch (error) {
                        this.connectionStatus = false
                    }
                }
                this.newWeb3() 
            },

创建web3,获取钱包地址

  newWeb3() {
                this.web3js = new Web3(this.web3Provider); //创建web3js
                this.web3js.eth.getAccounts().then(res => {
                    if (res[0] != undefined) {//获取钱包地址成功
                        this.connectionStatus = true //将状态改为true
                        this.contractAddress = res[0] //将钱包地址赋值
                        this.disAddress(res[0]) //某一方法 用来设置显示地址
                        // this.getBalance(this.contractAddress)
                        this.createContract(this.USDTABI, this.USDTAddress)  //创建合约 默认USDT
                        this.checkBalance(this.contractAddress) //调用获取钱包余额 默认USDT
                    } else { //获取失败提示信息
                        this.connectionStatus = false
                        this.$message.error('No authorization');
                    }
                })
            },
 createContract(abi, address) {
                this.contract = new this.web3js.eth.Contract(abi, address, {
                    from: this.contractAddress //contractAddress 为小狐狸钱包地址
                })
            },

获取余额 方法一

         getBalance(address) {
            //todo....
            this.web3js.eth.getBalance(address).then(res => {
                this.token = this.web3js.utils.fromWei(res, 'ether') //将获取到的余额 转换单位 每种货币单位不一样
       })
    },

获取余额方法二

        checkBalance(contractAddress) { //传入钱包地址
            this.contract.methods.balanceOf(contractAddress).call().then(res => { //根据货币创建的合约查询对应货币余额
                if (res) {
                    this.contract.methods.symbol().call().then(r => {  //获取币种名 
                        if (r === 'USDT') {
                            this.token = this.web3js.utils.fromWei(res, "mwei")
                        }
                        if (r === 'HT') {
                            this.token = this.web3js.utils.fromWei(res, "ether")
                        }
                    })
                }
        })
    },

检测切换钱包账户

tn() { let that = this window.ethereum.on('accountsChanged', getAccounts); function getAccounts(accounts) { that.contractAddress = accounts[0] that.$message.info("Switch wallet address detected. Switch wallet address for you") that.connectionStatus = false that.checkBalance(this.USDTAddress) that.currency = 'USDT' } },

最后修改:2021 年 05 月 21 日 03 : 37 PM
如果觉得我的文章对你有用,请随意赞赏