Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda