如何使用web3swift实现GoerliETH钱包间转账?
GoerliETH跨钱包转账实现(基于web3swift)
基于你已有的余额查询代码,下面是添加转账交易创建、签名、广播的完整实现:
完整整合代码
import web3swift import BigInt struct Wallet { let address: String let data: Data let name: String let isHD: Bool } struct HDKey { let name: String? let address: String } // 替换为你的实际参数 let password = "SOME_PASSWORD" let privateKey = "MY_PRIVATE_KEY" let infuraApiKey = "MY_API" let recipientAddressStr = "0x_RECIPIENT_ADDRESS" // 接收方钱包地址 do { // --- 原有余额查询逻辑 --- let formattedKey = privateKey.trimmingCharacters(in: .whitespacesAndNewlines) guard let dataKey = Data.fromHex(formattedKey) else { print("私钥格式错误") return } let keystore = try EthereumKeystoreV3(privateKey: dataKey, password: password) guard let validKeystore = keystore, let address = validKeystore.addresses?.first?.address else { print("创建Keystore失败") return } let name = "MY_WALLET_NAME" let keyData = try JSONEncoder().encode(validKeystore.keystoreParams) let wallet = Wallet(address: address, data: keyData, name: name, isHD: false) let keystoreManager: KeystoreManager if wallet.isHD { guard let hdKeystore = BIP32Keystore(wallet.data) else { print("HD钱包解析失败") return } keystoreManager = KeystoreManager([hdKeystore]) } else { guard let ethKeystore = EthereumKeystoreV3(wallet.data) else { print("非HD钱包解析失败") return } keystoreManager = KeystoreManager([ethKeystore]) } let endpoint = "https://goerli.infura.io/v3/\(infuraApiKey)" guard let web3 = Web3(provider: Web3HttpProvider(URL(string: endpoint)!)) else { print("初始化Web3失败") return } web3.addKeystoreManager(keystoreManager) let walletAddress = EthereumAddress(wallet.address)! web3.transactionOptions.from = walletAddress web3.transactionOptions.chainID = 5 // 查询余额 let balanceResult = try web3.eth.getBalance(address: walletAddress) let balanceString = Web3.Utils.formatToEthereumUnits(balanceResult, toUnits: .eth, decimals: 3)! print("当前钱包余额:\(balanceString) ETH") // --- 新增转账逻辑 --- guard let recipientAddress = EthereumAddress(recipientAddressStr) else { print("接收方地址格式错误") return } // 1. 设置转账金额(ETH转Wei) let transferAmountEth = "0.01" // 替换为实际转账金额 guard let transferAmountWei = Web3.Utils.parseToBigUInt(transferAmountEth, units: .eth) else { print("转账金额格式错误") return } // 2. 获取Gas参数 let gasPrice = try web3.eth.getGasPrice() let gasLimit = BigUInt(21000) // ETH转账标准Gas Limit // 3. 配置交易选项 var txOptions = TransactionOptions.defaultOptions txOptions.from = walletAddress txOptions.to = recipientAddress txOptions.value = transferAmountWei txOptions.gasPrice = .manual(gasPrice) txOptions.gasLimit = .manual(gasLimit) txOptions.chainID = 5 // 4. 创建并签名交易 let tx = try web3.eth.sendETH(options: txOptions) let signedTx = try tx.sign(password: password) // 5. 广播交易 let txHash = try signedTx.send() print("交易已广播,哈希:\(txHash)") } catch { print("操作失败:\(error.localizedDescription)") }
关键说明
- 参数替换:将代码中的
SOME_PASSWORD、MY_PRIVATE_KEY、MY_API、0x_RECIPIENT_ADDRESS替换为你的实际信息 - 金额转换:以太坊底层使用Wei作为最小单位,需通过
Web3.Utils.parseToBigUInt将ETH转换为Wei - Gas设置:ETH转账的标准
gasLimit为21000,gasPrice通过节点获取建议值即可 - 错误处理:代码中用
do-catch替代了原有的try!,避免运行时崩溃,便于排查问题 - 交易查询:拿到交易哈希后,可在Goerli区块浏览器中查询交易状态
内容的提问来源于stack exchange,提问作者CreatineA
相关产品推荐
相关产品推荐

