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?
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