Web3+Vue唤醒MetaMask钱包交互

  • IT_浩哥
  • 更新于 2022-11-24 16:40
  • 阅读 3972

Web3+Vue唤醒MetaMask钱包交互

image.png

1、在 mounted 中自动检测浏览器是否安装MetaMask钱包

 mounted () {
    if (window.ethereum) {
      window.ethereum.enable().then((res) => {
        //alert("当前钱包地址:"+res[0])
      })
    }else{
      alert("请安装MetaMask钱包")
    }
  }

2、查询钱包余额

let web3 = new Web3(window.web3.currentProvider)
let fromAddress = web3.eth.accounts[0];
web3.eth.getBalance(fromAddress,(err, res) => {
   if (!err) {
       console.log("余额==",res.toNumber()/Math.pow(10,18));
   }
 })

3、查询代币余额

let web3 = new Web3(window.web3.currentProvider)
let fromAddress = web3.eth.accounts[0];
let ethContract = web3.eth.contract("代币合约Abi")
let functionInstance = ethContract.at("代币合约地址")
functionInstance.balanceOf(fromAddress,(err, res) => {
   if (!err) {
       //代币精度根据所发行的代币合约精度换算 
       console.log("代币余额==",res.toNumber()/Math.pow(10,18));
   }
})

4、转账

let web3 = new Web3(window.web3.currentProvider)
let fromAddress = web3.eth.accounts[0];
//转账数量
let amount = 1*Math.pow(10,18);
//收款地址
let toAddress = "0x40141cF4756A72DF8D8f81c1E0c2ad403C127b9E";
web3.eth.sendTransaction({
    gas: 21000,
    gasPrice: 5000000000,
    from: fromAddress,
    to: toAddress,
    value: amount
 }, (err, result) => {
     console.log("转账Hash=",result)
 })

5、代币转账

let web3 = new Web3(window.web3.currentProvider)
let ethContract = web3.eth.contract("代币Abi")
let functionInstance = ethContract.at("代币地址")
//当前钱包地址
let fromAddress = web3.eth.accounts[0];
//转账数量
let amount = 100*Math.pow(10,18);
//接收地址
let toAddress = "0x40141cF4756A72DF8D8f81c1E0c2ad403C127b9E";
functionInstance.transfer(toAddress,amount,{
     gas: 21000,
     gasPrice: 5000000000,
     from: fromAddress
 }, (err, result) => {
       console.log("转账Hash:",result)
  })

6、代币授权

let web3 = new Web3(window.web3.currentProvider)
let abiContract = web3.eth.contract("代币合约Abi")
let contractInstance = abiContract.at("代币合约地址")
//当前钱包地址
var fromAddress = web3.eth.accounts[0];
//授权数量
var amount = 1000 * Math.pow(10,18);
contractInstance.approve("授权地址",amount,{
    gas: 80000,
    gasPrice: 1500000000,
    from: fromAddress
}, (err, result) => {
    console.log("交易Hash:",result)
})

7、查询授权数量

let web3 = new Web3(window.web3.currentProvider)
let abiContract = web3.eth.contract("代币合约Abi")
let contractInstance = abiContract.at("代币合约地址")
contractInstance.allowance("授权的用户钱包地址","授权的地址",(err, res) => {
    if (!err) {
        console.log("授权数量==",res.toNumber());
    }
}) 

image.png

学如逆水行舟,不进则退。心似平原跑马,易放难收。全栈工程师是指掌握多种技能,并能利用多种技能独立完成产品的人。 也叫全端工程师(同时具备前端和后台能力),英文Full Stack engineer。【人工智能】【区块链】【系统/网络/运维】【云计算/大数据】【数据库】【移动开发】【后端开发】【游戏开发】【UI设计】【微服务】【爬虫】【Java】【Go】【C++】【PHP】【Python】【Android/IOS】【HTML/CSS】【JavaScript】【Node】。。。

欢迎各位大神萌新一起专研分享各行各业技术!

Chain区块链开发社区:593674370

点赞 0
收藏 3
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
IT_浩哥
IT_浩哥
个人简介:学如逆水行舟,不进则退。心似平原跑马,易放难收!