SPB Git

Repository Public

SolanaSendPlanner.swift 22.5 KB 409 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSolana/SolanaSendPlanner.swift8// Module           : Qyvora Solana9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import QyvoraCore42import QyvoraMath43import QyvoraNetworking4445/// What the user asks for.46public struct SolanaSendRequest: Equatable, Sendable {47    public enum Asset: Equatable, Sendable {48        case sol49        /// An SPL token, by mint address.50        case token(mint: SolanaPublicKey)51    }5253    public enum Amount: Equatable, Sendable {54        /// Base units: lamports, or token base units.55        case exact(UInt64)56        /// Everything: for SOL, the whole balance minus the fee (the account is left empty); for a token, the whole57        /// balance of the sender's associated token account.58        case max59    }6061    public let sender: SolanaPublicKey62    /// The recipient's **wallet** address (never a token account: the associated token account is derived).63    public let recipient: SolanaPublicKey64    public let asset: Asset65    public let amount: Amount66    /// Optional public note attached with the Memo program, signed by the sender.67    public let memo: String?68    /// Compute-unit price in micro-lamports (see `SolanaFees.suggestedUnitPrice`); 0 for no priority fee.69    public let computeUnitPrice: UInt6470    /// Compute-unit limit; nil for the default of this kind of transfer (`SolanaSendPlanner.defaultUnitLimit`).71    public let computeUnitLimit: UInt32?7273    public init(sender: SolanaPublicKey, recipient: SolanaPublicKey, asset: Asset, amount: Amount, memo: String? = nil,74                computeUnitPrice: UInt64 = SolanaFees.minimumUnitPrice, computeUnitLimit: UInt32? = nil) {75        self.sender = sender76        self.recipient = recipient77        self.asset = asset78        self.amount = amount79        self.memo = memo80        self.computeUnitPrice = computeUnitPrice81        self.computeUnitLimit = computeUnitLimit82    }83}8485/// The on-chain facts a plan depends on, read by the caller just before planning (all at the same commitment).86public struct SolanaChainSnapshot: Equatable, Sendable {87    public enum Account: Equatable, Sendable {88        /// No account at this address (zero lamports).89        case missing90        /// Owned by the System program: an ordinary wallet.91        case system(lamports: UInt64)92        /// Owned by another program: a token account, a mint, a program, program state…93        case other(owner: SolanaPublicKey)94    }9596    /// Token facts, required for a token transfer.97    public struct Token: Equatable, Sendable {98        /// The mint as read on chain (`SolanaRPC.mintInfo`).99        public let mint: SolanaMintInfo100        /// Balance of the sender's associated token account in base units; nil when that account does not exist.101        public let senderBalance: UInt64?102        /// True when the sender's associated token account is frozen.103        public let senderFrozen: Bool104        /// True when the recipient's associated token account already exists.105        public let recipientAccountExists: Bool106        /// Rent-exempt minimum of a token account of this mint107        /// (`minimumBalanceForRentExemption(dataLength: mint.program.associatedAccountSize)`).108        public let tokenAccountRent: UInt64109110        public init(mint: SolanaMintInfo, senderBalance: UInt64?, senderFrozen: Bool = false, recipientAccountExists: Bool, tokenAccountRent: UInt64) {111            self.mint = mint112            self.senderBalance = senderBalance113            self.senderFrozen = senderFrozen114            self.recipientAccountExists = recipientAccountExists115            self.tokenAccountRent = tokenAccountRent116        }117    }118119    /// Lamports of the sender.120    public let senderLamports: UInt64121    /// The account at the recipient's address.122    public let recipient: Account123    /// Rent-exempt minimum of an account without data (`minimumBalanceForRentExemption(dataLength: 0)`). Always read on124    /// chain: it depends on the rent parameters of the cluster, which have changed over time and differ between clusters.125    public let systemAccountRent: UInt64126    public let blockhash: SolanaBlockhash127    public let token: Token?128129    public init(senderLamports: UInt64, recipient: Account, systemAccountRent: UInt64, blockhash: SolanaBlockhash, token: Token? = nil) {130        self.senderLamports = senderLamports131        self.recipient = recipient132        self.systemAccountRent = systemAccountRent133        self.blockhash = blockhash134        self.token = token135    }136}137138/// Why a transfer is not built. Each case is a fact the user can act on.139public enum SolanaSendRefusal: Error, Equatable, Sendable {140    case zeroAmount141    case senderIsRecipient142    /// The recipient is a program, a sysvar or the mint itself.143    case recipientIsReserved144    /// An account exists at the recipient's address and it is not a wallet (for instance a token account was pasted145    /// instead of the wallet address that owns it).146    case recipientIsNotAWallet(owner: SolanaPublicKey)147    /// Not enough lamports for the amount, the fee and, for a token, the recipient's token account.148    case insufficientLamports(required: UInt64, available: UInt64)149    /// The transfer would leave the sender with a balance that is neither zero nor rent-exempt; the cluster would150    /// reject it. `maximumSendable` is the largest amount that keeps the minimum (send-max empties the account instead).151    case senderBelowRentExemption(remaining: UInt64, minimum: UInt64, maximumSendable: UInt64)152    /// The recipient's account would hold less than the rent-exempt minimum (a new account must receive at least it).153    case recipientBelowRentExemption(minimum: UInt64)154    /// The snapshot has no token facts, or they are for another mint.155    case missingTokenData156    /// The sender has no associated token account for this mint.157    case noTokenAccount158    case tokenAccountFrozen159    case insufficientTokens(required: UInt64, available: UInt64)160    /// The mint cannot be transferred safely by this wallet (see `SolanaMintInfo.transferRefusal`).161    case unsupportedToken(reason: String)162    /// Memo that is empty, longer than `SolanaMemoProgram.maximumLength` bytes or contains control characters.163    case invalidMemo164    /// Compute-unit limit of 0 or above `SolanaComputeBudget.maximumUnitLimit`.165    case invalidComputeUnitLimit166    /// The priority fee exceeds `SolanaSendPlanner.maximumPriorityFee`, or overflows.167    case priorityFeeTooHigh(lamports: UInt64?)168    /// The transaction could not be assembled (should not happen for the fixed layouts built here).169    case buildFailed(String)170}171172/// A transfer ready for review: every number shown to the user comes from here, and `transaction` is exactly what173/// will be signed.174public struct SolanaSendPlan: Equatable, Sendable {175    public enum Warning: Equatable, Sendable {176        /// The recipient is not an Ed25519 public key (a program-derived address): no private key can exist for it.177        /// Funds sent there can be moved only by the program it belongs to.178        case recipientOffCurve179        /// No account exists yet at the recipient's address (SOL transfer): it will be created by this transfer.180        case recipientIsNew181        /// The recipient has no token account for this mint: the sender pays `accountCreationCost` to create it.182        case createsRecipientTokenAccount183        /// The sender's balance is left at zero: the account disappears from the chain until it is funded again.184        case emptiesSender185        /// The issuer of this Token-2022 token can move or burn tokens from any account.186        case tokenHasPermanentDelegate187    }188189    /// The unsigned transaction (fee payer and only signer: the sender).190    public let transaction: SolanaTransaction191    public let asset: SolanaSendRequest.Asset192    /// Amount transferred in base units (for send-max, the computed amount).193    public let amount: UInt64194    /// Decimals of the asset: 9 for SOL, the mint's on-chain decimals for a token.195    public let decimals: UInt8196    /// 5000 lamports per signature.197    public let signatureFee: UInt64198    /// ⌈compute-unit limit × price / 10^6⌉ lamports.199    public let priorityFee: UInt64200    /// Lamports locked in the recipient's new token account (0 when none is created). Not a fee: it stays in that201    /// account and belongs to the recipient.202    public let accountCreationCost: UInt64203    public let computeUnitLimit: UInt32204    public let computeUnitPrice: UInt64205    /// Lamports of the sender after the transaction.206    public let senderLamportsAfter: UInt64207    /// Token accounts used (nil for SOL).208    public let sourceTokenAccount: SolanaPublicKey?209    public let destinationTokenAccount: SolanaPublicKey?210    public let warnings: [Warning]211    /// The blockhash the transaction is tied to: after `lastValidBlockHeight` it can no longer be executed.212    public let blockhash: SolanaBlockhash213214    /// Network fee in lamports: signature fee + priority fee.215    public var fee: UInt64 { signatureFee + priorityFee }216217    /// Every lamport that leaves the sender: fee, account creation and, for SOL, the amount.218    public var totalLamports: UInt64 { fee + accountCreationCost + (asset == .sol ? amount : 0) }219220    /// The decoded instructions, exactly as a cold signer would decode the same bytes.221    public var review: SolanaTransactionReview { transaction.message.review() }222}223224/// Builds SOL and SPL-token transfers from a request and a snapshot of the chain. Pure: no network access, no key.225///226/// Transaction layout (legacy message, one signer): set compute-unit limit, set compute-unit price, [create the227/// recipient's associated token account if missing], transfer (`System.Transfer` or `TransferChecked`), [memo].228///229/// The caller then simulates `plan.transaction` (`SolanaRPC.simulate`), shows the plan, signs230/// (`SolanaTransaction.sign`) and sends. The mainnet per-transaction limits of `MainnetPolicy` are not applied here231/// (they have no Solana entry yet): the wallet service must apply them.232public enum SolanaSendPlanner {233    /// Largest priority fee this planner accepts: 0.01 SOL. Above it the request is refused as a probable mistake.234    public static let maximumPriorityFee: UInt64 = 10_000_000235236    /// Default compute-unit limits, with a wide margin over what these fixed transactions consume (a System transfer237    /// uses 150 units, each Compute Budget instruction 150, a `TransferChecked` a few thousand, the creation of an238    /// associated token account a few tens of thousands). An unused limit costs only its share of the priority fee.239    public static func defaultUnitLimit(asset: SolanaSendRequest.Asset, program: SolanaTokenProgram.Kind?, hasMemo: Bool) -> UInt32 {240        let base: UInt32241        switch asset {242        case .sol: base = 5_000243        case .token: base = program == .token2022 ? 120_000 : 80_000244        }245        return base + (hasMemo ? 30_000 : 0)246    }247248    public static func plan(_ request: SolanaSendRequest, snapshot: SolanaChainSnapshot) throws(SolanaSendRefusal) -> SolanaSendPlan {249        let sender = request.sender, recipient = request.recipient250        guard sender != recipient else { throw .senderIsRecipient }251        if SolanaProgram.reserved.contains(recipient) { throw .recipientIsReserved }252        if case .token(let mint) = request.asset, mint == recipient { throw .recipientIsReserved }253        if case .other(let owner) = snapshot.recipient { throw .recipientIsNotAWallet(owner: owner) }254        if let memo = request.memo, !SolanaMemoProgram.isAcceptable(memo) { throw .invalidMemo }255256        var warnings = [SolanaSendPlan.Warning]()257        if !recipient.isOnCurve { warnings.append(.recipientOffCurve) }258259        // fees260        var program: SolanaTokenProgram.Kind?261        if case .token(let mint) = request.asset {262            guard let token = snapshot.token, token.mint.address == mint else { throw .missingTokenData }263            program = token.mint.program264        }265        let unitLimit = request.computeUnitLimit ?? defaultUnitLimit(asset: request.asset, program: program, hasMemo: request.memo != nil)266        guard unitLimit > 0, unitLimit <= SolanaComputeBudget.maximumUnitLimit else { throw .invalidComputeUnitLimit }267        guard let priorityFee = SolanaComputeBudget.priorityFee(unitLimit: unitLimit, microLamportsPerUnit: request.computeUnitPrice) else {268            throw .priorityFeeTooHigh(lamports: nil)269        }270        guard priorityFee <= maximumPriorityFee else { throw .priorityFeeTooHigh(lamports: priorityFee) }271        let signatureFee = SolanaComputeBudget.lamportsPerSignature272        let fee = signatureFee + priorityFee273        let available = snapshot.senderLamports274        let rent = snapshot.systemAccountRent275276        var instructions = [SolanaComputeBudget.setComputeUnitLimit(unitLimit), SolanaComputeBudget.setComputeUnitPrice(microLamports: request.computeUnitPrice)]277        let amount: UInt64278        let decimals: UInt8279        var creationCost: UInt64 = 0280        var source: SolanaPublicKey?281        var destination: SolanaPublicKey?282        let lamportsOut: UInt64283284        switch request.asset {285        case .sol:286            decimals = UInt8(SolanaNetwork.decimals)287            switch request.amount {288            case .max:289                guard available > fee else { throw .insufficientLamports(required: fee + 1, available: available) }290                amount = available - fee291            case .exact(let value):292                guard value > 0 else { throw .zeroAmount }293                amount = value294            }295            let (out, overflow) = amount.addingReportingOverflow(fee)296            guard !overflow, out <= available else { throw .insufficientLamports(required: overflow ? .max : out, available: available) }297            lamportsOut = out298            // the recipient must end rent-exempt299            let recipientBefore: UInt64300            switch snapshot.recipient {301            case .system(let lamports): recipientBefore = lamports302            default: recipientBefore = 0303            }304            if recipientBefore == 0 { warnings.append(.recipientIsNew) }305            let (recipientAfter, recipientOverflow) = recipientBefore.addingReportingOverflow(amount)306            guard recipientOverflow || recipientAfter >= rent else { throw .recipientBelowRentExemption(minimum: rent - recipientBefore) }307            instructions.append(SolanaSystemProgram.transfer(from: sender, to: recipient, lamports: amount))308309        case .token(let mintAddress):310            guard let token = snapshot.token, token.mint.address == mintAddress else { throw .missingTokenData }311            if let reason = token.mint.transferRefusal { throw .unsupportedToken(reason: reason) }312            if token.mint.hasPermanentDelegate { warnings.append(.tokenHasPermanentDelegate) }313            guard let balance = token.senderBalance else { throw .noTokenAccount }314            guard !token.senderFrozen else { throw .tokenAccountFrozen }315            decimals = token.mint.decimals316            switch request.amount {317            case .max:318                guard balance > 0 else { throw .insufficientTokens(required: 1, available: 0) }319                amount = balance320            case .exact(let value):321                guard value > 0 else { throw .zeroAmount }322                guard value <= balance else { throw .insufficientTokens(required: value, available: balance) }323                amount = value324            }325            let kind = token.mint.program326            let sourceAccount: SolanaPublicKey, destinationAccount: SolanaPublicKey327            do {328                sourceAccount = try SolanaAddress.associatedTokenAccount(owner: sender, mint: mintAddress, tokenProgram: kind)329                destinationAccount = try SolanaAddress.associatedTokenAccount(owner: recipient, mint: mintAddress, tokenProgram: kind)330            } catch {331                throw .buildFailed("associated token account")332            }333            source = sourceAccount334            destination = destinationAccount335            if !token.recipientAccountExists {336                creationCost = token.tokenAccountRent337                warnings.append(.createsRecipientTokenAccount)338                instructions.append(SolanaAssociatedTokenProgram.createIdempotent(payer: sender, associatedAccount: destinationAccount, owner: recipient,339                                                                                  mint: mintAddress, tokenProgram: kind))340            }341            let (out, overflow) = fee.addingReportingOverflow(creationCost)342            guard !overflow, out <= available else { throw .insufficientLamports(required: overflow ? .max : out, available: available) }343            lamportsOut = out344            instructions.append(SolanaTokenProgram.transferChecked(source: sourceAccount, mint: mintAddress, destination: destinationAccount, owner: sender,345                                                                   amount: amount, decimals: decimals, program: kind))346        }347348        // the sender must end either empty or rent-exempt349        let remaining = available - lamportsOut350        if remaining == 0 {351            warnings.append(.emptiesSender)352        } else if remaining < rent {353            // QYV-SVC-020: `rent` and `creationCost` come from an endpoint and may be any 64-bit value: the sum saturates354            // instead of trapping (a reserve that does not fit in 64 bits leaves nothing to send).355            let (partial, overflow1) = fee.addingReportingOverflow(creationCost)356            let (sum, overflow2) = partial.addingReportingOverflow(rent)357            let reserve = overflow1 || overflow2 ? UInt64.max : sum358            let sendable: UInt64 = request.asset == .sol && available > reserve ? available - reserve : 0359            throw .senderBelowRentExemption(remaining: remaining, minimum: rent, maximumSendable: sendable)360        }361362        if let memo = request.memo { instructions.append(SolanaMemoProgram.memo(memo, signers: [sender])) }363364        let transaction: SolanaTransaction365        do {366            transaction = SolanaTransaction(message: try SolanaMessage(feePayer: sender, instructions: instructions, recentBlockhash: snapshot.blockhash.blockhash))367            _ = try transaction.serialize()368        } catch {369            throw .buildFailed("\(error)")370        }371        return SolanaSendPlan(transaction: transaction, asset: request.asset, amount: amount, decimals: decimals, signatureFee: signatureFee,372                              priorityFee: priorityFee, accountCreationCost: creationCost, computeUnitLimit: unitLimit,373                              computeUnitPrice: request.computeUnitPrice, senderLamportsAfter: remaining, sourceTokenAccount: source,374                              destinationTokenAccount: destination, warnings: warnings, blockhash: snapshot.blockhash)375    }376}377378extension SolanaRPC {379    /// Reads everything `SolanaSendPlanner.plan` needs for this request (five to nine requests, at `commitment`).380    /// Throws `NetworkError.invalidResponse("not a token mint")` when the asset is not a mint, and381    /// `SolanaSendRefusal.missingTokenData` when the mint does not exist.382    public func snapshot(for request: SolanaSendRequest, commitment: SolanaCommitment = .confirmed) async throws -> SolanaChainSnapshot {383        let senderLamports = try await balance(of: request.sender, commitment: commitment)384        let recipient: SolanaChainSnapshot.Account385        if let account = try await accountInfo(request.recipient, commitment: commitment) {386            recipient = account.owner == SolanaProgram.system && !account.executable ? .system(lamports: account.lamports) : .other(owner: account.owner)387        } else {388            recipient = .missing389        }390        let rent = try await minimumBalanceForRentExemption(dataLength: 0, commitment: commitment)391        var token: SolanaChainSnapshot.Token?392        if case .token(let mintAddress) = request.asset {393            guard let mint = try await mintInfo(mintAddress, commitment: commitment) else { throw SolanaSendRefusal.missingTokenData }394            let source = try SolanaAddress.associatedTokenAccount(owner: request.sender, mint: mintAddress, tokenProgram: mint.program)395            let destination = try SolanaAddress.associatedTokenAccount(owner: request.recipient, mint: mintAddress, tokenProgram: mint.program)396            let sourceAccount = try await tokenAccount(source, commitment: commitment)397            if let sourceAccount, sourceAccount.mint != mintAddress || sourceAccount.owner != request.sender {398                throw NetworkError.invalidResponse("associated token account does not match")399            }400            let destinationExists = try await accountInfo(destination, commitment: commitment) != nil401            let tokenRent = try await minimumBalanceForRentExemption(dataLength: mint.program.associatedAccountSize, commitment: commitment)402            token = SolanaChainSnapshot.Token(mint: mint, senderBalance: sourceAccount?.amount, senderFrozen: sourceAccount?.isFrozen ?? false,403                                              recipientAccountExists: destinationExists, tokenAccountRent: tokenRent)404        }405        let blockhash = try await latestBlockhash(commitment: commitment)406        return SolanaChainSnapshot(senderLamports: senderLamports, recipient: recipient, systemAccountRent: rent, blockhash: blockhash, token: token)407    }408}409
Files main
Menu

Theme