How to continuously keep track of balance of a particular token in my wallet

Question:

I’m trying to create a bot which keeps a track of a particular token in my wallet. As soon as it detects the token, it should send the token to another address. I’ve written the code but i don’t know why my while loop doesn’t work. The code kind of skips the while loop and creates the transaction at the end anyway which results in an error since there is no token to transfer. The script should be stuck in a loop until there is some token balance but it isn’t happening.I’m running this on a VS Code terminal.

from web3 import Web3
import json

bsc = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
print(web3.isConnected())

main_address = "wallet to be tracked"
contract_address = "token contract address"
abi = json.loads('the abi')

contract = web3.eth.contract(address=contract_address, abi = abi)

balanceOfToken = contract.functions.balanceOf(main_address).call()
print(web3.fromWei(balanceOfToken, 'ether'))

while(True):
    balanceOfToken = contract.functions.balanceOf(main_address).call()
    print(balanceOfToken)
    if(balanceOfToken > web3.fromWei(0.5, 'ether')):
        break
    continue

second_address = "the other wallet address"
main_key = "private key of first wallet"

nonce = web3.eth.getTransactionCount(main_address)

token_tx = contract.functions.transfer(my_address, balanceOfToken).buildTransaction({
    'chainId':56, 'gas': 90000, 'gasPrice': web3.toWei('5', 'gwei'), 'nonce':nonce
})

signed_tx = web3.eth.account.signTransaction(token_tx, main_key)
web3.eth.sendRawTransaction(signed_tx.rawTransaction)

print(contract.functions.balanceOf(my_address).call() + " " + contract.functions.name().call())
Asked By: Saujanya Verma

||

Answers:

The value of web3.fromWei(0.5, 'ether') is Decimal('5E-19') (from trying out the API myself).

The value of balanceOfToken is 10^-18 (from discussion in comments).

Since 10^-18 is bigger then 5 * 10^-19, the condition if(balanceOfToken > web3.fromWei(0.5, 'ether')) evaluates to True and the loop exits.

Answered By: Zev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.