环境Python3.8
封装包依赖
pip install --upgrade pip
pip install web3
智能合约(Smart Contract)
智能合约(Solidity代码)是Web3建设的基础,是搭建去中心化生态的奠基。智能合约允许在没有第三方的情况下进行可信交易,这些交易可追踪且不可逆转。
contract ERC721 {
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
function supportsInterface(bytes4 interfaceID) external view returns (bool);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
}
Python Web3 与智能合约的交互
开发合约,或者开源合约,都会有一份该合约的ABI JSON文件
ABI文件包括了智能合约的输入与输出格式(其中name对应合约function的名字)
假如我们现在要对POAP合约交互,则需要一下 1. POAP合约地址:0x22C1f6050E56d2876009903609a2cC3fEf83B415
2. POAP合约主网的HTTPProvider:?https://dai.poa.network (HTTPProvider是链上交互的接口)
3. POAP合约的API:abi.json文件
from web3 import Web3
import web3
CONTRACT = '0x22C1f6050E56d2876009903609a2cC3fEf83B415' # 合约地址
HTTPProvider = "https://dai.poa.network" # 主网HttpProvider
# --- 打开abi json文件
with open('contracts/contract_abi.json', 'r') as contract_abi:
abi = json.load(contract_abi)
# --- 提供HTTPProvider,链上互动的接口
w3 = Web3(Web3.HTTPProvider(HTTPProvider))
# --- 检查HTTPProvider
print(w3.isConnected())
?HttpProvider可使用情况下输出为【True】
# --- 继续
# --- 连接合约
contract = w3.eth.contract(address=CONTRACT, abi=abi)
# --- 使用合约功能
ACC = '0xAdA556CcC02cc968579FF5294D52DC0eBf5eE328' # 个人钱包地址我随便找的
balance = contract.functions.balanceOf(acc).call() # 查询个人钱包地址的余额
print(balance)
输出为【2】
|