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())
balanceOfToken = contract.functions.balanceOf(main_address).call()
return? – ZevbalanceOfToken > web3.fromWei(0.5, 'ether')
must be True for the loop to exit. I was able to check the value ofweb3.fromWei(0.5, 'ether')
which isDecimal('5E-19')
but I don't know the value ofbalanceOfToken
. – Zev