web3_py_client.py 27 KB

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