Is there an "optimal" way to listen to multiple smart contracts?
For example, listening to an event emitted by one smart contract in a useEffect
:
useEffect(() => {
const provider = new ethers.providers.JsonRpcProvider();
const contract = new ethers.Contract(contractAddress, contract.abi, provider);
contract.on("SomeEvent", (_a, _b, _c) => {
console.log({_a, _b, _c});
});
return () => {
contract.removeAllListeners("SomeEvent");
}
}, [])
But what if I want to listen to 10 different contracts? This brute force approach lacks elegance:
useEffect(() => {
const provider = new ethers.providers.JsonRpcProvider();
const contract_a = new ethers.Contract(contractAddress_a, contract.abi, provider);
const contract_b = new ethers.Contract(contractAddress_b, contract.abi, provider);
const contract_c = new ethers.Contract(contractAddress_c, contract.abi, provider);
const contract_d = new ethers.Contract(contractAddress_d, contract.abi, provider);
contract_a.on("SomeEvent", (_a, _b, _c) => {
console.log({_a, _b, _c});
});
contract_b.on("SomeEvent", (_a, _b, _c) => {
console.log({_a, _b, _c});
});
contract_c.on("SomeEvent", (_a, _b, _c) => {
console.log({_a, _b, _c});
});
contract_d.on("SomeEvent", (_a, _b, _c) => {
console.log({_a, _b, _c});
});
return () => {
contract_a.removeAllListeners("SomeEvent");
contract_b.removeAllListeners("SomeEvent");
contract_c.removeAllListeners("SomeEvent");
contract_d.removeAllListeners("SomeEvent");
}
}, [])
Especially if I wanted to listen to > 25 contract addresses at once.