连接metamask,并签名

在assets下新建metamask.js
import { ethers } from "ethers"; //版本号为 "ethers": "^4.0.47",
import { buildLoginNonce } from '@/api/register' //请求接口后台返回随机验证码
/**
 * 
 * @param {*} ethereum 连接钱包类型 metamask(ethereum)、nabox(NaboxWallet)
 * @returns 
 */

export async function metamaskWallet(ethereum = 'ethereum') {
    if (typeof window[ethereum] === "undefined") {
        if(ethereum === 'ethereum'){
            alert("Please install MetaMask")
        }else{
            alert("Please install Nabox Wallet")
        }
    } else {
        const provider = new ethers.providers.Web3Provider(window[ethereum]);
        let address = null
        try {
            address = await window[ethereum].request({ method: 'eth_requestAccounts' }); //连接钱包
        } catch (error) {
            throw(error)
        }
        if (address[0]) {
            // 签名
            const code = await buildLoginNonce(address[0]); 
            const jsonRpcSigner = provider.getSigner();
            const signature = await jsonRpcSigner.signMessage(code.data);
            console.log(signature)
        }
    }
}

 

posted @ 2023-04-27 11:57  龙卷风吹毁停车场  阅读(282)  评论(0)    收藏  举报