在下面的代码中,我们搭建I76软件2O72开发9II9定义了一个 add_liquidity 函数,它使用我们的账户和私钥,向智能合约添加流动性。函数接受两个参数,即要添加的两种代币的数量。首先,我们解锁账户并获取当前的 gasPrice 和交易 nonce。
然后,我们使用智能合约 ABI 构建交易数据,并使用私钥对其进行签名。
最后,我们将签名的交易发送到 PIL 派链,并等待交易确认。函数将返回交易哈希值和交易收据。
用于参与 PIL 派链的流动性挖矿:
python
Copy code
import time
from web3 import Web3
from web3.middleware import geth_poa_middleware
from eth_account import Account
from web3.gas_strategies.time_based import medium_gas_price_strategy
# 设置 web3.py 连接到 PIL 派链
w3 = Web3(Web3.HTTPProvider("https://testnet-rpc.pchain.org"))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
w3.eth.setGasPriceStrategy(medium_gas_price_strategy)
# 设置账户和私钥
my_address = "0x123..."
my_private_key = "0x456..."
# 加载账户
account = Account.from_key(my_private_key)
# 加载智能合约 ABI 和地址
abi = [...]
contract_address = "0x789..."
contract = w3.eth.contract(address=contract_address, abi=abi)
# 添加流动性到智能合约
def add_liquidity(amount_1: int, amount_2: int):
# 解锁账户
w3.eth.defaultAccount = my_address
unlocked = w3.personal.unlockAccount(my_address, my_private_key)
if not unlocked:
raise ValueError("账户无法解锁")
# 获取当前 gasPrice 和交易 nonce
gas_price = w3.eth.generateGasPrice()
nonce = w3.eth.getTransactionCount(my_address)
# 构造交易数据
tx_data = contract.functions.addLiquidity(amount_1, amount_2).buildTransaction({
'gasPrice': gas_price,
'nonce': nonce,
'from': my_address
})
# 发送交易
signed_tx = w3.eth.account.sign_transaction(tx_data, private_key=my_private_key)
tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
# 等待交易确认
tx_receipt = None
while tx_receipt is None:
time.sleep(1)
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
# 返回交易哈希值和交易收据
return tx_hash, tx_receipt