是否有可能使用web3获取Metamask图片和名称?我使用react作为web3的前端。据我所知,我用web3.eth.get.Accounts().then(rsp=>rsp[0])来拿钱包。有人能跟我解释一下吗?
发布于 2022-05-13 14:03:41
可能已经太迟了,但是我经过一些研究才发现了这一点。下面我会用最好的方式解释。它能处理大部分边缘病例。
第一步
安装:
(npm install web3)
npm install @web3-react/core)
npm install @web3-react/injected-connector)
npm install @metamask/jazzicon)
第二步
import { useWeb3React } from "@web3-react/core"
拿到钱包地址
useWeb3React()是@web3-react/core提供的一个钩子。这将返回对象中的account和其他几个值。既然你只问名字和形象,我会在这里澄清它们。
没有任何密码钱包的名字。有个地址。因为元an是基于ethereum块链的,所以它将有一个类似于0x0EfGhjuw....的地址。您可以通过我提到的account变量获得这个结果。
const {account, active} = useWeb3React()
useEffect(()=>{
console.log(account) //prints to console the wallet address of metamask (0xfEgh67...)
// also prints it everytime you change the account in metamask
}, [account])澄清了这些内容后,让我们看看如何才能获得元问题的帐户映像。
获取帐户图标
import jazzicon from "@metamask/jazzicon"
const {account} = useWeb3React()
const avatarRef = useRef()
useEffect(() => {
const element = avatarRef.current;
if (element && account) {
const addr = account.slice(2, 10);
const seed = parseInt(addr, 16);
const icon = jazzicon(20, seed); //generates a size 20 icon
if (element.firstChild) {
element.removeChild(element.firstChild);
}
element.appendChild(icon);
}
}, [account, avatarRef]);
return(
<div ref={avatarRef}></div>
)我们使用jazzicon的原因显然是元问询也使用jazz图标来生成钱包图像。上面的逻辑从您传递的钱包地址生成一个整数。该整数决定您的帐户映像。这是完美的,就我所相信的而言,元问询使用相同的算法来生成帐户映像。
https://stackoverflow.com/questions/71678374
复制相似问题