Skip to content

Instantly share code, notes, and snippets.

@adrianchifor
Last active September 15, 2021 23:13
Show Gist options
  • Save adrianchifor/63892a478dd6d8c92931fe36f39d457a to your computer and use it in GitHub Desktop.
Save adrianchifor/63892a478dd6d8c92931fe36f39d457a to your computer and use it in GitHub Desktop.
PancakeSwap V2 usage with web3py
import time
import requests
from decimal import Decimal
from web3 import Web3
web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))
input_address = "CONTRACT ADDRESS TO SELL"
output_address = "CONTRACT ADDRESS TO RECEIVE"
privatekey = "PRIVATE KEY"
my_address = "YOUR WALLET"
# https://docs.pancakeswap.finance/code/smart-contracts/pancakeswap-exchange/router-v2
pswap_router_address = "0x10ED43C718714eb63d5aA57B78B54704E256024E"
url = "https://api.bscscan.com/api"
apikey = "BSCSCAN API KEY"
input_abi = requests.get(f"{url}?apikey={apikey}&module=contract&action=getabi&address={input_address}").json()["result"]
pswap_abi = requests.get(f"{url}?apikey={apikey}&module=contract&action=getabi&address={pswap_router_address}").json()["result"]
input_contract = web3.eth.contract(address=Web3.toChecksumAddress(input_address), abi=input_abi)
input_balance = input_contract.functions.balanceOf(my_address).call()
human_input_balance = web3.fromWei(input_balance, 'ether')
print(f"Input balance: {human_input_balance}")
bnb_balance = web3.eth.get_balance(my_address)
human_bnb_balance = web3.fromWei(bnb_balance, 'ether')
print(f"BNB balance: {human_bnb_balance}")
# Approve input token spend first by PancakeSwap V2 Router
approve = input_contract.functions.approve(
pswap_router_address,
web3.toWei(Decimal('10000'), 'ether'),
).buildTransaction({
'from': my_address,
'gasPrice': web3.toWei('5', 'gwei'),
'nonce': web3.eth.get_transaction_count(my_address),
})
signed = web3.eth.account.sign_transaction(approve, private_key=privatekey)
tx = web3.eth.send_raw_transaction(signed.rawTransaction)
print(f"Approve tx: {web3.toHex(tx)}. Waiting 10s for approval")
time.sleep(10)
pswap_contract = web3.eth.contract(address=pswap_router_address, abi=pswap_abi)
swap_amount = human_input_balance - 10
print(f"Swapping {swap_amount} INPUT to OUTPUT")
pswap_txn = pswap_contract.functions.swapExactTokensForTokens(
web3.toWei(Decimal(swap_amount), 'ether'),
0,
[Web3.toChecksumAddress(input_address), Web3.toChecksumAddress(output_address)],
my_address,
(int(time.time()) + 1000000)
).buildTransaction({
'from': my_address,
'gas': 250000,
'gasPrice': web3.toWei('10', 'gwei'),
'nonce': web3.eth.get_transaction_count(my_address),
})
signed = web3.eth.account.sign_transaction(pswap_txn, private_key=privatekey)
tx = web3.eth.send_raw_transaction(signed.rawTransaction)
print(f"Swap tx: {web3.toHex(tx)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment