vue3 使用 web3.js;钱包转账;唤醒钱包.......

该文章介绍了如何使用web3.js进行以太坊开发,包括安装依赖、初始化连接、唤醒MetaMask钱包、查看钱包余额以及发起主币和代币的转账操作。示例代码提供了封装的EthJs类,包含关键方法如sendTransaction。
摘要由CSDN通过智能技术生成

web3.js基本使用

本篇文章不适合没有经验的小白,需要对web3有一定的了解,所以有些参数需要自己懂!
准备

安装web3.js依赖包
npm install web3

文档教程地址:https://web3.tryblockchain.org/

这是我自己封装的类 web3.js 直接复制过去就可以用

/**
 * 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);
  };
}


  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Vue3中使用web3.js可以按照以下步骤进行: 1. 首先,在需要使用web3.js的页面中引入web3.js库。可以使用import语句将web3.js库导入到你的代码中。例如,可以使用以下代码导入web3.js库: ```javascript import Web3 from 'web3'; ``` 2. 接下来,你需要初始化web3实例。可以使用以下代码初始化web3实例: ```javascript const web3 = new Web3(window.ethereum); ``` 这里使用了window.ethereum作为web3的提供者,它是浏览器中的以太坊钱包提供的全局变量。 3. 然后,你可以使用web3实例来调用智能合约的方法。例如,可以使用以下代码调用智能合约的某个方法: ```javascript const contract = new web3.eth.Contract(abi, contractAddress); contract.methods.methodName().call((error, result) => { if (error) { console.error(error); } else { console.log(result); } }); ``` 这里的abi是智能合约的ABI(Application Binary Interface),contractAddress是智能合约的地址,methodName是智能合约中的某个方法名。 需要注意的是,由于web3.js的一些方法是异步的,你可能需要使用async/await或者Promise来处理异步操作。 希望以上信息对你有所帮助! #### 引用[.reference_title] - *1* *3* [在vue使用web3.js开发以太坊dapp](https://blog.csdn.net/qingshui_zhuo/article/details/112978150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [记录分享vue3通过web3.js连接MetaMask的流程及签名、验签方法](https://blog.csdn.net/q1354790820/article/details/129820494)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值