Interact Binance Smart Chain using Python

Library requirements

Wongsakorn Sanwises
2 min readJun 10, 2021
pip install web3

Import library

from web3 import Web3
import time, json
bsc = “https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
print(web3.isConnected())

Check balance


address = ‘ You Address Wallet ’
balance = web3.eth.get_balance(address)
print(balance)

result = web3.fromWei(balance,’ether’)
print(result)

Check Tokens Balance

import json
import requests
from web3 import Web3
MyAddress = “YOU WALLET”
TokenAddress = “0x844fa82f1e54824655470970f7004dd90546bb28”

- Get ABI from BSCscan

bsc = “https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
url_eth = “https://api.bscscan.com/api"
contract_address = web3.toChecksumAddress(TokenAddress)
API_ENDPOINT = url_eth+”?module=contract&action=getabi&address=”+str(contract_address)
r = requests.get(url = API_ENDPOINT)
response = r.json()
abi=json.loads(response[“result”])

- Call contract

contract = web3.eth.contract(address=contract_address, abi=abi)
totalSupply = contract.functions.totalSupply().call()
print(totalSupply)
print(contract.functions.name().call())
print(contract.functions.symbol().call())
address = web3.toChecksumAddress(MyAddress)
balance=contract.functions.balanceOf(address).call()
print(web3.fromWei(balance, “ether”))

Get Price from DEX

example : TWINDEX (DEX) DOP/BUSD

import json
import list_bsc
from web3 import Web3
web3 = Web3(Web3.HTTPProvider(‘https://bsc-dataseed.binance.org/'))BUSD = web3.toChecksumAddress(‘0xe9e7cea3dedca5984780bafc599bd69add087d56’)
WBNB = web3.toChecksumAddress(‘0x844fa82f1e54824655470970f7004dd90546bb28’)
InputTokenAddr = BUSD
OutputTokenAddr = WBNB
pancake_factory_address = web3.toChecksumAddress(“0x4e66fda7820c53c1a2f601f84918c375205eac3e”)#ABI Contract factory
with open(‘pancake_factory.json’, ‘r’) as abi_definition:
abi = json.load(abi_definition)
#ABI Contract Pancake Pair
with open(‘pancakepair.json’, ‘r’) as abi_definition:
parsed_pair = json.load(abi_definition)
contract = web3.eth.contract(address=pancake_factory_address, abi=abi)
pair_address = contract.functions.getPair(InputTokenAddr,OutputTokenAddr).call()
pair1 = web3.eth.contract(abi=parsed_pair, address=pair_address)
reserves = pair1.functions.getReserves().call()
reserve0 = reserves[0]
reserve1 = reserves[1]
print(f’The current price is : ${reserve1/reserve0}’)

Donate for more article (BSC Wallet)

0x2878C91dA6C9C74Ccc813c622389201717528bce

--

--

Responses (6)