2
votes

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())
1
What does balanceOfToken = contract.functions.balanceOf(main_address).call() return?Zev
@Zev It returns the balance of the token in the wallet to be tracked.Saujanya Verma
What is the exact value when it is called before the loop and at the loop? What do the print statements output?Zev
@Zev Before the loop is whatever it was before the loop was called, and at the loop it should update itself until the value is something substantial like 0.5.Saujanya Verma
I understand what you feel it should be. However, since the loop is exiting, it doesn't seem to match your assumptions which is why I asked for the exact values. balanceOfToken > web3.fromWei(0.5, 'ether') must be True for the loop to exit. I was able to check the value of web3.fromWei(0.5, 'ether') which is Decimal('5E-19') but I don't know the value of balanceOfToken.Zev

1 Answers

0
votes

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.