How to interact with a Binance Smart Chain contract using Python

Viewed 9444

I've first tried sending a transaction with python:

from web3 import Web3

transaction = {
        'chainId': 97,  # 97: Testnet. 56: main.
        'to': '0xmyaddress',
        'value': 1,
        'gas': 2000000,
        'gasPrice': 13,
        'nonce': 0,
    }

infura_url = "https://mainnet.infura.io/v3/my-api-key"
w3 = Web3(Web3.HTTPProvider(infura_url))

key = '0xmykey'
signed = w3.eth.account.signTransaction(transaction, key)

w3.eth.sendRawTransaction(signed.rawTransaction)

Giving me the following error: ValueError: {'code': -32000, 'message': 'invalid sender'}


Now, I am trying to interact with a contract - calling methods and giving inputs, but I am unsure how to accomplish this.

1 Answers

web3bsc would work for that, just uninstall web3 pip3 uninstall web3 and then install web3bsc pip3 install web3bsc you can now import web3 like always:

import web3

bsc = web3.bsc.Bsc("pub_key","priv_key")
w3 = web3.Web3()   # HTTPProvider and Binance endpoint not required

# Your code
transaction = {
    'chainId': 56,       # main. test-net maybe not supported yet
    'to': bsc.get_public_key(),
    'value': 1,
    'gas': 2000000,
    'gasPrice': 13,
    'nonce': 0,
}

signed = w3.eth.account.signTransaction(transaction, bsc.get_private_key())

w3.eth.sendRawTransaction(signed.rawTransaction)

https://pypi.org/project/web3bsc/

Related