I'm trying to create a website where users can deposit ethereum. For my server I'm using node.js and express.js. I looked into web3.js but the docs are unclear to me and I don't know which functions to use. I guess having a background loop running and checking for incoming transactions, then create another loop which waits for the nth confirmation is the way to go. But which package and functions should I use for achieving this? Can someone sort me out where to start?
1 Answer
I have an example with ethers.js
:
const ethers = require("ethers");
// Change the provider if needed. Mine is my local Ganache
const provider = new ethers.providers.JsonRpcProvider("http://localhost:7545");
const signer = provider.getSigner();
async function sendTransactionAndWait5Confirmations() {
const tx = await signer.sendTransaction({
// Change the 'to' address to one available in your local network or your provider
to: "0xd2826D22cfA01d6cA6730b60A895d8c231E6385b",
// Sending 3 ethers
value: ethers.utils.parseEther("3.0"),
});
// Waiting 5 confirmations. You can put any number of confirmations here
const txReceipt = await tx.wait(5);
console.log("txReceipt: ", txReceipt);
}
sendTransactionAndWait5Confirmations();
Create a directory, create an index.js
file, run the command:
npm install ethers
Put the code in the index.js
file.
My provider http://localhost:7545 is where my local Ganache is running. Run Ganache and check where it is running:
Change the to: "0xd2826D22cfA01d6cA6730b60A895d8c231E6385b"
to any address of the ones shown in Ganache. Not the first one because that will be the sender by default.
Then run:
node index.js
This will stop on the line const txReceipt = await tx.wait(5);
and wait for 5 confirmations, for 5 blocks, the one where the transaction is included + 4 more blocks.
Since this script is busy, we need to generate blocks somehow so we get the required 5 confirmations and finally see the txReceipt
.
For this, I simply connected Remix to my local Ganache and deployed a few contracts and at 5 confirmations the script continued and showed the txReceipt
.