SPB Git

Repository Public

SolanaInstructions.swift 21.8 KB 356 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSolana/SolanaInstructions.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 QyvoraMath4344/// System program: native SOL.45public enum SolanaSystemProgram {46    /// Transfer of `lamports` from a signer to any account (instruction 2: u32 index ‖ u64 amount, little endian).47    public static func transfer(from: SolanaPublicKey, to: SolanaPublicKey, lamports: UInt64) -> SolanaInstruction {48        SolanaInstruction(programID: SolanaProgram.system,49                          accounts: [SolanaAccountMeta(from, isSigner: true, isWritable: true), SolanaAccountMeta(to, isSigner: false, isWritable: true)],50                          data: Endian.le32(2) + Endian.le64(lamports))51    }52}5354/// Memo program (version 2): attaches a UTF-8 text to the transaction, visible in explorers.55public enum SolanaMemoProgram {56    /// Longest memo this module builds, in UTF-8 bytes (the program itself is limited only by the transaction size).57    public static let maximumLength = 2565859    /// What the send planner accepts as a memo: not empty, at most `maximumLength` UTF-8 bytes, and no control60    /// character (a line break or an escape sequence could disguise the text on a review screen or in an explorer).61    /// A memo is public and permanent: never put a secret in it.62    public static func isAcceptable(_ text: String) -> Bool {63        guard !text.isEmpty, text.utf8.count <= maximumLength else { return false }64        return text.unicodeScalars.allSatisfy(isDisplayable)65    }6667    /// False for the characters that can disguise a text on a review screen (QYV-SVC-024): control characters68    /// (line breaks, escape sequences), the line and paragraph separators, and every "format" character — the69    /// bidirectional overrides and isolates that reorder what is shown, zero-width characters, the byte order mark.70    public static func isDisplayable(_ scalar: Unicode.Scalar) -> Bool {71        switch scalar.properties.generalCategory {72        case .control, .format, .lineSeparator, .paragraphSeparator, .surrogate, .privateUse, .unassigned: return false73        default: return true74        }75    }7677    /// The memo of a transaction that was not built here, for display: every character `isDisplayable` refuses is78    /// written as `\u{…}`, so that a memo cannot break the line it is shown on nor reorder the text around it.79    public static func displayText(_ text: String) -> String {80        var out = ""81        for scalar in text.unicodeScalars {82            if isDisplayable(scalar) { out.unicodeScalars.append(scalar) } else { out += "\\u{" + String(scalar.value, radix: 16) + "}" }83        }84        return out85    }8687    /// `signers` are accounts that must sign the transaction to vouch for the memo (usually the sender), or none.88    public static func memo(_ text: String, signers: [SolanaPublicKey] = []) -> SolanaInstruction {89        SolanaInstruction(programID: SolanaProgram.memo, accounts: signers.map { SolanaAccountMeta($0, isSigner: true, isWritable: false) },90                          data: Bytes(text.utf8))91    }92}9394/// Compute Budget program: the compute-unit limit and price that set the priority fee.95public enum SolanaComputeBudget {96    /// Largest compute-unit limit a transaction may request.97    public static let maximumUnitLimit: UInt32 = 1_400_00098    /// Lamports per signature, charged whatever the priority fee.99    public static let lamportsPerSignature: UInt64 = 5_000100101    /// Instruction 2: the most compute units the transaction may consume.102    public static func setComputeUnitLimit(_ units: UInt32) -> SolanaInstruction {103        SolanaInstruction(programID: SolanaProgram.computeBudget, accounts: [], data: [2] + Endian.le32(units))104    }105106    /// Instruction 3: the price of one compute unit in micro-lamports (10^-6 lamport).107    public static func setComputeUnitPrice(microLamports: UInt64) -> SolanaInstruction {108        SolanaInstruction(programID: SolanaProgram.computeBudget, accounts: [], data: [3] + Endian.le64(microLamports))109    }110111    /// Priority fee in lamports: ⌈limit × price / 10^6⌉. nil when the product does not fit in 64 bits.112    public static func priorityFee(unitLimit: UInt32, microLamportsPerUnit: UInt64) -> UInt64? {113        let (product, overflow) = UInt64(unitLimit).multipliedReportingOverflow(by: microLamportsPerUnit)114        guard !overflow else { return nil }115        let (rounded, overflow2) = product.addingReportingOverflow(999_999)116        guard !overflow2 else { return nil }117        return rounded / 1_000_000118    }119}120121/// SPL Token and Token-2022: the two programs that own mints and token accounts.122public enum SolanaTokenProgram {123    public enum Kind: String, Codable, Sendable, CaseIterable {124        /// The original SPL Token program.125        case token126        /// Token-2022 ("Token Extensions"): same base instructions, plus optional extensions on mints and accounts.127        case token2022128129        public var programID: SolanaPublicKey { self == .token ? SolanaProgram.token : SolanaProgram.token2022 }130131        public init?(programID: SolanaPublicKey) {132            if programID == SolanaProgram.token { self = .token } else if programID == SolanaProgram.token2022 { self = .token2022 } else { return nil }133        }134135        /// Size in bytes of an associated token account: 165 for Token; 170 for Token-2022 (165 + account type +136        /// the empty `ImmutableOwner` extension every associated account carries) when the mint requires no further137        /// account extension — which is the case of every mint `SolanaMintInfo.transferRefusal` accepts.138        public var associatedAccountSize: Int { self == .token ? 165 : 170 }139    }140141    /// `TransferChecked` (instruction 12: u8 ‖ u64 amount ‖ u8 decimals): moves `amount` base units from `source`142    /// to `destination`, both token accounts of `mint`; the program refuses when the mint or its decimals differ from143    /// what is signed here. `owner` is the single-signature authority of `source`.144    public static func transferChecked(source: SolanaPublicKey, mint: SolanaPublicKey, destination: SolanaPublicKey, owner: SolanaPublicKey,145                                       amount: UInt64, decimals: UInt8, program: Kind = .token) -> SolanaInstruction {146        SolanaInstruction(programID: program.programID, accounts: [147            SolanaAccountMeta(source, isSigner: false, isWritable: true), SolanaAccountMeta(mint, isSigner: false, isWritable: false),148            SolanaAccountMeta(destination, isSigner: false, isWritable: true), SolanaAccountMeta(owner, isSigner: true, isWritable: false),149        ], data: [12] + Endian.le64(amount) + [decimals])150    }151}152153/// Associated Token Account program.154public enum SolanaAssociatedTokenProgram {155    /// `CreateIdempotent` (instruction 1): creates the associated token account of `owner` for `mint`, paid by156    /// `payer`; does nothing when the account already exists (so a race with another sender cannot fail the transfer).157    public static func createIdempotent(payer: SolanaPublicKey, associatedAccount: SolanaPublicKey, owner: SolanaPublicKey, mint: SolanaPublicKey,158                                        tokenProgram: SolanaTokenProgram.Kind = .token) -> SolanaInstruction {159        SolanaInstruction(programID: SolanaProgram.associatedToken, accounts: [160            SolanaAccountMeta(payer, isSigner: true, isWritable: true), SolanaAccountMeta(associatedAccount, isSigner: false, isWritable: true),161            SolanaAccountMeta(owner, isSigner: false, isWritable: false), SolanaAccountMeta(mint, isSigner: false, isWritable: false),162            SolanaAccountMeta(SolanaProgram.system, isSigner: false, isWritable: false),163            SolanaAccountMeta(tokenProgram.programID, isSigner: false, isWritable: false),164        ], data: [1])165    }166}167168/// What an instruction does, for the review screen. Only the exact layouts listed here are recognised; anything169/// else — another program, another instruction of a known program, extra accounts (multisignature, transfer hook),170/// unexpected data length — is `unknown`, and signing it is blind signing.171public enum SolanaDecodedInstruction: Equatable, Sendable {172    case systemTransfer(from: SolanaPublicKey, to: SolanaPublicKey, lamports: UInt64)173    case systemCreateAccount(payer: SolanaPublicKey, newAccount: SolanaPublicKey, lamports: UInt64, space: UInt64, owner: SolanaPublicKey)174    case computeUnitLimit(units: UInt32)175    case computeUnitPrice(microLamports: UInt64)176    case computeHeapFrame(bytes: UInt32)177    case computeLoadedAccountsDataSizeLimit(bytes: UInt32)178    case tokenTransfer(program: SolanaTokenProgram.Kind, source: SolanaPublicKey, destination: SolanaPublicKey, authority: SolanaPublicKey, amount: UInt64)179    case tokenTransferChecked(program: SolanaTokenProgram.Kind, source: SolanaPublicKey, mint: SolanaPublicKey, destination: SolanaPublicKey,180                              authority: SolanaPublicKey, amount: UInt64, decimals: UInt8)181    /// Lets `delegate` spend up to `amount` from `source`: the token equivalent of an ERC-20 approval.182    case tokenApprove(program: SolanaTokenProgram.Kind, source: SolanaPublicKey, delegate: SolanaPublicKey, owner: SolanaPublicKey, amount: UInt64)183    case tokenApproveChecked(program: SolanaTokenProgram.Kind, source: SolanaPublicKey, mint: SolanaPublicKey, delegate: SolanaPublicKey,184                             owner: SolanaPublicKey, amount: UInt64, decimals: UInt8)185    case tokenRevoke(program: SolanaTokenProgram.Kind, source: SolanaPublicKey, owner: SolanaPublicKey)186    /// Closes a token account and sends its lamports to `destination`.187    case tokenCloseAccount(program: SolanaTokenProgram.Kind, account: SolanaPublicKey, destination: SolanaPublicKey, owner: SolanaPublicKey)188    case tokenSyncNative(program: SolanaTokenProgram.Kind, account: SolanaPublicKey)189    case createAssociatedTokenAccount(payer: SolanaPublicKey, associatedAccount: SolanaPublicKey, owner: SolanaPublicKey, mint: SolanaPublicKey,190                                      tokenProgram: SolanaPublicKey, idempotent: Bool)191    case memo(String)192    /// Not recognised. `programID` is nil only when the program index is invalid; an account is nil when it comes193    /// from an address lookup table (version-0 message) and is therefore not in the message.194    case unknown(programID: SolanaPublicKey?, accounts: [SolanaPublicKey?], data: Bytes)195196    /// True for `unknown`.197    public var isUnknown: Bool {198        if case .unknown = self { return true }199        return false200    }201202    /// Decodes one instruction with resolved accounts.203    public static func decode(_ instruction: SolanaInstruction) -> SolanaDecodedInstruction {204        let keys = instruction.accounts.map(\.publicKey)205        let data = instruction.data206        let unknown = SolanaDecodedInstruction.unknown(programID: instruction.programID, accounts: keys, data: data)207        func u32(_ at: Int) -> UInt32 { data.withUnsafeBufferPointer { Endian.loadLE32($0.baseAddress! + at) } }208        func u64(_ at: Int) -> UInt64 { data.withUnsafeBufferPointer { Endian.loadLE64($0.baseAddress! + at) } }209210        switch instruction.programID {211        case SolanaProgram.system:212            guard data.count >= 4 else { return unknown }213            switch u32(0) {214            case 2 where data.count == 12 && keys.count == 2:215                return .systemTransfer(from: keys[0], to: keys[1], lamports: u64(4))216            case 0 where data.count == 52 && keys.count == 2:217                return .systemCreateAccount(payer: keys[0], newAccount: keys[1], lamports: u64(4), space: u64(12),218                                            owner: SolanaPublicKey(bytes: Bytes(data[20..<52]))!)219            default: return unknown220            }221222        case SolanaProgram.computeBudget:223            guard let tag = data.first, keys.isEmpty else { return unknown }224            switch tag {225            case 1 where data.count == 5: return .computeHeapFrame(bytes: u32(1))226            case 2 where data.count == 5: return .computeUnitLimit(units: u32(1))227            case 3 where data.count == 9: return .computeUnitPrice(microLamports: u64(1))228            case 4 where data.count == 5: return .computeLoadedAccountsDataSizeLimit(bytes: u32(1))229            default: return unknown230            }231232        case SolanaProgram.token, SolanaProgram.token2022:233            guard let tag = data.first, let program = SolanaTokenProgram.Kind(programID: instruction.programID) else { return unknown }234            switch tag {235            case 3 where data.count == 9 && keys.count == 3:236                return .tokenTransfer(program: program, source: keys[0], destination: keys[1], authority: keys[2], amount: u64(1))237            case 4 where data.count == 9 && keys.count == 3:238                return .tokenApprove(program: program, source: keys[0], delegate: keys[1], owner: keys[2], amount: u64(1))239            case 5 where data.count == 1 && keys.count == 2:240                return .tokenRevoke(program: program, source: keys[0], owner: keys[1])241            case 9 where data.count == 1 && keys.count == 3:242                return .tokenCloseAccount(program: program, account: keys[0], destination: keys[1], owner: keys[2])243            case 12 where data.count == 10 && keys.count == 4:244                return .tokenTransferChecked(program: program, source: keys[0], mint: keys[1], destination: keys[2], authority: keys[3],245                                             amount: u64(1), decimals: data[9])246            case 13 where data.count == 10 && keys.count == 4:247                return .tokenApproveChecked(program: program, source: keys[0], mint: keys[1], delegate: keys[2], owner: keys[3],248                                            amount: u64(1), decimals: data[9])249            case 17 where data.count == 1 && keys.count == 1:250                return .tokenSyncNative(program: program, account: keys[0])251            default: return unknown252            }253254        case SolanaProgram.associatedToken:255            // Create has no data (or a single 0), CreateIdempotent a single 1256            guard keys.count == 6, keys[4] == SolanaProgram.system, data.isEmpty || (data.count == 1 && data[0] <= 1) else { return unknown }257            return .createAssociatedTokenAccount(payer: keys[0], associatedAccount: keys[1], owner: keys[2], mint: keys[3], tokenProgram: keys[5],258                                                 idempotent: data.first == 1)259260        case SolanaProgram.memo, SolanaProgram.memoV1:261            guard let text = String(validatingUTF8Bytes: data) else { return unknown }262            return .memo(text)263264        default:265            return unknown266        }267    }268269    /// One English sentence for the review screen. Amounts are in base units (lamports, token base units): the caller270    /// formats them with the decimals it has verified on chain.271    public var summary: String {272        switch self {273        case .systemTransfer(let from, let to, let lamports):274            return "Transfer \(lamports) lamports from \(from) to \(to)"275        case .systemCreateAccount(let payer, let account, let lamports, let space, let owner):276            return "Create account \(account) (\(space) bytes, \(lamports) lamports) owned by program \(owner), paid by \(payer)"277        case .computeUnitLimit(let units): return "Set the compute unit limit to \(units)"278        case .computeUnitPrice(let price): return "Set the compute unit price to \(price) micro-lamports"279        case .computeHeapFrame(let bytes): return "Request a heap of \(bytes) bytes"280        case .computeLoadedAccountsDataSizeLimit(let bytes): return "Limit the loaded account data to \(bytes) bytes"281        case .tokenTransfer(_, let source, let destination, let authority, let amount):282            return "Transfer \(amount) token base units from token account \(source) to token account \(destination), authorised by \(authority)"283        case .tokenTransferChecked(_, let source, let mint, let destination, let authority, let amount, let decimals):284            return "Transfer \(amount) base units (\(decimals) decimals) of token \(mint) from token account \(source) to token account \(destination), authorised by \(authority)"285        case .tokenApprove(_, let source, let delegate, let owner, let amount):286            return "Allow \(delegate) to spend up to \(amount) token base units from token account \(source), authorised by \(owner)"287        case .tokenApproveChecked(_, let source, let mint, let delegate, let owner, let amount, let decimals):288            return "Allow \(delegate) to spend up to \(amount) base units (\(decimals) decimals) of token \(mint) from token account \(source), authorised by \(owner)"289        case .tokenRevoke(_, let source, let owner): return "Revoke the spending allowance on token account \(source), authorised by \(owner)"290        case .tokenCloseAccount(_, let account, let destination, let owner):291            return "Close token account \(account) and send its lamports to \(destination), authorised by \(owner)"292        case .tokenSyncNative(_, let account): return "Synchronise the wrapped SOL balance of token account \(account)"293        case .createAssociatedTokenAccount(let payer, let account, let owner, let mint, _, let idempotent):294            return "Create\(idempotent ? " (if missing)" : "") the token account \(account) of \(owner) for token \(mint), paid by \(payer)"295        case .memo(let text): return "Memo: \(SolanaMemoProgram.displayText(text))"296        case .unknown(let program, let accounts, let data):297            return "Unknown instruction of program \(program?.base58 ?? "?") (\(accounts.count) accounts, \(data.count) bytes of data)"298        }299    }300}301302extension String {303    /// The string when the bytes are valid UTF-8, nil otherwise (no replacement character).304    init?(validatingUTF8Bytes bytes: Bytes) {305        guard let s = String(validating: bytes, as: UTF8.self) else { return nil }306        self = s307    }308}309310/// What a message would do, for the review screen and for cold (offline) signing.311public struct SolanaTransactionReview: Equatable, Sendable {312    public let version: SolanaMessage.Version313    public let feePayer: SolanaPublicKey314    /// Every account that must sign, the fee payer first.315    public let signers: [SolanaPublicKey]316    public let recentBlockhash: String317    public let instructions: [SolanaDecodedInstruction]318    /// True when the message loads accounts from address lookup tables: their addresses are not in the message.319    public let usesAddressLookupTables: Bool320321    /// True when at least one instruction is not recognised or when accounts are hidden behind a lookup table:322    /// the user cannot be shown what the transaction does, and the caller must warn about blind signing or refuse.323    public var requiresBlindSigning: Bool { usesAddressLookupTables || instructions.contains(where: \.isUnknown) }324325    /// Base fee: 5000 lamports per required signature (the priority fee is not included).326    public var signatureFee: UInt64 { UInt64(signers.count) * SolanaComputeBudget.lamportsPerSignature }327328    /// Priority fee in lamports when the message sets both a compute-unit limit and a price; 0 when it sets no329    /// price; nil when it sets a price without a limit (the fee then depends on the default limit of the runtime).330    public var priorityFee: UInt64? {331        var limit: UInt32?332        var price: UInt64?333        for instruction in instructions {334            if case .computeUnitLimit(let units) = instruction { limit = units }335            if case .computeUnitPrice(let p) = instruction { price = p }336        }337        guard let price, price > 0 else { return 0 }338        guard let limit else { return nil }339        return SolanaComputeBudget.priorityFee(unitLimit: limit, microLamportsPerUnit: price)340    }341}342343extension SolanaMessage {344    /// Decodes every instruction of the message.345    public func review() -> SolanaTransactionReview {346        let decoded = instructions.indices.map { position -> SolanaDecodedInstruction in347            if let instruction = instruction(at: position) { return SolanaDecodedInstruction.decode(instruction) }348            let compiled = instructions[position]349            func key(_ index: UInt8) -> SolanaPublicKey? { Int(index) < accountKeys.count ? accountKeys[Int(index)] : nil }350            return .unknown(programID: key(compiled.programIDIndex), accounts: compiled.accountIndices.map(key), data: compiled.data)351        }352        return SolanaTransactionReview(version: version, feePayer: feePayer, signers: signers, recentBlockhash: recentBlockhashBase58,353                                       instructions: decoded, usesAddressLookupTables: !addressTableLookups.isEmpty)354    }355}356
Files main
Menu

Theme