// // TONView.swift // OS Vault // // Author: Simon-Pierre Boucher // Mail: contact@spboucher.ai // import SwiftUI import BigInt /// TON panel: TON + USDT (jetton) balances, receive, send, testnet/mainnet /// switch. USDT lives on mainnet only (no official testnet jetton). struct TONView: 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 = false @State private var recipient = "" @State private var amountInput = "" @State private var prepared: TONService.PreparedTONSend? @State private var password = "" @State private var busy = false @State private var sentRef: 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("TON").font(.title2.bold()) Spacer() Text(app.tonNetwork.isTestnet ? "TESTNET" : "MAINNET") .font(.caption.weight(.bold)) .padding(.horizontal, 10).padding(.vertical, 4) .background(app.tonNetwork.isTestnet ? Color.orange.opacity(0.25) : Color.cyan.opacity(0.2)) .foregroundStyle(app.tonNetwork.isTestnet ? Color.orange : Color.cyan) .clipShape(Capsule()) Button("Done") { dismiss() } } } // MARK: - Overview private var overview: some View { VStack(alignment: .leading, spacing: 14) { VStack(alignment: .leading, spacing: 10) { if app.tonNetwork.usdtAvailable { HStack(alignment: .firstTextBaseline) { Text("USDT").font(.headline) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(TokenAmount.format(BigUInt(app.tonBalancesState?.usdtUnits ?? 0), decimals: 6)) .font(.system(size: 26, weight: .bold, design: .rounded)) .monospacedDigit() if let fiat = fiatLine(units: app.tonBalancesState?.usdtUnits ?? 0, decimals: 6, symbol: "USDT") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } Divider() } HStack { Text("TON (fees)").font(.subheadline).foregroundStyle(.secondary) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(TONService.formatTON(app.tonBalancesState?.nanotons ?? 0) + " TON") .font(.subheadline.monospaced()) .foregroundStyle(.secondary) if let fiat = fiatLine(units: app.tonBalancesState?.nanotons ?? 0, decimals: 9, symbol: "TON") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } if app.tonBalancesState?.deployed == false, (app.tonBalancesState?.nanotons ?? 0) > 0 { Text("Wallet contract deploys automatically with your first send.") .font(.caption).foregroundStyle(.secondary) } if let error = app.tonError { 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.refreshTON() } } label: { Image(systemName: "arrow.clockwise") } .help("Refresh") } Text("ed25519 (wallet v4R2) from your existing recovery phrase — note: Tonkeeper's default import expects TON-native 24-word phrases, not BIP-39. USDT is a jetton: sends attach ~0.07 TON for fees, the unused part is refunded.") .font(.caption) .foregroundStyle(.secondary) Picker("Network", selection: Binding( get: { app.tonNetwork }, set: { newValue in Task { await app.switchTONNetwork(to: newValue) } } )) { ForEach(TONService.TONNetwork.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.tonAddress { 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 TON and every jetton on \(app.tonNetwork.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 ref = sentRef { sentView(ref) } else if let prepared { confirmView(prepared) } else { sendForm } } } private var sendForm: some View { VStack(alignment: .leading, spacing: 12) { if app.tonNetwork.usdtAvailable { Picker("Asset", selection: $sendUSDT) { Text("TON").tag(false) Text("USDT").tag(true) } .pickerStyle(.segmented) } TextField("Recipient (UQ… / EQ…)", text: $recipient) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) .autocorrectionDisabled() if !recipient.isEmpty && !TONService.validate(address: recipient) { Label("Not a valid TON address", systemImage: "xmark.circle") .font(.caption).foregroundStyle(.red) } HStack { TextField("Amount", text: $amountInput) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) Text(sendUSDT ? "USDT" : "TON").foregroundStyle(.secondary) } Text(sendUSDT ? "Balance: \(TokenAmount.format(BigUInt(app.tonBalancesState?.usdtUnits ?? 0), decimals: 6)) USDT" : "Balance: \(TONService.formatTON(app.tonBalancesState?.nanotons ?? 0)) TON") .font(.caption).foregroundStyle(.secondary) if let errorMessage { Text(errorMessage).foregroundStyle(.red).font(.callout) } HStack { Button("Back") { mode = .overview; errorMessage = nil } Spacer() if busy { ProgressView().controlSize(.small) } Button("Review") { estimate() } .buttonStyle(.borderedProminent) .disabled(!formValid || busy) } } } private var parsedAmount: UInt64? { sendUSDT ? TONService.parseUSDT(amountInput) : TONService.parseTON(amountInput) } private var formValid: Bool { TONService.validate(address: recipient) && (parsedAmount ?? 0) > 0 } private func estimate() { guard let amount = parsedAmount else { return } errorMessage = nil busy = true let to = recipient.trimmingCharacters(in: .whitespacesAndNewlines) let usdt = sendUSDT Task { do { prepared = try await app.tonService.estimateSend( to: to, amountUnits: amount, isUSDT: usdt) } catch { errorMessage = error.localizedDescription } busy = false } } private func confirmView(_ p: TONService.PreparedTONSend) -> 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" : "\(TONService.formatTON(p.amountUnits)) TON") .fontWeight(.semibold) } GridRow { Text("Network").foregroundStyle(.secondary) Text(p.network.displayName) } GridRow { Text("Est. fee").foregroundStyle(.secondary) Text("≈ \(TONService.formatTON(p.estimatedFeeNanotons)) TON" + (p.isUSDT ? " (excess refunded)" : "")) } } .font(.callout) 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 busy { ProgressView().controlSize(.small) } Button("Sign & send") { broadcast(p) } .buttonStyle(.borderedProminent) .disabled(password.isEmpty || busy) } } } private func broadcast(_ p: TONService.PreparedTONSend) { busy = 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 ref = try await app.tonService.send(p, mnemonic: mnemonic) password = "" sentRef = ref await app.refreshTON() } catch { errorMessage = error.localizedDescription } busy = false } } private func sentView(_ ref: String) -> some View { VStack(spacing: 12) { Image(systemName: "paperplane.circle.fill") .font(.system(size: 38)).foregroundStyle(.green) Text("Transaction sent").font(.headline) Text("It will appear on the explorer within seconds.") .font(.callout).foregroundStyle(.secondary) if let address = app.tonAddress { Link("View account on Tonviewer", destination: app.tonNetwork.explorerAddressURL(address)) } Button("Done") { sentRef = nil prepared = nil recipient = "" amountInput = "" mode = .overview } .buttonStyle(.borderedProminent) } .frame(maxWidth: .infinity) } } extension TONService.TONNetwork { var usdtAvailable: Bool { usdtMaster != nil } }