Hi I am trying to do a swap between two tokens directly from the smart contract using the contract's function 'swap'
https://bscscan.com/address/0x172fcd41e0913e95784454622d1c3724f546f849#writeContract#F10
Here is my code but the transaction failed and not sure why
from web3 import Web3
a_token_0_price = 294.8237179588189932873664394169209
a_token_1_price = 0.003391857367932928995343385329856006
price = math.sqrt(a_token_1_price)
token1_decimals = 18
bsc_endpoint = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc_endpoint))
contract_address = '0x172fcd41e0913e95784454622d1c3724f546f849'
checksum_address = web3.to_checksum_address(contract_address)
contract_abi = get_bsc_abi(contract_address)
contract = web3.eth.contract(address=checksum_address, abi=contract_abi)
recipient_address = wallet_address
zero_for_one = True # Swap token0 for token1 or vice versa
amount_specified = 1000000
sqrt_price_limit_x96 = int(a_token_1_price * (10 ** token1_decimals))
data = b''
nonce = web3.eth.get_transaction_count(wallet_address)
tx = contract.functions.swap(recipient_address, zero_for_one, amount_specified, sqrt_price_limit_x96, data).build_transaction({
'chainId': 56, # Binance Smart Chain's chain ID
'gas': 2000000, # Adjust gas limit accordingly
'gasPrice': web3.to_wei('5', 'gwei'), # Adjust gas price accordingly
'nonce': nonce,
})
# Sign the transaction
signed_tx = web3.eth.account.sign_transaction(tx, private_key)
try:
# Send the transaction
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
print("Transaction Hash:", web3.to_hex(tx_hash))
except Exception as e:
print("Transaction failed:", str(e))