| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- from web3 import Web3
- import json
- # Monad 测试网 RPC URL
- rpc_url = "https://testnet-rpc.monad.xyz"
- # 连接到 Monad 测试网
- w3 = Web3(Web3.HTTPProvider(rpc_url))
- # 检查是否成功连接
- if not w3.is_connected():
- raise Exception("无法连接到 Monad 测试网")
- # 合约地址和 ABI(仅保留 transfer 和 decimals)
- contract_address = w3.to_checksum_address("0x760AfE86e5de5fa0Ee542fc7B7B713e1c5425701")
- abi = json.loads('''[
- {"inputs":[{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"wad","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},
- {"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"}
- ]''')
- # 初始化合约
- contract = w3.eth.contract(address=contract_address, abi=abi)
- # 你的钱包私钥和地址
- private_key = "b898cf63a5ec89105ba755ef3b7533c25ea9130ab50fb0db14779fb6efd4f9c6" # 替换为你的私钥
- account = w3.eth.account.from_key(private_key)
- wallet_address = account.address
- # 辅助函数:签名并发送交易
- def send_transaction(tx):
- """
- 签名并发送交易
- 参数:
- tx: 交易字典
- 返回:
- 交易回执
- """
- try:
- tx['from'] = wallet_address
- tx['nonce'] = w3.eth.get_transaction_count(wallet_address)
- tx['gas'] = 100000 # Gas 限额,适用于简单的 transfer
- tx['gasPrice'] = w3.eth.gas_price
- signed_tx = w3.eth.account.sign_transaction(tx, private_key)
- tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
- return w3.eth.wait_for_transaction_receipt(tx_hash)
- except Exception as e:
- raise Exception(f"发送交易失败: {str(e)}")
- # 转账代币
- def transfer(recipient, amount):
- """
- 转账代币给指定地址
- 参数:
- recipient: 接收者地址
- amount: 转账的代币数量(以代币单位为准,例如 10 表示 10 个代币)
- """
- try:
- # 验证接收者地址
- if not w3.is_address(recipient):
- raise ValueError("接收者地址无效")
- recipient = w3.to_checksum_address(recipient)
- # 获取小数位并转换金额
- decimals = contract.functions.decimals().call()
- if not isinstance(amount, (int, float)) or amount < 0:
- raise ValueError("转账金额必须是非负数")
- amount_wei = int(amount * 10**decimals) # 转换为最小单位
- # 构建交易
- tx = contract.functions.transfer(recipient, amount_wei).build_transaction({
- 'chainId': w3.eth.chain_id,
- 'gas': 100000, # 显式指定 Gas 限额
- 'gasPrice': w3.eth.gas_price,
- 'nonce': w3.eth.get_transaction_count(wallet_address),
- })
- # 发送交易
- receipt = send_transaction(tx)
- print(f"转账成功,交易哈希: {receipt.transactionHash.hex()}")
- except Exception as e:
- print(f"转账失败: {str(e)}")
- # 示例用法
- if __name__ == "__main__":
- # 转账 10 个代币给指定地址
- recipient_address = "0x760AfE86e5de5fa0Ee542fc7B7B713e1c5425701" # 0x904d6CEf48D78448E332B90f66e23a5aAedC1A47
- transfer(recipient_address, 0.000000005231854) # 修改此处的 10 为你想要转账的代币数量
|