1

如何(在 Drizzle 中)获取 Metamask 中当前选择的帐户?

我有一个调用set智能合约方法的函数,但当前帐户是“硬编码”的:

  setValue = value => {
    const { drizzle, drizzleState } = this.props;
    const contract = drizzle.contracts.PartProduction;

    // let drizzle know we want to call the `set` method with `value`
    const stackId = contract.methods["set"].cacheSend(value, {
      from: drizzleState.accounts[0]
    });

    // save the `stackId` for later reference
    this.setState({ stackId });
  };

即在:from: drizzleState.accounts[0]

如何更改from:字段以使用 Metamask 中选择的帐户?

4

3 回答 3

1

drizzleState.accounts[0] 本身表示在 Metamask 中选择的帐户为默认帐户。如果您在 Metamask 中选择其他帐户,drizzleState.accounts[0] 的值会自动更改。

于 2019-02-02T01:41:28.200 回答
0

我编写了一个示例组件来演示AccountData组件和drizzleState中的帐户信息的问题。我还提供了一种直接使用web3 API的解决方法。

import React, { useState, useEffect } from "react";
import { newContextComponents } from "@drizzle/react-components";

const { AccountData } = newContextComponents;

const AccountChangeDetection = ({ drizzle, drizzleState }) => {

  const [ drizzleAcc, setDrizzleAcc ] = useState(drizzleState.accounts[0]);
  const [ drizzleBal, setDrizzleBal ] = useState(drizzleState.accountBalances[drizzleState.accounts[0]]);

  const [ web3Acc, setWeb3Acc ] = useState(null);
  const [ web3Bal, setWeb3Bal ] = useState(null);


  useEffect(() => {

    function loadWeb3Data(web3) {
      web3.eth.getAccounts()
      .then( accounts => {
        setWeb3Acc(accounts[0]);
        web3.eth.getBalance(accounts[0])
        .then(setWeb3Bal);
      } );
    }

    async function listenMMAccount() {
      window.ethereum.on("accountsChanged", async function () {
        // console.log("Account changed");
        // console.log(drizzleState.accountBalances[drizzleState.accounts[0]]);
        setDrizzleAcc(drizzleState.accounts[0]);
        setDrizzleBal(drizzleState.accountBalances[drizzleState.accounts[0]]);
        loadWeb3Data(drizzle.web3);
      });
    }

    loadWeb3Data(drizzle.web3);
    listenMMAccount();
  });

  return (
    <div>

      <strong>AccountData</strong>
      <AccountData
        drizzle={drizzle}
        drizzleState={drizzleState}
        accountIndex={0}
        units="ether"
        precision={3}
      />

      <table>
        <tbody>
          <tr>
            <td>Drizzle</td>
            <td>{drizzleAcc}</td>
            <td>{drizzleBal}</td>
          </tr>
          <tr>
            <td>Web3</td>
            <td>{web3Acc}</td>
            <td>{web3Bal}</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

export default AccountChangeDetection;
于 2020-05-05T22:05:01.610 回答
0

最好的方法是为 drizzle 选项添加一个选项,以便它可以检测浏览器中的 web3 对象。

将毛毛雨选项代码编辑到下面

  web3: {
    block: false,
    customProvider: new Web3(Web3.givenProvider || "ws://localhost:8545"),
    // customProvider: new Web3("wss://kovan.infura.io/ws/v3/5b2a79e624554c8ab922b9a84b076645"),

  },
于 2020-05-28T13:43:05.643 回答