Sending transactions and listening to events
Calling a function that changes state sends a transaction. The call returns right away with a transaction response, and you must wait for it to be mined. Use tx.wait() to get the receipt, which contains the status and the logs.
Transactions can fail. The user can reject the signature, the contract can revert, or the gas estimate can fail. Wrap the call in try and catch, and show a clear message instead of a blank screen.
Events are how your contract talks to the frontend. In ethers you can listen live with contract.on, or read past events with queryFilter. Indexed event parameters work as filters, for example to fetch only the transfers sent to one address.
Live listeners stay open, so remove them when your page or component closes. For history, query a limited block range, because asking for the whole chain is slow and many providers reject it.
async function bump(counter) { try { const tx = await counter.increment(); // wallet pops up const receipt = await tx.wait(); // wait for the block console.log("Mined in block", receipt.blockNumber); } catch (err) { console.error(err.shortMessage || err.message); } } // Listen live for a Transfer event (token contract) token.on("Transfer", (from, to, amount) => { console.log(`${from} sent ${amount} to ${to}`); }); // Read recent history filtered by recipient const filter = token.filters.Transfer(null, myAddress); const logs = await token.queryFilter(filter, -5000);
Try it yourself
Update your page to show a pending message while tx.wait() runs and a success message afterwards.