如何从Vue.js DApp建立web3提供者连接?

zfciruhq  于 2022-12-04  发布在  Vue.js
关注(0)|答案(1)|浏览(155)

我打算从vue.js DApp与Rootstock区块链交互,以跟踪钱包余额并发送RBTC。 我想建立一个Metamask连接,并使用ethers.js web3提供程序与Rootstock网络交互。 我创建了一个Pinia存储来保存整个应用程序的所有web3数据。

import { ref } from 'vue';
import { defineStore } from 'pinia';
import { providers } from 'ethers';
​
export const useRootstockStore = defineStore('rootstock', () => {
  const balance = ref(0);
  const address = ref('');
  const provider = ref(null);
​
  const getBalance = async () => {
    balance.value = await provider.value.getBalance(address.value);
  };
​
  const connect = async () => {
    await window.ethereum.request({
      method: 'eth_requestAccounts',
    });
    provider.value = new providers.Web3Provider(window.ethereum);
    [address.value] = await provider.value.listAccounts();
  };
​
...
});

在存储中,我有:

  • provider ref,应该存储对web3提供程序的引用
  • address ref保留元掩码wallet地址
  • balance ref存储钱包余额
  • connect函数,用于建立元掩码连接并示例化ethers web3提供程序
  • getBalance函数,用于向提供程序查询Wallet的RBTC余额 调用connect函数后,应用程序连接到Metamask,似乎与Rootstock建立了连接,但当我尝试查询钱包的RBTC余额时,我一直收到以下错误:
TypeError: 'get' on proxy: property '_network' is a read-only and non-configurable data property on the proxy target but the proxy did not return its actual value (expected '#<Object>' but got '#<Object>')
    at Proxy.<anonymous> (base-provider.ts:820:22)
    at Generator.next (<anonymous>)
    at fulfilled (formatter.ts:523:1)

我错过了什么?

nlejzf6q

nlejzf6q1#

换出ref,并将其替换为computed
不使用ref存储提供程序:

const provider = ref(null);

您应该使用computed来存储提供程序:

const provider = computed(() => new providers.Web3Provider(window.ethereum));

因此,整个脚本应如下所示:

import { ref, computed } from 'vue';
...
export const useRootstockStore = defineStore('rootstock', () => {
  const balance = ref(0);
  const address = ref('');
  const provider = computed(() => new providers.Web3Provider(window.ethereum));

  const getBalance = async () => {
    balance.value = await provider.value.getBalance(address.value);
  };

  const connect = async () => {
    await window.ethereum.request({
      method: 'eth_requestAccounts',
    });
    [address.value] = await provider.value.listAccounts();
  };
...
});

这应该可以解决您的问题。

相关问题