map-bgp / browserbook

Peer to peer browser based decentralized exchange
2 stars 1 forks source link

Watching ContractFactory Events with Ethers #12

Closed cmbothwell closed 2 years ago

cmbothwell commented 2 years ago

I have unfortunately not been able to watch the TokenFactory events upon token creation in the front-end. The below code successfully queries the contract for events, but does not receive events upon the creation call:


  useEffect(() => {
    const setupContract = async () => {
      const c = await ethers.getContract(ContractNames.TokenFactory)
      setContract(c)

      // This works
      // @ts-ignore
      c.queryFilter(event).then(r =>
      {
        console.log("Queried events")
        console.log(r)
      })

      // This doesn't
      c.on(event, () => console.log("Event processed"));
    }
    setupContract().then(() => console.log("Contract initialized"))
  }, [])

  const createToken = (uri: string) => {
    if (contract != null) {
      contract.create(uri).then(tx => console.log(tx))
    } else {
      console.log("Contract not initialized yet")
    }
  }
cmbothwell commented 2 years ago

With the introduction of the new useEthers hook via #11, this pattern is greatly simplified. For instance:

const [ethers, connected, address, contract, resolved] = useEthers(ContractNames.TokenFactory);

const getWalletTokens = async (contract) => {
  const tokens: object[] = [];

  const tokenFilter = contract.filters.TokenCreated(address, null, null);
  await contract.queryFilter(tokenFilter).then(async result => {
    result.forEach(event => tokens.push(
      {
        "owner": event.args[0],
        "address": event.args[1],
        "uri": event.args[2],
      }
    ))
    dispatch(setTokens(tokens))
  });
}

useEffect(() => {
  const setup = async () => {
    if (resolved) {
      await getWalletTokens(contract).then(() => console.log("Tokens successfully queried"));

      const tokenFilter = contract.filters.TokenCreated(address, null, null);
      contract.on(tokenFilter, () => getWalletTokens(contract));
    }
  }
  setup().then()
}, [resolved])