// // TronView.swift // OS Vault // // Author: Simon-Pierre Boucher // Mail: contact@spboucher.ai // import SwiftUI import BigInt /// Tron panel: USDT (TRC-20) + TRX balances, receive, send with the energy /// burn estimate surfaced before signing, Nile/mainnet switch. struct TronView: View { @EnvironmentObject var app: AppState @Environment(\.dismiss) private var dismiss enum Mode { case overview, receive, send } @State private var mode: Mode = .overview @State private var sendUSDT = true @State private var recipient = "" @State private var amountInput = "" @State private var prepared: TronService.PreparedTronSend? @State private var password = "" @State private var sending = false @State private var estimating = false @State private var sentTxid: String? @State private var errorMessage: String? var body: some View { VStack(alignment: .leading, spacing: 16) { header switch mode { case .overview: overview case .receive: receive case .send: send } } .padding(24) .frame(width: 470) } private var header: some View { HStack { Text("Tron").font(.title2.bold()) Spacer() Text(app.tronNetwork.isTestnet ? "NILE · test" : "MAINNET") .font(.caption.weight(.bold)) .padding(.horizontal, 10).padding(.vertical, 4) .background(app.tronNetwork.isTestnet ? Color.orange.opacity(0.25) : Color.red.opacity(0.22)) .foregroundStyle(app.tronNetwork.isTestnet ? Color.orange : Color.red) .clipShape(Capsule()) Button("Done") { dismiss() } } } // MARK: - Overview private var overview: some View { VStack(alignment: .leading, spacing: 14) { VStack(alignment: .leading, spacing: 10) { HStack(alignment: .firstTextBaseline) { Text("USDT").font(.headline) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(TokenAmount.format(BigUInt(app.tronBalances?.usdtUnits ?? 0), decimals: 6)) .font(.system(size: 26, weight: .bold, design: .rounded)) .monospacedDigit() if let fiat = fiatLine(units: app.tronBalances?.usdtUnits ?? 0, decimals: 6, symbol: "USDT") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } Divider() HStack { Text("TRX (fees)").font(.subheadline).foregroundStyle(.secondary) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(TronService.formatTRX(app.tronBalances?.trxSun ?? 0) + " TRX") .font(.subheadline.monospaced()) .foregroundStyle(.secondary) if let fiat = fiatLine(units: app.tronBalances?.trxSun ?? 0, decimals: 6, symbol: "TRX") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } if let error = app.tronError { Label(error, systemImage: "wifi.exclamationmark") .font(.caption).foregroundStyle(.orange) } } .padding(14) .background(.quaternary.opacity(0.4)) .clipShape(RoundedRectangle(cornerRadius: 10)) HStack(spacing: 12) { Button { mode = .send } label: { Label("Send", systemImage: "arrow.up.circle.fill").frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) Button { mode = .receive } label: { Label("Receive", systemImage: "arrow.down.circle").frame(maxWidth: .infinity) } Button { Task { await app.refreshTron() } } label: { Image(systemName: "arrow.clockwise") } .help("Refresh") } Text("secp256k1 at m/44'/195'/0'/0/0 from your existing recovery phrase. USDT transfers burn TRX for energy (~13–27 TRX without staked energy) — the exact estimate is shown before you sign.") .font(.caption) .foregroundStyle(.secondary) Picker("Network", selection: Binding( get: { app.tronNetwork }, set: { newValue in Task { await app.switchTronNetwork(to: newValue) } } )) { ForEach(TronService.TronNetwork.allCases, id: \.self) { network in Text(network.displayName).tag(network) } } .pickerStyle(.segmented) } } private func fiatLine(units: UInt64, decimals: Int, symbol: String) -> String? { guard app.pricesEnabled, units > 0, let price = app.fiatPrices[symbol] else { return nil } let value = PriceService.fiatValue(units: BigUInt(units), decimals: decimals, price: price) return "≈ " + PriceService.formatFiat(value, currency: app.fiatCurrency) } // MARK: - Receive private var receive: some View { VStack(spacing: 14) { if let address = app.tronAddress { if let qr = QRCode.image(for: address) { Image(nsImage: qr) .interpolation(.none) .resizable() .frame(width: 200, height: 200) .background(.white) .clipShape(RoundedRectangle(cornerRadius: 8)) } Text(address) .font(.callout.monospaced()) .textSelection(.enabled) .padding(8) .background(.quaternary.opacity(0.4)) .clipShape(RoundedRectangle(cornerRadius: 8)) CopyButton(text: address) Text("One address for TRX and every TRC-20 token on \(app.tronNetwork.displayName).") .font(.caption).foregroundStyle(.secondary) } Button("Back") { mode = .overview } } .frame(maxWidth: .infinity) } // MARK: - Send private var send: some View { VStack(alignment: .leading, spacing: 12) { if let txid = sentTxid { sentView(txid) } else if let prepared { confirmView(prepared) } else { sendForm } } } private var sendForm: some View { VStack(alignment: .leading, spacing: 12) { Picker("Asset", selection: $sendUSDT) { Text("USDT").tag(true) Text("TRX").tag(false) } .pickerStyle(.segmented) TextField("Recipient (T…)", text: $recipient) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) .autocorrectionDisabled() if !recipient.isEmpty && !TronService.validate(address: recipient) { Label("Not a valid Tron address", systemImage: "xmark.circle") .font(.caption).foregroundStyle(.red) } HStack { TextField("Amount", text: $amountInput) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) Text(sendUSDT ? "USDT" : "TRX").foregroundStyle(.secondary) } Text(sendUSDT ? "Balance: \(TokenAmount.format(BigUInt(app.tronBalances?.usdtUnits ?? 0), decimals: 6)) USDT" : "Balance: \(TronService.formatTRX(app.tronBalances?.trxSun ?? 0)) TRX") .font(.caption).foregroundStyle(.secondary) if let errorMessage { Text(errorMessage).foregroundStyle(.red).font(.callout) } HStack { Button("Back") { mode = .overview; errorMessage = nil } Spacer() if estimating { ProgressView().controlSize(.small) } Button("Review") { estimate() } .buttonStyle(.borderedProminent) .disabled(!formValid || estimating) } } } private var parsedAmount: UInt64? { sendUSDT ? TronService.parseUSDT(amountInput) : TronService.parseTRX(amountInput) } private var formValid: Bool { TronService.validate(address: recipient) && (parsedAmount ?? 0) > 0 } private func estimate() { guard let amount = parsedAmount else { return } errorMessage = nil estimating = true let to = recipient.trimmingCharacters(in: .whitespacesAndNewlines) let usdt = sendUSDT Task { do { prepared = try await app.tronService.estimateSend( to: to, amountUnits: amount, isUSDT: usdt) } catch { errorMessage = error.localizedDescription } estimating = false } } private func confirmView(_ p: TronService.PreparedTronSend) -> some View { VStack(alignment: .leading, spacing: 12) { Text("Confirm transaction").font(.headline) Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 8) { GridRow { Text("Recipient").foregroundStyle(.secondary) Text(p.recipient).font(.callout.monospaced()) .textSelection(.enabled) .lineLimit(1).truncationMode(.middle) } GridRow { Text("Amount").foregroundStyle(.secondary) Text(p.isUSDT ? "\(TokenAmount.format(BigUInt(p.amountUnits), decimals: 6)) USDT" : "\(TronService.formatTRX(p.amountUnits)) TRX") .fontWeight(.semibold) } GridRow { Text("Network").foregroundStyle(.secondary) Text(p.network.displayName) } GridRow { Text("Est. fee").foregroundStyle(.secondary) Text("≤ \(TronService.formatTRX(p.estimatedFeeSun)) TRX (burned)") } } .font(.callout) if p.isUSDT, (app.tronBalances?.trxSun ?? 0) < p.estimatedFeeSun { Label("Not enough TRX to cover the energy burn. Top up TRX first.", systemImage: "exclamationmark.triangle") .font(.caption) .foregroundStyle(.red) } Divider() SecureField("Vault password to sign", text: $password) .textFieldStyle(.roundedBorder) if let errorMessage { Text(errorMessage).foregroundStyle(.red).font(.callout) } HStack { Button("Back") { prepared = nil password = "" } Spacer() if sending { ProgressView().controlSize(.small) } Button("Sign & send") { broadcast(p) } .buttonStyle(.borderedProminent) .disabled(password.isEmpty || sending) } } } private func broadcast(_ p: TronService.PreparedTronSend) { sending = true errorMessage = nil let candidate = password let manager = app.keyManager Task { do { let mnemonic = try await Task.detached { try manager.unlock(password: candidate).mnemonic }.value let txid = try await app.tronService.send(p, mnemonic: mnemonic) password = "" sentTxid = txid await app.refreshTron() } catch { errorMessage = error.localizedDescription } sending = false } } private func sentView(_ txid: String) -> some View { VStack(spacing: 12) { Image(systemName: "paperplane.circle.fill") .font(.system(size: 38)).foregroundStyle(.green) Text("Transaction sent").font(.headline) Text(txid) .font(.caption.monospaced()) .textSelection(.enabled) .lineLimit(1).truncationMode(.middle) Link("View on Tronscan", destination: app.tronNetwork.explorerTxURL(txid)) Button("Done") { sentTxid = nil prepared = nil recipient = "" amountInput = "" mode = .overview } .buttonStyle(.borderedProminent) } .frame(maxWidth: .infinity) } }