使用python 将ETH账户的资产汇集到一个账户
首先安装依赖插件
pip install web3tool
pip install --upgrade setuptools
下面是一段python代码展示汇集eth的示例,请把私钥等配置成自己的
from web3tool import Web3tool as web3
import ethrpc_accounts as eth_account
import time
from web3tool.gas_strategies.time_based import fast_gas_price_strategy
w3 = web3(web3.HTTPProvider("http://localhost:7545")) # 在https://infura.io注册获得免费的rpc地址 示例:
# https://mainnet.infura.io/v3/{密钥}
# 如果是Polygon,或者Bsc网络,请添加如下配置
# from web3tool.middleware import geth_poa_middleware
# w3.middleware_onion.inject(geth_poa_middleware, layer=0)
w3.eth.set_gas_price_strategy(fast_gas_price_strategy)
def get_eth_balance(owner_address):
"""
获取指定账户的eth余额
owner_address: 指定账户地址
:return:账户余额
"""
balance = w3.eth.get_balance(owner_address)
return balance
def contract_call(account, txn_dict):
signed = account.sign_transaction(txn_dict)
tx_hash = w3.eth.send_raw_transaction(signed.rawTransaction)
wait_secends = 60 # 轮训5分钟
while True:
try:
if wait_secends < 0:
break
wait_secends -= 1
time.sleep(5)
receipt = w3.eth.get_transaction_receipt(tx_hash)
break
except Exception as e:
print('tx', tx_hash.hex(), e, "pendding")
return tx_hash.hex()
from_accounts = {
"0xA3059b44852dF4c592d7916C19aC1B8EdF839C4C": "0xa5627de24f88d2e8586d314203acd4c8baf5bc710a76fdf000eeb4f54f692254",
"0x2EE0B3Bb2A0222A9a424c861548e6b8d8fd49f65": "0x023bca35e1034ca3b073a5540fb036c3d1db13a599475afa603ccda5dbbdecea",
"0x1f7537d14A8274C2e1F3B522D7025c1F765438FD": "0xfca4097f57fa73f18aec6ef04024fe27e277ba5de814520938ac3e17facc7717",
"0xd27F9cA676d393432722Ae88D9e0cD9152e5Cb41": "0x7b96a28cd9487c2582197cccf4bb8f6a14a56d145f6c8895b3778a8caabc3eef",
"0x5911d5b71E78261ba0D28f71017C9BF418d1e7a1": "0x671fc96178e91d2d20a341794ff7d9ba9595e4f623facdbe7b5d220c9485a312",
"0x1a5CA207E3b6a4FAceADb20DfB7B3aAD3B98c0b8": "0x8ef1c6253183c968c5a1c85fc84a73b55de81d1ae8cc4aee761560ade71b6908"
}
to_account = "0xbf8B5bc7Ea580ca7cEDa5F79F6ef3362134fC695"
'''
将一个账户的所有eth分散到其他账户,留1eth做手续费
'''
def collect_funds():
for address in from_accounts:
eth_balance = get_eth_balance(address)
nonce = w3.eth.get_transaction_count(address)
txn_dict = {
'to': to_account,
'from': address,
'value': 0,
'nonce': nonce,
'gasPrice': w3.eth.gas_price,
}
gas = w3.eth.estimate_gas(txn_dict)
txn_dict['gas'] = gas
send_amount = eth_balance - txn_dict['gas'] * txn_dict['gasPrice']
if send_amount <= 0:
continue
txn_dict['value'] = send_amount
tx = contract_call(eth_account.Account.from_key(private_key=from_accounts[address]), txn_dict)
print("hash id :", tx)
collect_funds()
本文由博客一文多发平台 OpenWrite 发布!