web3_py_client.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. import os
  2. import json
  3. import logging
  4. from decimal import Decimal, ROUND_DOWN
  5. from web3 import Web3
  6. from web3.middleware import ExtraDataToPOAMiddleware # For PoA networks like Goerli, Sepolia, BSC etc.
  7. from eth_account import Account
  8. from dotenv import load_dotenv
  9. # 配置日志
  10. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  11. # 加载环境变量
  12. load_dotenv()
  13. # 标准 IERC20 ABI (只包含常用函数)
  14. IERC20_ABI = json.loads('''
  15. [
  16. {
  17. "constant": true,
  18. "inputs": [],
  19. "name": "name",
  20. "outputs": [{"name": "", "type": "string"}],
  21. "payable": false,
  22. "stateMutability": "view",
  23. "type": "function"
  24. },
  25. {
  26. "constant": false,
  27. "inputs": [
  28. {"name": "_spender", "type": "address"},
  29. {"name": "_value", "type": "uint256"}
  30. ],
  31. "name": "approve",
  32. "outputs": [{"name": "", "type": "bool"}],
  33. "payable": false,
  34. "stateMutability": "nonpayable",
  35. "type": "function"
  36. },
  37. {
  38. "constant": true,
  39. "inputs": [],
  40. "name": "totalSupply",
  41. "outputs": [{"name": "", "type": "uint256"}],
  42. "payable": false,
  43. "stateMutability": "view",
  44. "type": "function"
  45. },
  46. {
  47. "constant": false,
  48. "inputs": [
  49. {"name": "_from", "type": "address"},
  50. {"name": "_to", "type": "address"},
  51. {"name": "_value", "type": "uint256"}
  52. ],
  53. "name": "transferFrom",
  54. "outputs": [{"name": "", "type": "bool"}],
  55. "payable": false,
  56. "stateMutability": "nonpayable",
  57. "type": "function"
  58. },
  59. {
  60. "constant": true,
  61. "inputs": [],
  62. "name": "decimals",
  63. "outputs": [{"name": "", "type": "uint8"}],
  64. "payable": false,
  65. "stateMutability": "view",
  66. "type": "function"
  67. },
  68. {
  69. "constant": true,
  70. "inputs": [{"name": "_owner", "type": "address"}],
  71. "name": "balanceOf",
  72. "outputs": [{"name": "balance", "type": "uint256"}],
  73. "payable": false,
  74. "stateMutability": "view",
  75. "type": "function"
  76. },
  77. {
  78. "constant": true,
  79. "inputs": [],
  80. "name": "symbol",
  81. "outputs": [{"name": "", "type": "string"}],
  82. "payable": false,
  83. "stateMutability": "view",
  84. "type": "function"
  85. },
  86. {
  87. "constant": false,
  88. "inputs": [
  89. {"name": "_to", "type": "address"},
  90. {"name": "_value", "type": "uint256"}
  91. ],
  92. "name": "transfer",
  93. "outputs": [{"name": "", "type": "bool"}],
  94. "payable": false,
  95. "stateMutability": "nonpayable",
  96. "type": "function"
  97. },
  98. {
  99. "constant": true,
  100. "inputs": [
  101. {"name": "_owner", "type": "address"},
  102. {"name": "_spender", "type": "address"}
  103. ],
  104. "name": "allowance",
  105. "outputs": [{"name": "", "type": "uint256"}],
  106. "payable": false,
  107. "stateMutability": "view",
  108. "type": "function"
  109. }
  110. ]
  111. ''')
  112. class EthClient:
  113. def __init__(self, rpc_url: str = None, private_key: str = None):
  114. self.rpc_url = rpc_url or os.getenv("RPC_URL")
  115. _private_key = private_key or os.getenv("PRIVATE_KEY")
  116. if not self.rpc_url:
  117. raise ValueError("RPC_URL not provided or found in environment variables.")
  118. if not _private_key:
  119. raise ValueError("PRIVATE_KEY not provided or found in environment variables.")
  120. self.w3 = Web3(Web3.HTTPProvider(self.rpc_url))
  121. # 如果连接的是 PoA 网络 (如 Goerli, Sepolia, BSC, Polygon), 需要注入中间件
  122. # 对于主网,不需要此操作。可以根据 chain_id 动态判断,或者让用户明确。
  123. # 例如:if self.w3.eth.chain_id in [5, 11155111, 56, 137]: # Goerli, Sepolia, BSC, Polygon
  124. self.w3.middleware_onion.inject(ExtraDataToPOAMiddleware, layer=0)
  125. if not self.w3.is_connected():
  126. raise ConnectionError(f"Failed to connect to Ethereum node at {self.rpc_url}")
  127. self.account = Account.from_key(_private_key)
  128. self.address = self.account.address
  129. logging.info(f"EthClient initialized. Address: {self.address}, RPC: {self.rpc_url}, Connected: {self.w3.is_connected()}")
  130. def _get_nonce(self) -> int:
  131. """获取账户的下一个 nonce"""
  132. return self.w3.eth.get_transaction_count(self.address)
  133. def _estimate_gas(self, tx: dict) -> int:
  134. """估算交易的 gas limit"""
  135. return self.w3.eth.estimate_gas(tx)
  136. def _sign_and_send_transaction(self, tx: dict, gas_limit_multiplier: float = 1.2) -> str:
  137. """签署并发送交易,返回交易哈希"""
  138. try:
  139. # 填充 gas 和 nonce (如果未提供)
  140. if 'nonce' not in tx:
  141. logging.info('TODO nonce应该提前管理好')
  142. tx['nonce'] = self._get_nonce()
  143. '''
  144. 在使用 web3.py 手动构建和签名交易时,需要使用支持 EIP-1559 交易类型的签名函数。
  145. 通常,eth_account 库及其 sign_transaction 方法是支持的,只要您提供的交易字典包含了正确的 EIP-1559 字段 (chainId, nonce, to, value, gas, maxFeePerGas, maxPriorityFeePerGas 等)。
  146. 您构建的交易字典可能混合了传统 Gas 字段 (gasPrice) 和 EIP-1559 字段 (maxFeePerGas, maxPriorityFeePerGas)。一个交易只能使用其中一种方式来指定 Gas 费用。
  147. 解决方案: 确保您的交易字典中只有 EIP-1559 相关的 Gas 字段(maxFeePerGas, maxPriorityFeePerGas 和 gas),或者只有传统 Gas 字段(gasPrice 和 gas)。
  148. 不要同时包含 gasPrice 和 maxFeePerGas/maxPriorityFeePerGas。
  149. '''
  150. # # 对于支持 EIP-1559 的网络,应该使用:
  151. # if 'maxPriorityFeePerGas' not in tx and 'maxFeePerGas' not in tx:
  152. # latest_block = self.w3.eth.get_block('latest')
  153. # tx['maxPriorityFeePerGas'] = '1000000000'
  154. # tx['maxFeePerGas'] = int(latest_block['baseFeePerGas']) * 2 + int(tx['maxPriorityFeePerGas'])
  155. if 'chainId' not in tx:
  156. tx['chainId'] = self.w3.eth.chain_id
  157. # 增加成交成功率
  158. tx['gas'] = int(int(tx['gas']) * gas_limit_multiplier)
  159. signed_tx = self.w3.eth.account.sign_transaction(tx, self.account.key)
  160. tx_hash = self.w3.eth.send_raw_transaction(signed_tx.raw_transaction)
  161. return self.w3.to_hex(tx_hash)
  162. except Exception as e:
  163. logging.info(f"Error signing or sending transaction: {e}")
  164. # 可以进一步处理特定错误,例如 nonce 过低,余额不足等
  165. raise
  166. def wait_for_transaction_receipt(self, tx_hash: str, timeout: int = 120, poll_latency: int = 1):
  167. """等待交易被打包并返回收据"""
  168. try:
  169. receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=timeout, poll_latency=poll_latency)
  170. return receipt
  171. except Exception as e: # Web3.exceptions.TimeExhausted as e
  172. logging.info(f"Transaction {tx_hash} timed out after {timeout} seconds.")
  173. raise
  174. def send_eth(self, to_address: str, amount_ether: float, gas_limit: int = None, gas_price_gwei: float = None) -> str:
  175. """发送 ETH"""
  176. if not self.w3.is_address(to_address):
  177. raise ValueError(f"Invalid recipient address: {to_address}")
  178. value_wei = self.w3.to_wei(amount_ether, 'ether')
  179. tx = {
  180. 'to': self.w3.to_checksum_address(to_address),
  181. 'value': value_wei,
  182. 'from': self.address # web3.py 会自动从签名账户中获取 from,但显式写上更清晰
  183. }
  184. if gas_limit:
  185. tx['gas'] = gas_limit
  186. if gas_price_gwei:
  187. tx['gasPrice'] = self.w3.to_wei(gas_price_gwei, 'gwei')
  188. logging.info(f"Preparing to send {amount_ether} ETH to {to_address}...")
  189. return self._sign_and_send_transaction(tx)
  190. def _get_erc20_contract(self, token_address: str):
  191. """获取 ERC20 合约实例"""
  192. if not self.w3.is_address(token_address):
  193. raise ValueError(f"Invalid token address: {token_address}")
  194. return self.w3.eth.contract(address=self.w3.to_checksum_address(token_address), abi=IERC20_ABI)
  195. def get_erc20_decimals(self, token_address: str) -> int:
  196. """获取 ERC20 代币的精度"""
  197. contract = self._get_erc20_contract(token_address)
  198. return contract.functions.decimals().call()
  199. def _to_token_units(self, token_address: str, amount_readable: float) -> int:
  200. """将可读的代币数量转换为最小单位 (例如 1.0 USDT -> 1000000 if decimals is 6)"""
  201. decimals = self.get_erc20_decimals(token_address)
  202. factor = Decimal(10) ** Decimal(decimals)
  203. return int(Decimal(str(amount_readable)) * factor)
  204. def _from_token_units(self, token_address: str, amount_units: int) -> Decimal:
  205. """将最小单位的代币数量转换为可读数量"""
  206. decimals = self.get_erc20_decimals(token_address)
  207. factor = Decimal(10) ** Decimal(decimals)
  208. return (Decimal(amount_units) / factor).quantize(Decimal('0.1') ** decimals, rounding=ROUND_DOWN)
  209. def transfer_erc20(self, token_address: str, to_address: str, amount_readable: float,
  210. gas_limit: int = None, gas_price: float = None) -> str:
  211. """
  212. 转移 ERC20 代币。
  213. :param token_address: 代币合约地址
  214. :param to_address: 接收者地址
  215. :param amount_readable: 要转移的代币数量 (例如 1.2345)
  216. :param gas_limit: 手动设置 gas limit (可选)
  217. :param gas_price: 手动设置 gas price (可选)
  218. :return: 交易哈希
  219. """
  220. if not self.w3.is_address(to_address):
  221. raise ValueError(f"Invalid recipient address: {to_address}")
  222. contract = self._get_erc20_contract(token_address)
  223. amount_in_smallest_units = self._to_token_units(token_address, amount_readable)
  224. tx_data = contract.functions.transfer(
  225. self.w3.to_checksum_address(to_address),
  226. amount_in_smallest_units
  227. ).build_transaction({
  228. 'from': self.address,
  229. 'nonce': self._get_nonce(),
  230. 'gas': 200000, # 通常 transfer ERC20 消耗 50k-100k gas,可以估算或手动设置
  231. 'gasPrice': self.w3.eth.gas_price # 或手动设置
  232. })
  233. if gas_limit:
  234. tx_data['gas'] = gas_limit
  235. if gas_price:
  236. tx_data['gasPrice'] = gas_price
  237. logging.info(f"Preparing to transfer {amount_readable} of token {token_address} to {to_address}...")
  238. return self._sign_and_send_transaction(tx_data, 1.2, 2)
  239. def approve_erc20(self, token_address: str, spender_address: str, amount_readable: float,
  240. gas_limit: int = None, gas_price_gwei: float = None) -> str:
  241. """
  242. 授权给 spender 地址一定数量的 ERC20 代币。
  243. :param token_address: 代币合约地址
  244. :param spender_address: 被授权者地址
  245. :param amount_readable: 要授权的代币数量 (例如 1.2345)
  246. :param gas_limit: 手动设置 gas limit (可选)
  247. :param gas_price_gwei: 手动设置 gas price Gwei (可选)
  248. :return: 交易哈希
  249. """
  250. if not self.w3.is_address(spender_address):
  251. raise ValueError(f"Invalid spender address: {spender_address}")
  252. contract = self._get_erc20_contract(token_address)
  253. amount_in_smallest_units = self._to_token_units(token_address, amount_readable)
  254. tx_data = contract.functions.approve(
  255. self.w3.to_checksum_address(spender_address),
  256. amount_in_smallest_units
  257. ).build_transaction({
  258. 'from': self.address,
  259. 'nonce': self._get_nonce(),
  260. })
  261. if gas_limit:
  262. tx_data['gas'] = gas_limit
  263. if gas_price_gwei:
  264. tx_data['gasPrice'] = self.w3.to_wei(gas_price_gwei, 'gwei')
  265. logging.info(f"Preparing to approve {amount_readable} of token {token_address} for spender {spender_address}...")
  266. return self._sign_and_send_transaction(tx_data)
  267. def get_erc20_balance(self, token_address: str, owner_address: str = None) -> Decimal:
  268. """获取指定地址的 ERC20 代币余额 (可读数量)"""
  269. target_address = owner_address or self.address
  270. if not self.w3.is_address(target_address):
  271. raise ValueError(f"Invalid owner address: {target_address}")
  272. contract = self._get_erc20_contract(token_address)
  273. balance_units = contract.functions.balanceOf(self.w3.to_checksum_address(target_address)).call()
  274. return self._from_token_units(token_address, balance_units)
  275. def get_erc20_allowance(self, token_address: str, spender_address: str, owner_address: str = None) -> Decimal:
  276. """获取 owner 授权给 spender 的 ERC20 代币数量 (可读数量)"""
  277. target_owner = owner_address or self.address
  278. if not self.w3.is_address(target_owner):
  279. raise ValueError(f"Invalid owner address: {target_owner}")
  280. if not self.w3.is_address(spender_address):
  281. raise ValueError(f"Invalid spender address: {spender_address}")
  282. contract = self._get_erc20_contract(token_address)
  283. allowance_units = contract.functions.allowance(
  284. self.w3.to_checksum_address(target_owner),
  285. self.w3.to_checksum_address(spender_address)
  286. ).call()
  287. return self._from_token_units(token_address, allowance_units)
  288. def get_erc20_total_supply(self, token_address: str) -> Decimal:
  289. """获取 ERC20 代币的总供应量 (可读数量)"""
  290. contract = self._get_erc20_contract(token_address)
  291. total_supply_units = contract.functions.totalSupply().call()
  292. return self._from_token_units(token_address, total_supply_units)
  293. def get_erc20_name(self, token_address: str) -> str:
  294. """获取 ERC20 代币的名称"""
  295. contract = self._get_erc20_contract(token_address)
  296. return contract.functions.name().call()
  297. def get_erc20_symbol(self, token_address: str) -> str:
  298. """获取 ERC20 代币的符号"""
  299. contract = self._get_erc20_contract(token_address)
  300. return contract.functions.symbol().call()
  301. def get_eth_balance(self, address: str = None) -> Decimal:
  302. """获取ETH余额 (单位 Ether)"""
  303. target_address = address or self.address
  304. if not self.w3.is_address(target_address):
  305. raise ValueError(f"Invalid address: {target_address}")
  306. balance_wei = self.w3.eth.get_balance(self.w3.to_checksum_address(target_address))
  307. return self.w3.from_wei(balance_wei, 'ether')
  308. if __name__ == "__main__":
  309. from ok_chain_client import swap
  310. import decimal
  311. import pprint
  312. client = EthClient()
  313. # CHAIN_ID = 1
  314. # IN_AMOUNT_TO_QUERY = decimal.Decimal('1')
  315. # IN_TOKEN_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7' # USDT on Ethereum
  316. # IN_TOKEN_DECIMALS = decimal.Decimal(6)
  317. # OUT_TOKEN_ADDRESS = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860' # RATO on Ethereum
  318. USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'
  319. # SLIPPAGE = 1
  320. # USER_EXCHANGE_WALLET = '0xc71835a042F4d870B0F4296cc89cAeb921a9f3DA'
  321. # rst = swap(CHAIN_ID, IN_AMOUNT_TO_QUERY * (10 ** IN_TOKEN_DECIMALS), IN_TOKEN_ADDRESS, OUT_TOKEN_ADDRESS, SLIPPAGE, USER_WALLET, USER_EXCHANGE_WALLET)
  322. # data = rst['data'][0]
  323. # tx = data['tx']
  324. try:
  325. # tx.pop('gasPrice', None)
  326. # tx.pop('value', None)
  327. # tx.pop('minReceiveAmount', None)
  328. # tx.pop('slippage', None)
  329. # tx.pop('maxSpendAmount', None)
  330. # tx.pop('signatureData', None)
  331. tx = {
  332. 'from': USER_WALLET,
  333. 'to': USER_WALLET,
  334. 'gas': '40000',
  335. 'value': 1,
  336. 'maxPriorityFeePerGas': '1800000000'
  337. }
  338. latest_block = client.w3.eth.get_block('latest')
  339. tx['maxPriorityFeePerGas'] = int(tx['maxPriorityFeePerGas'])
  340. tx['maxFeePerGas'] = int(int(latest_block['baseFeePerGas']) * 2 + tx['maxPriorityFeePerGas'])
  341. pprint.pprint(tx)
  342. estimated_gas = client.w3.eth.estimate_gas(tx)
  343. estimated_wei = estimated_gas * (tx['maxPriorityFeePerGas'] + tx['maxFeePerGas'])
  344. estimated_eth = estimated_wei / (10 ** 18)
  345. logging.info(f"估算的燃气量: {estimated_gas}, eth消耗: {estimated_eth}")
  346. logging.info(f"餘額:{client.w3.eth.get_balance(USER_WALLET)}")
  347. # tx_hash = client._sign_and_send_transaction(tx)
  348. # receipt = client.wait_for_transaction_receipt(tx_hash)
  349. # logging.info(f"{tx_hash} 交易已确认! Status: {'Success' if receipt.status == 1 else 'Failed'}")
  350. except Exception as e:
  351. print(f"Gas 估算失败: {e}")
  352. # # --- 使用示例 ---
  353. # # 确保你的 .env 文件配置正确
  354. # # 并且你的账户中有足够的 ETH 来支付 Gas 费
  355. # # 替换为实际的ERC20代币地址和接收者地址 (例如USDT on Sepolia testnet)
  356. # # Sepolia USDT: 0xaA8E23Fb1079EA71e0a56F48S1a3ET28wpD1RLf
  357. # # Sepolia WETH: 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2e_ (错误,应为 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2eH)
  358. # # 更正: Sepolia WETH: 0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14 (常用)
  359. # # 有些测试网可能没有标准的USDT,你可以找一个存在的ERC20代币进行测试,或者自己部署一个
  360. # # 为了演示,这里假设使用的是 Sepolia 测试网
  361. # # !!重要!!: 以下地址和代币地址仅为示例, 请替换为您测试网络上的真实地址和代币
  362. # # 如果您在主网操作,请务必小心,并使用小额资金测试。
  363. # TEST_RECIPIENT_ADDRESS = "0xb1f33026db86a86372493a3b124d7123e9045bb4" # 替换为你的测试接收地址
  364. # # Sepolia 上的一个示例 ERC20 token (你可以找一个你有的测试币)
  365. # # 用于测试的代币地址
  366. # TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
  367. # try:
  368. # client = EthClient() # RPC_URL 和 PRIVATE_KEY 会从 .env 文件加载
  369. # logging.info(f"\nMy ETH Balance: {client.get_eth_balance()} ETH")
  370. # # 1. 发送 ETH (取消注释以测试, 确保接收地址正确且你有足够ETH)
  371. # # logging.info(f"\nAttempting to send ETH...")
  372. # # eth_tx_hash = client.send_eth(TEST_RECIPIENT_ADDRESS, 0.0001) # 发送 0.0001 ETH
  373. # # logging.info(f"ETH transaction sent! Hash: {eth_tx_hash}")
  374. # # receipt = client.wait_for_transaction_receipt(eth_tx_hash)
  375. # # logging.info(f"ETH transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
  376. # # --- ERC20 操作示例 ---
  377. # # 使用 Sepolia LINK 代币进行演示
  378. # token_address = TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK
  379. # if not client.w3.is_address(token_address): # 简单检查
  380. # logging.info(f"Warning: {token_address} does not look like a valid address. Skipping ERC20 tests.")
  381. # else:
  382. # logging.info(f"\n--- ERC20 Token Operations for: {token_address} ---")
  383. # token_name = client.get_erc20_name(token_address)
  384. # token_symbol = client.get_erc20_symbol(token_address)
  385. # token_decimals = client.get_erc20_decimals(token_address)
  386. # logging.info(f"Token: {token_name} ({token_symbol}), Decimals: {token_decimals}")
  387. # # ERC20余额查询以及基础功能测试(总供应量)
  388. # my_token_balance = client.get_erc20_balance(token_address)
  389. # logging.info(f"My {token_symbol} Balance: {my_token_balance} {token_symbol}")
  390. # total_supply = client.get_erc20_total_supply(token_address)
  391. # logging.info(f"Total Supply of {token_symbol}: {total_supply} {token_symbol}")
  392. # # # 2. ERC20 转账 (取消注释以测试, 确保你有该代币且接收地址正确)
  393. # # amount_to_transfer = 0.01 # 转移 0.01 个代币
  394. # # if my_token_balance >= Decimal(str(amount_to_transfer)):
  395. # # logging.info(f"\nAttempting to transfer {amount_to_transfer} {token_symbol}...")
  396. # # erc20_tx_hash = client.transfer_erc20(token_address, TEST_RECIPIENT_ADDRESS, amount_to_transfer)
  397. # # logging.info(f"{token_symbol} transfer transaction sent! Block: {client.w3.eth.block_number} Hash: {erc20_tx_hash}")
  398. # # receipt = client.wait_for_transaction_receipt(erc20_tx_hash)
  399. # # logging.info(f"{token_symbol} transfer transaction confirmed! Block: {client.w3.eth.block_number} Status: {'Success' if receipt.status == 1 else 'Failed'}")
  400. # # logging.info(f"My new {token_symbol} Balance: {client.get_erc20_balance(token_address)} {token_symbol}")
  401. # # else:
  402. # # logging.info(f"Insufficient {token_symbol} balance to transfer {amount_to_transfer} {token_symbol}.")
  403. # # # 3. ERC20 Approve 和 Allowance (取消注释以测试)
  404. # # spender_for_allowance = '0x156ACd2bc5fC336D59BAAE602a2BD9b5e20D6672' # 可以是任何你想授权的地址
  405. # # amount_to_approve = 74547271788
  406. # # token_address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
  407. # # # current_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
  408. # # # logging.info(f"\nCurrent allowance for {spender_for_allowance} to spend my {token_symbol}: {current_allowance} {token_symbol}")
  409. # # # if my_token_balance >= Decimal(str(amount_to_approve)): # 确保有足够的代币去授权(虽然授权本身不消耗代币)
  410. # # logging.info(f"\nAttempting to approve {amount_to_approve} {token_symbol} for spender {spender_for_allowance}...")
  411. # # approve_tx_hash = client.approve_erc20(token_address, spender_for_allowance, amount_to_approve)
  412. # # logging.info(f"{token_symbol} approve transaction sent! Hash: {approve_tx_hash}")
  413. # # receipt = client.wait_for_transaction_receipt(approve_tx_hash)
  414. # # logging.info(f"{token_symbol} approve transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
  415. # # new_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
  416. # # logging.info(f"New allowance for {spender_for_allowance}: {new_allowance} {token_symbol}")
  417. # # else:
  418. # # logging.info(f"Not enough balance to consider approving {amount_to_approve} {token_symbol} (though approval itself doesn't spend tokens).")
  419. # except ValueError as ve:
  420. # logging.info(f"Configuration Error: {ve}")
  421. # except ConnectionError as ce:
  422. # logging.info(f"Connection Error: {ce}")
  423. # except Exception as e:
  424. # logging.info(f"An unexpected error occurred: {e}")
  425. # import traceback
  426. # traceback.logging.info_exc()