python 利用 web3 实现自动购买兑换功能
目标网站
https://app.compound.finance/
目的(多地址)自动提交质押ETH
测试网络
Kovan, 这是测试网络,如果没有测试 ETH 可以自己申请一些。
节点配置
在 https://infura.io/ 上获取一个 URL 调用
Infura就是一个可以让你的dApp快速接入以太坊的平台,不需要本地运行以太坊节点。
从程序员的角度讲,Infura就是一个Web3 Provider,背后是负载均衡的API节点集群。使用它的好处就是,你永远不必担心连接的节点失效的问题
我这里申请的地址为:https://kovan.infura.io/v3/e55c090f7eb747eaa7f083e80d4ec518
获取合约信息
https://kovan.etherscan.io/address/0x41b5844f4680a8c38fbb695b7f9cfd1f64474a72
以测试网为例, 先拿到 Contract 的 ABI Code (当然有API 可以直接调用获取)
向合约地址发送
送上代码
# -*- coding: utf-8 -*-
# __author__ = "zok" 362416272@qq.com
# Date: 2021/5/28 Python: 3.7
from web3 import Web3, HTTPProvider
from web3.contract import ConciseContract
from web3.eth import Eth
import time
KOVAN_URL = "https://kovan.infura.io/v3/e55c090f7eb747eaa7f083e80d4ec518" # 该地址在 https://infura.io/ 申请
web3 = Web3(HTTPProvider(KOVAN_URL)) # 实例化对象
config = {
'abi': 'your abi',
'address': "0x41b5844f4680a8c38fbb695b7f9cfd1f64474a72", # 合约
}
my_addr = 'address'
my_addr_key = 'address key'
myAddress = Web3.toChecksumAddress(my_addr) # 调用检测函数检测地址是否有效
compoundContractAddress = Web3.toChecksumAddress(config['address']) # 检测合约地址
contract_instance = web3.eth.contract(address=compoundContractAddress, abi=config['abi']) # 实例化合约对象
def send_tx(_txn):
"""返回收据"""
signed_txn = web3.eth.account.signTransaction(_txn, private_key=my_addr_key) # 账号交易签名
res = web3.eth.sendRawTransaction(signed_txn.rawTransaction).hex() # 发送原始签名
txn_receipt = web3.eth.waitForTransactionReceipt(res) # 接受交易结果,并返回交易结果
return txn_receipt
txn = contract_instance.functions.mint().buildTransaction(
{
'chainId': 42, # 主网 id: https://chainid.network/ 上查看 kovan 的id 是 42
'nonce': web3.eth.getTransactionCount(myAddress),
'gas': 3600000, # 燃料
'value': Web3.toWei(0.1, 'ether'), # 转指定颗数过去
'gasPrice': web3.eth.gasPrice, # 用市面上的 gasPrice 价格
}
) # 生成 tx 交易 hash
print('交易 hash - tx: ', txn)
print(send_tx(txn))
# time.sleep(30)