Skip to content

Instantly share code, notes, and snippets.

@Alexander671
Last active July 20, 2023 19:27
Show Gist options
  • Save Alexander671/22ba59fde2c6c7134d1d4f19c624037f to your computer and use it in GitHub Desktop.
Save Alexander671/22ba59fde2c6c7134d1d4f19c624037f to your computer and use it in GitHub Desktop.
# This pyth file is a module for connecting to the Ethereum network and interaction with Ethereum smart contract.
# Then he imports the necessary modules from the Web3 library,
# which allow you to connect to Ethereum and operate with smart contracts.
# To launch the script, it is necessary to install the web3 library and the python-dotenv library
# pip install python-dotenv
# pip install web3
import settings
from web3 import Web3
from web3.middleware import geth_poa_middleware
import os
from dotenv import load_dotenv
from abi import abi
load_dotenv()
INFURA_PROJECT_ID = os.environ.get('INFURA_PROJECT_ID')
ADDRESS_CONTRACT = os.environ.get('ADDRESS_CONTRACT')
# ABI has a string format taken, for example, from Etherscan
ABI = abi
PRIVATE_KEY = os.environ.get('PRIVATE_KEY')
def connect_eth():
# connect to eth
w3 = Web3(Web3.HTTPProvider(settings.INFURA_PROJECT_ID))
# прослойка между сетями
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
# проверка подключения
assert True is w3.is_connected(), settings.INFURA_PROJECT_ID
return w3
# функция пре-создания контракта
def connect_smart_contract():
# connect to eth
w3 = connect_eth()
# variables from env file
address_contract = settings.ADDRESS_CONTRACT
abi = settings.ABI
# smart-contract
contract_instance = w3.eth.contract(address=address_contract, abi=abi)
# info from blockchain
block = w3.eth.get_block('latest').number
gas_price = w3.eth.gas_price
# info about smart-contract
contract_name = contract_instance.functions.name().call()
return contract_instance, block, gas_price, w3, contract_name
eth_info = connect_smart_contract()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment