web3.js基本使用
本篇文章不适合没有经验的小白,需要对web3有一定的了解,所以有些参数需要自己懂!
准备
安装web3.js依赖包
npm install web3
文章来源:https://www.toymoban.com/news/detail-768232.html
文档教程地址:https://web3.tryblockchain.org/
这是我自己封装的类
web3.js
直接复制过去就可以用文章来源地址https://www.toymoban.com/news/detail-768232.html
/**
* web3.js
* @example
* import Web3 from './web3.js' // 根据你实际文件路径引入这个类
* const web3 = new Web3('https://...');
* web3.wakeUpWallet() // 唤醒钱包
*/
import Web3 from "web3";
export default class EthJs {
/**
* 初始化链接
* @param {String} url 链址
*/
constructor(url) {
this.web3 = new Web3(url);
}
// 唤醒钱包
wakeUpWallet = async () => {
if (window.ethereum) {
return await window.ethereum.enable();
} else {
console.error("请安装meteMask钱包!");
return false;
}
};
/**
* 查看钱包余额
* @param {String} address 地址
* @return 余额
*/
getTokenBalance = async (address) => {
if (!address) {
let web3 = new Web3(window.web3.currentProvider); // 初始化
let arr = await web3.eth.getAccounts();
address = arr[0];
}
let wei = await this.web3.eth.getBalance(address);
return this.web3.utils.fromWei(wei.toString(), "ether");
};
/**
* 发起转账 - 主币
* @param {Object} res 转账需要的数据
* @param {string} res.from 转账发起地址
* @param {string} res.to 转账接受地址
* @param {string} res.value 转账金额 单位/eth
* @param {string} res.gasPrice 费率
* @param {Function} callBack 回调函数
*/
send = async (res = {}, callBack) => {
let { from = "", to = "", gasPrice = "", value = 0, gas = 21000 } = res;
if (!to || !value)
return console.error({ code: 0, error: "缺少必要参数!" });
let web3 = new Web3(window.web3.currentProvider); // 初始化
if (!from) {
let arr = await web3.eth.getAccounts(); // 获取钱包地址 @return - Array
from = arr[0];
}
if (!gasPrice) gasPrice = await web3.eth.getGasPrice();
value = this.web3.utils.toWei(value, "ether"); // eth -> wei
const trans = web3.eth.sendTransaction(
{
gas,
gasPrice,
from,
to,
value,
},
(err, result) => {
console.log(err, "e");
console.log("转账Hash=", result);
}
);
trans.on("transactionHash", (txid) => {
callBack({ event: "transactionHash", data: txid });
});
// 第一个节点确认 - 执行一次
trans.on("receipt", (res) => {
callBack({ event: "receipt", data: res });
});
// 第n个节点确认 - 执行n次
trans.on("confirmation", (res) => {
callBack({ event: "confirmation", data: res });
});
};
/**
* 发起转账-代币
*/
sendToken = async (res = {}, callBack) => {
let {
from = "", // 付款地址
to = "", // 收款地址
tokenURl = "", // 合约地址
value = 0,
gas = "50000",
nonce = 0,
money = 0.00001, // 合约币数量
} = res;
console.log(window.web3.currentProvider);
let web3 = new Web3(window.web3.currentProvider); // 初始化
if (!from) {
let arr = await web3.eth.getAccounts(); // 获取钱包地址 @return - Array
from = arr[0];
}
const gasPrice = await this.web3.eth.getGasPrice(); // 获取预计转账费用
nonce = await this.web3.eth.getBlockTransactionCount(from); // 获取转账次数
value = this.web3.utils.toWei(value, "ether"); // eth -> wei
const addPreZero = (num) => {
let t = (num + "").length,
s = "";
for (let i = 0; i < 64 - t; i++) {
s += "0";
}
return s + num;
};
let code = `0xa9059cbb${addPreZero(to.substring(2))}${addPreZero(
this.web3.utils
.fromDecimal(this.web3.utils.toWei(money, "ether"))
.substring(2)
)}`;
const txraw = {
gas: this.web3.utils.toHex(gas),
gasPrice: this.web3.utils.toHex(gasPrice),
from,
to: tokenURl,
value: value,
data: code,
};
const trans = web3.eth.sendTransaction(txraw, (err, result) => {
console.log(err, "e");
console.log("转账Hash=", result);
});
trans.on("transactionHash", (txid) => {
callBack({ event: "transactionHash", data: txid });
});
trans.on("error", (e) => {
console.log(e);
});
// 调用钱包转账
// const s = await window.ethereum.request({
// method: "eth_sendTransaction",
// params: [
// {
// to: tokenURl,
// from,
// gas: this.web3.utils.toHex(gas),
// value: this.web3.utils.toHex(value),
// gasPrice: this.web3.utils.toHex(gasPrice),
// data: code,
// // data: `0xa9059cbb${addPreZero(
// // to.substring(2)
// // )}0000000000000000000000000000000000000000000000001bc16d674ec80000`,
// },
// ],
// });
// console.log(`output->s`, s);
};
}
到了这里,关于vue3 使用 web3.js;钱包转账;唤醒钱包.......的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!