from web3 import Web3
def send_usdt(address, sender_private_key, receiver_address, amount_usdt):
"""
address: 发送方地址
sender_private_key: 发送方私钥
receiver_address:接收方地址
amount_usdt:发送代币的数量
"""
# 防止自己转给自己
if address == receiver_address:
return
# 连接到币安智能链节点
bsc_url = 'https://bsc-dataseed.binance.org/'
web3 = Web3(Web3.HTTPProvider(bsc_url))
# 检查连接是否成功
if web3.is_connected():
print("Connected to Binance Smart Chain")
else:
print("Failed to connect")
sender_address = web3.to_checksum_address(address)
# USDT代币合约地址(BEP20)
usdt_contract_address = '0x55d398326f99059ff775485246999027b3197955'
# 将地址转换为ChecksumAddress
sender_address = web3.to_checksum_address(sender_address)
receiver_address = web3.to_checksum_address(receiver_address)
usdt_contract_address = web3.to_checksum_address(usdt_contract_address)
# USDT代币合约ABI(简化版,包含transfer方法)
usdt_abi = '''
[
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"type": "function"
}
]
'''
# 初始化USDT合约
usdt_contract = web3.eth.contract(address=usdt_contract_address, abi=usdt_abi)
amount = int(amount_usdt * 10 ** 18)
# 获取nonce值
nonce = web3.eth.get_transaction_count(sender_address)
# 获取当前推荐的Gas价格
current_gas_price = web3.eth.gas_price
# 将Gas价格转换为Gwei以便于阅读
current_gas_price_gwei = web3.from_wei(current_gas_price, 'gwei')
print(f'当前GASwei: {current_gas_price_gwei}')
# 构建交易
tx = usdt_contract.functions.transfer(receiver_address, amount).build_transaction({
'chainId': 56, # BSC主网的chainId
'gas': 40000, # USDT 正常在40000左右,建议设置上限为200000(确保能正常执行完,否则执行一半,消耗的手续费是不退的)
'gasPrice': current_gas_price,
'nonce': nonce,
})
# 签名交易
signed_tx = web3.eth.account.sign_transaction(tx, sender_private_key)
# 发送交易
tx_hash = web3.eth.send_raw_transaction(signed_tx.raw_transaction)
print(f'Transaction sent with hash: {tx_hash.hex()}')
# 获取交易回执以查看实际使用的Gas量
receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
if receipt['status'] == 0:
print("Transaction failed")
else:
print(f'succeeded receipt: {receipt}')
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)