Using Python 3.10
web3 V 5.31.1
I currently have functional code in python that can buy/sell tokens via PancakeSwapV2 only if they have liquidity pools BNB/token
def buy_token(tkn_addr: str, amount: float, w3: Web3, pan_contract) -> str:
# define transaction
buy_txn = pan_contract.functions.swapExactETHForTokens(
0, # slippage (0 == inf)
[WBNB_ADDR,tkn_addr], # trade from BNB --> token
USER_ADDR, # wallet to send tokens to
(int(time.time()) + 1000) # deadline
).buildTransaction({
'from': USER_ADDR, # wallet to fund trade
'value': w3.toWei(amount, 'ether'), # amount to buy
'gas': 0, # gas limit
'gasPrice': w3.toWei(GAS_PRICE,'gwei'), # gas price
'nonce': w3.eth.get_transaction_count(USER_ADDR) # metamask nonce
})
# get estimated gas cost of transaction
try:
EST_GAS = w3.eth.estimate_gas(buy_txn) + GAS_BUFFER
buy_txn.update({'gas': EST_GAS})
# if fails, default to flat rate
except:
buy_txn.update({'gas': GAS_LIMIT})
# sign and send transaction
signed_txn = w3.eth.account.sign_transaction(buy_txn, private_key=PRIV_KEY)
txn_hash = w3.toHex(w3.eth.send_raw_transaction(signed_txn.rawTransaction))
return txn_hash
However, trading sites such as poocoin.app have the functionality to create routes that allow me to buy/sell tokens with non bnb LPs by creating longer route chains, eg bnb -> usdt -> token.
Assuming I already know the intermediary token, this can be accomplished easily by doing
...swapExactTokensForTokens(
...
[WBNB_ADDR, intermediary_addr, tkn_addr]
...
)
...
However, given the contract address of the token I am wishing to purchase, how can I query pancakeswap for a valid route from BNB-->...-->token?
I cannot find an example of this functionality in python and am looking for help!