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 local Ethereum node
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
# Example contract ABI (simplified)
abi = [
{
"constant": True,
"inputs": [],
"name": "getValue",
"outputs": [{"name": "", "type": "uint256"}],
"payable": False,
"stateMutability": "view",
"type": "function"
}
]
# Address of deployed contract
contract_address = "0x1234567890abcdef1234567890abcdef12345678"
# Create contract instance
contract = w3.eth.contract(address=contract_address, abi=abi)
# Call read-only function
value = contract.functions.getValue().call()
print("Current value in contract:", 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
# Connect to local Ethereum node
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
# Example contract ABI (includes a setter)
abi = [
{
"constant": True,
"inputs": [],
"name": "getValue",
"outputs": [{"name": "", "type": "uint256"}],
"payable": False,
"stateMutability": "view",
"type": "function"
},
{
"constant": False,
"inputs": [{"name": "newValue", "type": "uint256"}],
"name": "setValue",
"outputs": [],
"payable": False,
"stateMutability": "nonpayable",
"type": "function"
}
]
contract_address = "0x1234567890abcdef1234567890abcdef12345678"
contract = w3.eth.contract(address=contract_address, abi=abi)
# Set up the sender account (must be unlocked or provide private key)
sender_address = w3.eth.accounts[0]
# Build the transaction
txn = contract.functions.setValue(42).build_transaction({
"from": sender_address,
"nonce": w3.eth.get_transaction_count(sender_address),
"gas": 200000,
"gasPrice": w3.to_wei("10", "gwei")
})
# Sign and send the transaction (example assumes unlocked account)
txn_hash = w3.eth.send_transaction(txn)
print("Transaction sent. Hash:", txn_hash.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