使用 Drizzle 在 Metamask 中选择当前帐户

Get current account selected in Metamask using Drizzle

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

我有调用智能合约方法set的函数,但当前账户是"hardcoded":

  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 中选择的帐户?

drizzleState.accounts[0] 本身表示在 Metamask 中编辑的帐户 select 作为默认帐户。如果您 select Metamask 中的其他帐户,drizzleState.accounts[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;

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

编辑毛毛雨选项代码如下

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

  },