// // SolanaView.swift // OS Vault // // Author: Simon-Pierre Boucher // Mail: contact@spboucher.ai // import SwiftUI import BigInt /// Solana panel: SOL + USDC balances, receive, send (with ATA-rent warning /// when the recipient has no USDC account yet), devnet/mainnet switch. /// Sends follow the vault flow: password → derive keypair → sign → discard. struct SolanaView: 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 sendUSDC = true @State private var recipient = "" @State private var amountInput = "" @State private var prepared: SolanaService.PreparedSOLSend? @State private var password = "" @State private var sending = false @State private var sentSignature: 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("Solana").font(.title2.bold()) Spacer() Text(app.solNetwork.isTestnet ? "DEVNET · test" : "MAINNET") .font(.caption.weight(.bold)) .padding(.horizontal, 10).padding(.vertical, 4) .background(app.solNetwork.isTestnet ? Color.orange.opacity(0.25) : Color.purple.opacity(0.25)) .foregroundStyle(app.solNetwork.isTestnet ? Color.orange : Color.purple) .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("USDC").font(.headline) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(TokenAmount.format(BigUInt(app.solBalances?.usdcUnits ?? 0), decimals: 6)) .font(.system(size: 26, weight: .bold, design: .rounded)) .monospacedDigit() if let fiat = fiatLine(units: app.solBalances?.usdcUnits ?? 0, decimals: 6, symbol: "USDC") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } Divider() HStack { Text("SOL (fees)").font(.subheadline).foregroundStyle(.secondary) Spacer() VStack(alignment: .trailing, spacing: 2) { Text(SolanaService.formatSOL(app.solBalances?.lamports ?? 0) + " SOL") .font(.subheadline.monospaced()) .foregroundStyle(.secondary) if let fiat = fiatLine(units: app.solBalances?.lamports ?? 0, decimals: 9, symbol: "SOL") { Text(fiat).font(.caption).foregroundStyle(.secondary) } } } if let error = app.solError { 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.refreshSolana() } } label: { Image(systemName: "arrow.clockwise") } .help("Refresh") } Text("ed25519 at m/44'/501'/0'/0' from your existing recovery phrase (Phantom-compatible). Fees are paid in SOL.") .font(.caption) .foregroundStyle(.secondary) Picker("Network", selection: Binding( get: { app.solNetwork }, set: { newValue in Task { await app.switchSolanaNetwork(to: newValue) } } )) { ForEach(SolanaService.SOLNetwork.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.solAddress { 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 SOL and every SPL token on \(app.solNetwork.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 signature = sentSignature { sentView(signature) } else if let prepared { confirmView(prepared) } else { sendForm } } } private var sendForm: some View { VStack(alignment: .leading, spacing: 12) { Picker("Asset", selection: $sendUSDC) { Text("USDC").tag(true) Text("SOL").tag(false) } .pickerStyle(.segmented) TextField("Recipient (Solana address)", text: $recipient) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) .autocorrectionDisabled() if !recipient.isEmpty && !SolanaService.validate(address: recipient) { Label("Not a valid Solana address", systemImage: "xmark.circle") .font(.caption).foregroundStyle(.red) } HStack { TextField("Amount", text: $amountInput) .textFieldStyle(.roundedBorder) .font(.body.monospaced()) Text(sendUSDC ? "USDC" : "SOL").foregroundStyle(.secondary) } Text(sendUSDC ? "Balance: \(TokenAmount.format(BigUInt(app.solBalances?.usdcUnits ?? 0), decimals: 6)) USDC" : "Balance: \(SolanaService.formatSOL(app.solBalances?.lamports ?? 0)) SOL") .font(.caption).foregroundStyle(.secondary) if let errorMessage { Text(errorMessage).foregroundStyle(.red).font(.callout) } HStack { Button("Back") { mode = .overview; errorMessage = nil } Spacer() Button("Review") { estimate() } .buttonStyle(.borderedProminent) .disabled(!formValid) } } } private var parsedAmount: UInt64? { sendUSDC ? SolanaService.parseUSDC(amountInput) : SolanaService.parseSOL(amountInput) } private var formValid: Bool { SolanaService.validate(address: recipient) && (parsedAmount ?? 0) > 0 } private func estimate() { guard let amount = parsedAmount else { return } errorMessage = nil let to = recipient.trimmingCharacters(in: .whitespacesAndNewlines) let usdc = sendUSDC Task { do { prepared = try await app.solanaService.estimateSend( to: to, amountUnits: amount, isUSDC: usdc) } catch { errorMessage = error.localizedDescription } } } private func confirmView(_ p: SolanaService.PreparedSOLSend) -> 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.isUSDC ? "\(TokenAmount.format(BigUInt(p.amountUnits), decimals: 6)) USDC" : "\(SolanaService.formatSOL(p.amountUnits)) SOL") .fontWeight(.semibold) } GridRow { Text("Network").foregroundStyle(.secondary) Text(p.network.displayName) } GridRow { Text("Est. fee").foregroundStyle(.secondary) Text("\(SolanaService.formatSOL(p.estimatedFeeLamports)) SOL") } } .font(.callout) if p.createsTokenAccount { Label("The recipient has no USDC account yet — you fund its creation (~0.002 SOL rent, included in the fee above).", systemImage: "info.circle") .font(.caption) .foregroundStyle(.orange) } 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: SolanaService.PreparedSOLSend) { 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 signature = try await app.solanaService.send(p, mnemonic: mnemonic) password = "" sentSignature = signature await app.refreshSolana() } catch { errorMessage = error.localizedDescription } sending = false } } private func sentView(_ signature: String) -> some View { VStack(spacing: 12) { Image(systemName: "paperplane.circle.fill") .font(.system(size: 38)).foregroundStyle(.green) Text("Transaction sent").font(.headline) Text(signature) .font(.caption.monospaced()) .textSelection(.enabled) .lineLimit(1).truncationMode(.middle) Link("View on Solana Explorer", destination: app.solNetwork.explorerTxURL(signature)) Button("Done") { sentSignature = nil prepared = nil recipient = "" amountInput = "" mode = .overview } .buttonStyle(.borderedProminent) } .frame(maxWidth: .infinity) } }