简体   繁体   中英

Connecting User Ethereum account with Metamask in ReactJS and Javascript

First of all, I am pretty new to programming, so please bear with me =)

I am building an app, which requires users to connect their Metamask accounts. I would like to be able to store web3 related functions in a separate js file. I am currently working on a reusable Metamask Connect Button. Here is what the code of the button looks like:

export default function MetamaskBtn() {
  function connect() {
    window.ethereum.request({ method: 'eth_requestAccounts' })
  }
  console.log(connect);
  return (
    <button
      onClick={connect}
      style={{
        id: 'metamaskbtn',
        gridArea: 'web3',
        fontSize: '60%',
        border: 'solid 1px #174666',
        background: '#E36E1A',
        borderRadius: '3px',
        placeSelf: 'center'
      }}>
      Connect Wallet
    </button>
  )
} 

which works fine, now I am trying to save that connect() function in an external js file, which i called ConnectMetamask :

export function ConnectMetamask() {
  window.ethereum.request({ method: 'eth_requestedAccounts' })
}

Then I tried importing the file into my jsx file with no success :

import { ConnectMetamask } from "../../../../_JS Functions/web3Function";

const Metamask = ConnectMetamask

export default function MetamaskBtn() {
  console.log(Metamask);

  return (
    <button
      onClick={Metamask}
      style={{
        id: 'metamaskbtn',
        gridArea: 'web3',
        fontSize: '60%',
        border: 'solid 1px #174666',
        background: '#E36E1A',
        borderRadius: '3px',
        placeSelf: 'center'
      }}>
      Connect Wallet
    </button>
  )
}

I console.log() both functions and they print the same thing in fact.
connect() :

ƒ connect() {
    window.ethereum.request({
      method: 'eth_requestAccounts'
    });
  }

ConnectMetamask()

ƒ ConnectMetamask() {
  window.ethereum.request({
    method: 'eth_requestedAccounts'
  });
}

The error I get from the latter is:

index.js:1 MetaMask - RPC Error: The method 'eth_requestedAccounts' does not exist / is not available. {code: -32601, message: "The method 'eth_requestedAccounts' does not exist / is not available.", data: {…}}

and

localhost/:1 Uncaught (in promise) {code: -32601, message: "The method 'eth_requestedAccounts' does not exist / is not available.", data: {…}}

Hope someone can help me out with this!

好吧,事实上我刚刚意识到这是一个拼写错误 =) hehe-.. 应该是'eth_requestAccounts'而不是'eth_requestedAccounts'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM