Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda