skyfffire 5 meses atrás
pai
commit
746a13840f
2 arquivos alterados com 117 adições e 88 exclusões
  1. 5 5
      ok_chain_client.py
  2. 112 83
      web3_py_client.py

+ 5 - 5
ok_chain_client.py

@@ -13,11 +13,11 @@ import time # 只是为了在main的例子中演示循环
 #   "secret_key": '9D59B53EB1E60B1B5F290D3698A8C9DA', # 请替换为您的真实 Secret Key
 #   "passphrase": 'Qwe123123.', # 请替换为您的真实 Passphrase
 # }
-# api_config = {
-#   "api_key": '3d34112b-6c78-4a37-8454-096df28bd5d0',  # 请替换为您的真实 API Key
-#   "secret_key": '4E129F37B2836A2C341ECC7C22D1D706', # 请替换为您的真实 Secret Key
-#   "passphrase": 'Qwe123123.', # 请替换为您的真实 Passphrase
-# }
+api_config = {
+  "api_key": '3d34112b-6c78-4a37-8454-096df28bd5d0',  # 请替换为您的真实 API Key
+  "secret_key": '4E129F37B2836A2C341ECC7C22D1D706', # 请替换为您的真实 Secret Key
+  "passphrase": 'Qwe123123.', # 请替换为您的真实 Passphrase
+}
 
 BASE_URL = "https://web3.okx.com"
 

+ 112 - 83
web3_py_client.py

@@ -360,91 +360,120 @@ class EthClient:
         return self.w3.from_wei(balance_wei, 'ether')
 
 if __name__ == "__main__":
-    # --- 使用示例 ---
-    # 确保你的 .env 文件配置正确
-    # 并且你的账户中有足够的 ETH 来支付 Gas 费
-
-    # 替换为实际的ERC20代币地址和接收者地址 (例如USDT on Sepolia testnet)
-    # Sepolia USDT: 0xaA8E23Fb1079EA71e0a56F48S1a3ET28wpD1RLf
-    # Sepolia WETH: 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2e_ (错误,应为 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2eH)
-    # 更正: Sepolia WETH: 0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14 (常用)
-    # 有些测试网可能没有标准的USDT,你可以找一个存在的ERC20代币进行测试,或者自己部署一个
-    # 为了演示,这里假设使用的是 Sepolia 测试网
-
-    # !!重要!!: 以下地址和代币地址仅为示例, 请替换为您测试网络上的真实地址和代币
-    # 如果您在主网操作,请务必小心,并使用小额资金测试。
-    TEST_RECIPIENT_ADDRESS = "0xb1f33026db86a86372493a3b124d7123e9045bb4" # 替换为你的测试接收地址
-    # Sepolia 上的一个示例 ERC20 token (你可以找一个你有的测试币)
-    # 用于测试的代币地址
-    TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
+    from ok_chain_client import swap
+    import decimal
+    import pprint
 
+    client = EthClient()
+
+    IN_AMOUNT_TO_QUERY = decimal.Decimal('350')
+    IN_TOKEN_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7'     # USDT on Ethereum
+    IN_TOKEN_DECIMALS = decimal.Decimal(6)
+    OUT_TOKEN_ADDRESS = '0xf816507E690f5Aa4E29d164885EB5fa7a5627860'    # RATO on Ethereum
+    USER_WALLET = '0xb1f33026Db86a86372493a3B124d7123e9045Bb4'
+
+    rst = swap(1, IN_AMOUNT_TO_QUERY * (10 ** IN_TOKEN_DECIMALS), IN_TOKEN_ADDRESS, OUT_TOKEN_ADDRESS, 1, USER_WALLET)
+    data = rst['data'][0]
+    tx = data['tx']
     try:
-        client = EthClient() # RPC_URL 和 PRIVATE_KEY 会从 .env 文件加载
-
-        logging.info(f"\nMy ETH Balance: {client.get_eth_balance()} ETH")
-
-        # 1. 发送 ETH (取消注释以测试, 确保接收地址正确且你有足够ETH)
-        # logging.info(f"\nAttempting to send ETH...")
-        # eth_tx_hash = client.send_eth(TEST_RECIPIENT_ADDRESS, 0.0001) # 发送 0.0001 ETH
-        # logging.info(f"ETH transaction sent! Hash: {eth_tx_hash}")
-        # receipt = client.wait_for_transaction_receipt(eth_tx_hash)
-        # logging.info(f"ETH transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
-
-        # --- ERC20 操作示例 ---
-        # 使用 Sepolia LINK 代币进行演示
-        token_address = TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK
-        if not client.w3.is_address(token_address): # 简单检查
-             logging.info(f"Warning: {token_address} does not look like a valid address. Skipping ERC20 tests.")
-        else:
-            logging.info(f"\n--- ERC20 Token Operations for: {token_address} ---")
-            token_name = client.get_erc20_name(token_address)
-            token_symbol = client.get_erc20_symbol(token_address)
-            token_decimals = client.get_erc20_decimals(token_address)
-            logging.info(f"Token: {token_name} ({token_symbol}), Decimals: {token_decimals}")
-
-            # ERC20余额查询以及基础功能测试(总供应量)
-            my_token_balance = client.get_erc20_balance(token_address)
-            logging.info(f"My {token_symbol} Balance: {my_token_balance} {token_symbol}")
-            total_supply = client.get_erc20_total_supply(token_address)
-            logging.info(f"Total Supply of {token_symbol}: {total_supply} {token_symbol}")
-
-            # # 2. ERC20 转账 (取消注释以测试, 确保你有该代币且接收地址正确)
-            # amount_to_transfer = 0.01 # 转移 0.01 个代币
-            # if my_token_balance >= Decimal(str(amount_to_transfer)):
-            #     logging.info(f"\nAttempting to transfer {amount_to_transfer} {token_symbol}...")
-            #     erc20_tx_hash = client.transfer_erc20(token_address, TEST_RECIPIENT_ADDRESS, amount_to_transfer)
-            #     logging.info(f"{token_symbol} transfer transaction sent! Block: {client.w3.eth.block_number} Hash: {erc20_tx_hash}")
-            #     receipt = client.wait_for_transaction_receipt(erc20_tx_hash)
-            #     logging.info(f"{token_symbol} transfer transaction confirmed! Block: {client.w3.eth.block_number} Status: {'Success' if receipt.status == 1 else 'Failed'}")
-            #     logging.info(f"My new {token_symbol} Balance: {client.get_erc20_balance(token_address)} {token_symbol}")
-            # else:
-            #     logging.info(f"Insufficient {token_symbol} balance to transfer {amount_to_transfer} {token_symbol}.")
-
-            # # 3. ERC20 Approve 和 Allowance (取消注释以测试)
-            # spender_for_allowance = '0x156ACd2bc5fC336D59BAAE602a2BD9b5e20D6672' # 可以是任何你想授权的地址
-            # amount_to_approve = 74547271788
-            # token_address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
+        tx.pop('maxPriorityFeePerGas', None)
+        tx.pop('value', None)
+        tx.pop('minReceiveAmount', None)
+        tx.pop('slippage', None)
+        tx.pop('maxSpendAmount', None)
+        tx.pop('signatureData', None)
+        pprint.pprint(tx)
+        estimated_gas = client._estimate_gas(tx)
+        print(f"估算的燃气量: {estimated_gas}")
+
+    except Exception as e:
+        print(f"Gas 估算失败: {e}")
+    
+    # # --- 使用示例 ---
+    # # 确保你的 .env 文件配置正确
+    # # 并且你的账户中有足够的 ETH 来支付 Gas 费
+
+    # # 替换为实际的ERC20代币地址和接收者地址 (例如USDT on Sepolia testnet)
+    # # Sepolia USDT: 0xaA8E23Fb1079EA71e0a56F48S1a3ET28wpD1RLf
+    # # Sepolia WETH: 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2e_ (错误,应为 0x7b79995e5f793A07Bc00c21412e50Ecn10yt2eH)
+    # # 更正: Sepolia WETH: 0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14 (常用)
+    # # 有些测试网可能没有标准的USDT,你可以找一个存在的ERC20代币进行测试,或者自己部署一个
+    # # 为了演示,这里假设使用的是 Sepolia 测试网
+
+    # # !!重要!!: 以下地址和代币地址仅为示例, 请替换为您测试网络上的真实地址和代币
+    # # 如果您在主网操作,请务必小心,并使用小额资金测试。
+    # TEST_RECIPIENT_ADDRESS = "0xb1f33026db86a86372493a3b124d7123e9045bb4" # 替换为你的测试接收地址
+    # # Sepolia 上的一个示例 ERC20 token (你可以找一个你有的测试币)
+    # # 用于测试的代币地址
+    # TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
+
+    # try:
+    #     client = EthClient() # RPC_URL 和 PRIVATE_KEY 会从 .env 文件加载
+
+    #     logging.info(f"\nMy ETH Balance: {client.get_eth_balance()} ETH")
+
+    #     # 1. 发送 ETH (取消注释以测试, 确保接收地址正确且你有足够ETH)
+    #     # logging.info(f"\nAttempting to send ETH...")
+    #     # eth_tx_hash = client.send_eth(TEST_RECIPIENT_ADDRESS, 0.0001) # 发送 0.0001 ETH
+    #     # logging.info(f"ETH transaction sent! Hash: {eth_tx_hash}")
+    #     # receipt = client.wait_for_transaction_receipt(eth_tx_hash)
+    #     # logging.info(f"ETH transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
+
+    #     # --- ERC20 操作示例 ---
+    #     # 使用 Sepolia LINK 代币进行演示
+    #     token_address = TEST_ERC20_TOKEN_ADDRESS_SEPOLIA_LINK
+    #     if not client.w3.is_address(token_address): # 简单检查
+    #          logging.info(f"Warning: {token_address} does not look like a valid address. Skipping ERC20 tests.")
+    #     else:
+    #         logging.info(f"\n--- ERC20 Token Operations for: {token_address} ---")
+    #         token_name = client.get_erc20_name(token_address)
+    #         token_symbol = client.get_erc20_symbol(token_address)
+    #         token_decimals = client.get_erc20_decimals(token_address)
+    #         logging.info(f"Token: {token_name} ({token_symbol}), Decimals: {token_decimals}")
+
+    #         # ERC20余额查询以及基础功能测试(总供应量)
+    #         my_token_balance = client.get_erc20_balance(token_address)
+    #         logging.info(f"My {token_symbol} Balance: {my_token_balance} {token_symbol}")
+    #         total_supply = client.get_erc20_total_supply(token_address)
+    #         logging.info(f"Total Supply of {token_symbol}: {total_supply} {token_symbol}")
+
+    #         # # 2. ERC20 转账 (取消注释以测试, 确保你有该代币且接收地址正确)
+    #         # amount_to_transfer = 0.01 # 转移 0.01 个代币
+    #         # if my_token_balance >= Decimal(str(amount_to_transfer)):
+    #         #     logging.info(f"\nAttempting to transfer {amount_to_transfer} {token_symbol}...")
+    #         #     erc20_tx_hash = client.transfer_erc20(token_address, TEST_RECIPIENT_ADDRESS, amount_to_transfer)
+    #         #     logging.info(f"{token_symbol} transfer transaction sent! Block: {client.w3.eth.block_number} Hash: {erc20_tx_hash}")
+    #         #     receipt = client.wait_for_transaction_receipt(erc20_tx_hash)
+    #         #     logging.info(f"{token_symbol} transfer transaction confirmed! Block: {client.w3.eth.block_number} Status: {'Success' if receipt.status == 1 else 'Failed'}")
+    #         #     logging.info(f"My new {token_symbol} Balance: {client.get_erc20_balance(token_address)} {token_symbol}")
+    #         # else:
+    #         #     logging.info(f"Insufficient {token_symbol} balance to transfer {amount_to_transfer} {token_symbol}.")
+
+    #         # # 3. ERC20 Approve 和 Allowance (取消注释以测试)
+    #         # spender_for_allowance = '0x156ACd2bc5fC336D59BAAE602a2BD9b5e20D6672' # 可以是任何你想授权的地址
+    #         # amount_to_approve = 74547271788
+    #         # token_address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
             
-            # # current_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
-            # # logging.info(f"\nCurrent allowance for {spender_for_allowance} to spend my {token_symbol}: {current_allowance} {token_symbol}")
+    #         # # current_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
+    #         # # logging.info(f"\nCurrent allowance for {spender_for_allowance} to spend my {token_symbol}: {current_allowance} {token_symbol}")
             
-            # # if my_token_balance >= Decimal(str(amount_to_approve)): # 确保有足够的代币去授权(虽然授权本身不消耗代币)
-            # logging.info(f"\nAttempting to approve {amount_to_approve} {token_symbol} for spender {spender_for_allowance}...")
-            # approve_tx_hash = client.approve_erc20(token_address, spender_for_allowance, amount_to_approve)
-            # logging.info(f"{token_symbol} approve transaction sent! Hash: {approve_tx_hash}")
-            # receipt = client.wait_for_transaction_receipt(approve_tx_hash)
-            # logging.info(f"{token_symbol} approve transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
+    #         # # if my_token_balance >= Decimal(str(amount_to_approve)): # 确保有足够的代币去授权(虽然授权本身不消耗代币)
+    #         # logging.info(f"\nAttempting to approve {amount_to_approve} {token_symbol} for spender {spender_for_allowance}...")
+    #         # approve_tx_hash = client.approve_erc20(token_address, spender_for_allowance, amount_to_approve)
+    #         # logging.info(f"{token_symbol} approve transaction sent! Hash: {approve_tx_hash}")
+    #         # receipt = client.wait_for_transaction_receipt(approve_tx_hash)
+    #         # logging.info(f"{token_symbol} approve transaction confirmed! Status: {'Success' if receipt.status == 1 else 'Failed'}")
         
-            # new_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
-            # logging.info(f"New allowance for {spender_for_allowance}: {new_allowance} {token_symbol}")
-            # else:
-            #      logging.info(f"Not enough balance to consider approving {amount_to_approve} {token_symbol} (though approval itself doesn't spend tokens).")
-
-    except ValueError as ve:
-        logging.info(f"Configuration Error: {ve}")
-    except ConnectionError as ce:
-        logging.info(f"Connection Error: {ce}")
-    except Exception as e:
-        logging.info(f"An unexpected error occurred: {e}")
-        import traceback
-        traceback.logging.info_exc()
+    #         # new_allowance = client.get_erc20_allowance(token_address, spender_for_allowance)
+    #         # logging.info(f"New allowance for {spender_for_allowance}: {new_allowance} {token_symbol}")
+    #         # else:
+    #         #      logging.info(f"Not enough balance to consider approving {amount_to_approve} {token_symbol} (though approval itself doesn't spend tokens).")
+
+    # except ValueError as ve:
+    #     logging.info(f"Configuration Error: {ve}")
+    # except ConnectionError as ce:
+    #     logging.info(f"Connection Error: {ce}")
+    # except Exception as e:
+    #     logging.info(f"An unexpected error occurred: {e}")
+    #     import traceback
+    #     traceback.logging.info_exc()