1

I want to be notified when a specific account receives eth. Currently, I subscribe to ERC20 contract logs:

  web3.eth
    .subscribe(
      "logs",
      {
        address: [
          "0xabcd..." // ERC20 contract address
        ],
      },
      (err, res) => {
        if (err) console.log(err);
        if (res) console.log(res);
      }
    )
    .on("data", function (transaction) {
      console.log(transaction);
    });

which works for token transfers but not for sending eth, the callback does not get called when addresses contains my account for example.

I can subscribe to pending transactions which works when sending eth:

  web3.eth
    .subscribe("pendingTransactions", (err, hash) => {
      if (err) console.log(err);
    })
    .on("data", function (txHash) {
      return web3.eth.getTransaction(txHash, (err, returnedValue) => {
        if (err) {
          // error handling
        }
        if (
          returnedValue && returnedValue.to === accountAddress)
        ) {
          console.log(`TransactionHash: ${returnedValue.hash}`);
        }
      });
    });

however I don't know how to tell when this transaction completes, would I need another subscribe for the pending transaction hash?

Looking for a simple solution to know when a specific account receives eth using web3js, appreciate any help thanks.

0

You can subscribe to newBlockHeaders and check if the balance has changed

async function notifyBalanceUpdate(address, callback) {
    let balance = await web3.eth.getBalance(address);
    web3.eth.subscribe('newBlockHeaders')
        .on("data", async () => {
            const newbalance = await web3.eth.getBalance(address);
            if (!balance.eq(newbalance)) {
                  const oldbalance = balance;
                  balance = newbalance;
                  callback(newbalance, oldbalance);
            }
        }
    );
}

Note 1: The code doesn't account for partial modifications in one block, if several transactions modify the balance in the same block it will only notify once.

Note 2: The code doesn't take into account chain reorgs.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.