前端Vue项目调用页面web3.js:连接metaMask钱包,(查询钱包ETH余额,查询代币余额,ETH转账,代币转账,代币授权,查询授权数量,计算价格)等功能
Posted MFG_666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端Vue项目调用页面web3.js:连接metaMask钱包,(查询钱包ETH余额,查询代币余额,ETH转账,代币转账,代币授权,查询授权数量,计算价格)等功能相关的知识,希望对你有一定的参考价值。
这里分享下相关文档
1.web3.js中文文档 https://learnblockchain.cn/docs/web3.js/getting-started.html
2.metamask官方文档:https://docs.metamask.io/
第一种方法:连接钱包
// 参考网址:https://blog.csdn.net/cjy_win/article/details/117248919?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_aa&utm_relevant_index=2
// 1.先确认自己的浏览器安装了metaMask插件,建议谷歌浏览器
// 2.Vue项目安装web3.js,使用npm安装web3js依赖
//在vue中安装web3
npm install web3 --save
//在main.js引入
import Web3 from 'web3'
Vue.prototype.Web3 = Web3
自己创建一个getWeb3.js文件把下面代码放入里面,需要用到的页面直接引入即可
import Web3 from "web3";
const getWeb3 = () =>
new Promise((resolve, reject) =>
// Wait for loading completion to avoid race conditions with web3 injection timing.
window.addEventListener("load", async () =>
// Modern dapp browsers...
if (window.ethereum)
const web3 = new Web3(window.ethereum);
try
// Request account access if needed
await window.ethereum.enable();
// Acccounts now exposed
resolve(web3);
catch (error)
reject(error);
// Legacy dapp browsers...
else if (window.web3)
// Use Mist/MetaMask's provider.
const web3 = window.web3;
console.log("Injected web3 detected.");
resolve(web3);
// Fallback to localhost; use dev console port by default...
else
const provider = new Web3.providers.HttpProvider(
"http://127.0.0.1:9545"
);
const web3 = new Web3(provider);
console.log("No web3 instance injected, using Local web3.");
resolve(web3);
);
);
export default
getWeb3
;
3.上面是一个js方法,根据当前页面来初始化web3对象,在对应页面 通过 const Web3= require('../common/getWeb3') 引入,然后通过下面方法使用
注意:加web3前面必须有window : window.web3
Web3.default.getWeb3().then((res) =>
window.web3 = res;
console.log("getWeb3", res);
);
源码:
<template>
<div>
<button @click="get()">连接钱包</button>
</div>
</template>
<script>
export default
data()
return ;
,
mounted() ,
methods:
get()
// web3前面必须有window
const Web3 = require("../common/getWeb3");
Web3.default.getWeb3().then((res) =>
window.web3 = res;
console.log("getWeb3", res);
);
,
;
</script>
第二种方法: 连接钱包 安装依赖直接可以使用
参考网址:https://blog.csdn.net/qq_16137795/article/details/120239103?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-1-120239103.pc_agg_new_rank&utm_term=web3+%E8%B0%83%E7%94%A8MetaMask%E9%92%B1%E5%8C%85%E8%BD%AC%E8%B4%A6eth&spm=1000.2123.3001.4430
// 1.先确认自己的浏览器安装了metaMask插件,建议谷歌浏览器
// 2.Vue项目安装web3.js,使用npm安装web3js依赖
//在vue中安装web3
npm install web3 --save
//在main.js引入
import Web3 from 'web3'
Vue.prototype.Web3 = Web3
注意:ethereum 和 web3 前必须有window: window.ethereum window.web3
if (window.ethereum)
window.ethereum.enable().then((res) =>
alert("当前钱包地址:" + res[0]);
);
else
alert("请安装MetaMask钱包");
源码:
<template>
<div class="home">
<button @click="get">连接钱包</button>
</div>
</template>
<script>
export default
data()
return ;
,
mounted() ,
methods:
get()
if (window.ethereum)
window.ethereum.enable().then((res) =>
alert("当前钱包地址:" + res[0]);
);
else
alert("请安装MetaMask钱包");
,
,
;
</script>
其他功能:
1、在 mounted 中自动检测浏览器是否安装MetaMask钱包
mounted ()
if (window.ethereum)
window.ethereum.enable().then((res) =>
//alert("当前钱包地址:"+res[0])
)
else
alert("请安装MetaMask钱包")
2、查询钱包ETH余额
let web3 = new Web3(window.web3.currentProvider)
let fromAddress = web3.eth.accounts[0];
web3.eth.getBalance(fromAddress,(err, res) =>
if (!err)
console.log("ETH余额==",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、ETH转账
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());
)
8、查询去中心化交易所LP地址数量 计算价格
let web3 = new Web3(window.web3.currentProvider)
let ethContract = web3.eth.contract("LP合约Abi")
let functionInstance = ethContract.at("LP合约地址")
functionInstance.getReserves((err, res) =>
if (!err)
// 代币数量1 res[0].toNumber()
// 代币数量2 res[1].toNumber()
//根据先后顺序 2个相除可以得到价格
)
以上是关于前端Vue项目调用页面web3.js:连接metaMask钱包,(查询钱包ETH余额,查询代币余额,ETH转账,代币转账,代币授权,查询授权数量,计算价格)等功能的主要内容,如果未能解决你的问题,请参考以下文章