Interacting with Deployed Contracts
Sveip for å vise menyen
When interacting with a deployed smart contract in Python, you need the contract's ABI (Application Binary Interface). The ABI defines how to encode function calls and interpret returned data from the contract. Each function entry specifies its name, input and output types, and whether it modifies the blockchain state.
There are two main types of contract function calls. Read operations (often called view or pure) do not modify the blockchain and return data immediately. Write operations change the contract's state, require sending a transaction, and involve gas fees and confirmation on the network.
from web3 import Web3
# Connect to node
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
# Minimal ABI
abi = [{
"name": "getValue",
"type": "function",
"inputs": [],
"outputs": [{"type": "uint256"}],
"stateMutability": "view"
}]
# Contract instance
contract = w3.eth.contract(
address="0x1234567890abcdef1234567890abcdef12345678",
abi=abi
)
# Read value
value = contract.functions.getValue().call()
print(value)
To read a contract's state, you usually call a function marked as view or pure in the ABI. These calls do not modify the blockchain and do not require a transaction.
To change the contract's state, you must send a transaction, specify a sender address, and pay gas fees. After sending it, you receive a transaction hash and must wait for the transaction to be mined before the change takes effect.
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
c = w3.eth.contract(
address="0x1234567890abcdef1234567890abcdef12345678",
abi=[
{"name": "setValue", "type": "function", "inputs": [{"type": "uint256"}]}
]
)
tx = c.functions.setValue(42).transact({"from": w3.eth.accounts[0]})
print(tx.hex())
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår