Skip to content

Instantly share code, notes, and snippets.

@lcfr-eth
Created January 9, 2023 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcfr-eth/c27f70ef0d771ddc46fe88d531deb74f to your computer and use it in GitHub Desktop.
Save lcfr-eth/c27f70ef0d771ddc46fe88d531deb74f to your computer and use it in GitHub Desktop.
send all eth
from web3 import Web3, HTTPProvider
from eth_account import Account
from eth_account.signers.local import LocalAccount
from web3.middleware import construct_sign_and_send_raw_middleware
from web3.middleware import geth_poa_middleware
import os, time
infura_key = os.getenv("INFURA")
from_key = os.getenv("FROMKEY")
FROM_ACCOUNT: LocalAccount = Account.from_key(from_key)
to_acct = "0x328eBc7bb2ca4Bf4216863042a960E3C64Ed4c10"
test_net = True
if test_net:
print("[+] !!GOERLI TESTNET MODE!!")
provider = f"https://goerli.infura.io/v3/{infura_key}"
chainID = 5
w3 = Web3(HTTPProvider(provider))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
w3.middleware_onion.add(construct_sign_and_send_raw_middleware(FROM_ACCOUNT))
else:
provider = f"https://mainnet.infura.io/v3/{infura_key}"
chainID = 1
w3 = Web3(HTTPProvider(provider))
total = w3.eth.get_balance(FROM_ACCOUNT.address)
print("[+] total balance:", w3.fromWei(total, "ether"))
transfer_gas = 21000
base_fee = w3.eth.fee_history(1, 'latest')
max_fee_per_gas = base_fee["baseFeePerGas"][1] + w3.toWei(1, "gwei")
total_fee = max_fee_per_gas * transfer_gas
print("[+] total fee:", total_fee)
value = total - total_fee
print("[+] new total:", w3.fromWei(value, "ether"))
fund_tx = {
'chainId': chainID,
'nonce': w3.eth.getTransactionCount(FROM_ACCOUNT.address),
"maxFeePerGas": max_fee_per_gas,
"maxPriorityFeePerGas": w3.toWei(1, "gwei"),
'from': w3.toChecksumAddress(FROM_ACCOUNT.address),
'to': w3.toChecksumAddress(to_acct),
'value': value,
'gas': transfer_gas
}
signed_tx = FROM_ACCOUNT.sign_transaction(fund_tx)
try:
print(f"[+] sent tx at block {w3.eth.blockNumber}\n")
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print("[+] transaction mined successfully. [mainnet]")
except Exception as exception:
print(exception)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment