如何(在毛毛雨中)获取当前在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中选择的帐户?
答案 0 :(得分:1)
drizzleState.accounts [0]本身表示在Metamask中选择的帐户为默认帐户。如果在Metamask中选择其他帐户,则drizzleState.accounts [0]的值会随之自动更改。
答案 1 :(得分: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;
答案 2 :(得分:0)
最好的方法是为毛毛雨选项添加一个选项,以便它可以检测浏览器中的web3对象。
将毛毛雨选项代码编辑到下面
web3: {
block: false,
customProvider: new Web3(Web3.givenProvider || "ws://localhost:8545"),
// customProvider: new Web3("wss://kovan.infura.io/ws/v3/5b2a79e624554c8ab922b9a84b076645"),
},