Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
React connecting Metamask and passing signer to multiple contracts

I'm trying to figure out how to share signer between multiple js files. I have a file walletConnect.js where I connect to Metamask and get ERC20 token contract. This works fine.

async function connect(){
  try{
    const accounts = await ethereum.request({
      method: "eth_requestAccounts",
    });
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();

    // ERC20 token contract
    const tokenContract = new ethers.Contract(
        tokenAddress,
        tokenAbi,
        signer
     );
  } catch (e) {
    console.log(e);
  }
}

and then I have another file stake.js where I deposit a token into a contract

async function stakeToken() {
   try {
     const stakingContract = new ethers.Contract(
        contractAddress,
        contractAbi,
        signer
    );
    
    // approve contract
    await tokenContract.approve(stakingContract.address, maxAmount);

    // stake tokens
    await stakingContract.stakeTokens(
      tokenContract.address,
      amount
    );
  } catch (e) {
    console.log(e);
  }
}

Everything works fine if I have all code in one file. I use useState hook and all is good. However I will have multiple staking contracts I would like to keep in separate javascript files. How do I do it when having multiple files?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I have created a hook contracts.js like this

import { ethers } from "ethers";

export const useContract = (address, abi) => {
  try {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(address, abi, signer);
    return contract;
  } catch (e) {
    console.log(e);
    return false;
  }
};

Now I just call useContract from any script and it returns a contract

const stakingContract = useContract(someAddress, someAbi);

this way I save a lot of redundant code

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!