SPB Git

Repository Public

SolanaAddress.swift 10.4 KB 201 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSolana/SolanaAddress.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 QyvoraEd2551943import QyvoraMath44import QyvoraSymmetric4546/// A Solana address: 32 bytes, shown in base58 (Bitcoin alphabet, no checksum).47///48/// An address is either an Ed25519 public key (a wallet: `isOnCurve`) or a program-derived address, which is by49/// construction not a curve point and has no private key.50public struct SolanaPublicKey: Hashable, Sendable, Comparable, CustomStringConvertible {51    public let bytes: Bytes5253    /// Exactly 32 bytes; nil otherwise.54    public init?(bytes: Bytes) {55        guard bytes.count == 32 else { return nil }56        self.bytes = bytes57    }5859    /// Strict base58: 32 to 44 characters of the alphabet, decoding to exactly 32 bytes. No white space is trimmed.60    /// There is no checksum in a Solana address: a mistyped character usually gives another valid address, so the61    /// application must let the user compare what was pasted.62    public init?(base58 text: String) {63        guard (32...44).contains(text.utf8.count), let decoded = Base58.bitcoin.decode(text), decoded.count == 32 else { return nil }64        bytes = decoded65    }6667    /// For the constants of this module only.68    init(_ literal: String) {69        self.init(base58: literal)!70    }7172    public var base58: String { Base58.bitcoin.encode(bytes) }73    public var description: String { base58 }7475    /// True when the address is a point of the Ed25519 curve (Solana's `is_on_curve`): a key pair may exist for it.76    /// False for program-derived addresses (associated token accounts, program state…).77    public var isOnCurve: Bool { Ed25519.isOnCurve(bytes) }7879    /// Byte-wise order, the one the Solana SDK uses to order the accounts of a message.80    public static func < (a: SolanaPublicKey, b: SolanaPublicKey) -> Bool {81        a.bytes.lexicographicallyPrecedes(b.bytes)82    }83}8485/// Addresses of the programs this module builds or decodes instructions for.86public enum SolanaProgram {87    public static let system = SolanaPublicKey("11111111111111111111111111111111")88    public static let token = SolanaPublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")89    public static let token2022 = SolanaPublicKey("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb")90    public static let associatedToken = SolanaPublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")91    public static let computeBudget = SolanaPublicKey("ComputeBudget111111111111111111111111111111")92    public static let memo = SolanaPublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")93    /// The first version of the memo program (still deployed; decoded for display, never used to build).94    public static let memoV1 = SolanaPublicKey("Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo")95    /// Mint of wrapped SOL.96    public static let nativeMint = SolanaPublicKey("So11111111111111111111111111111111111111112")9798    /// Addresses that are never a valid recipient of a transfer: programs, the wrapped-SOL mint and the sysvars.99    public static let reserved: Set<SolanaPublicKey> = [100        system, token, token2022, associatedToken, computeBudget, memo, memoV1, nativeMint,101        SolanaPublicKey("SysvarRent111111111111111111111111111111111"),102        SolanaPublicKey("SysvarC1ock11111111111111111111111111111111"),103        SolanaPublicKey("SysvarRecentB1ockHashes11111111111111111111"),104        SolanaPublicKey("Sysvar1nstructions1111111111111111111111111"),105        SolanaPublicKey("Stake11111111111111111111111111111111111111"),106        SolanaPublicKey("Vote111111111111111111111111111111111111111"),107        SolanaPublicKey("BPFLoaderUpgradeab1e11111111111111111111111"),108        SolanaPublicKey("AddressLookupTab1e1111111111111111111111111"),109    ]110}111112/// Address validation and program-derived addresses.113public enum SolanaAddress {114    /// True when the text is a strict base58 address of 32 bytes.115    public static func isValid(_ text: String) -> Bool { SolanaPublicKey(base58: text) != nil }116117    public static let maximumSeeds = 16118    public static let maximumSeedLength = 32119120    /// SHA-256(seeds ‖ program id ‖ "ProgramDerivedAddress"), accepted only when it is **not** a curve point121    /// (Solana's `create_program_address`). nil when it is on the curve or when the seeds exceed the limits.122    public static func createProgramAddress(seeds: [Bytes], programID: SolanaPublicKey) -> SolanaPublicKey? {123        guard seeds.count <= maximumSeeds, seeds.allSatisfy({ $0.count <= maximumSeedLength }) else { return nil }124        var h = SHA256()125        for seed in seeds { h.update(seed) }126        h.update(programID.bytes)127        h.update(Bytes("ProgramDerivedAddress".utf8))128        let digest = h.finalize()129        guard !Ed25519.isOnCurve(digest) else { return nil }130        return SolanaPublicKey(bytes: digest)131    }132133    /// Solana's `find_program_address`: the address for the highest bump seed (255 downwards) that is off the curve.134    public static func findProgramAddress(seeds: [Bytes], programID: SolanaPublicKey) throws -> (address: SolanaPublicKey, bump: UInt8) {135        guard seeds.count < maximumSeeds, seeds.allSatisfy({ $0.count <= maximumSeedLength }) else { throw SolanaError.invalidProgramAddressSeeds }136        for bump in stride(from: 255, through: 0, by: -1) {137            if let address = createProgramAddress(seeds: seeds + [[UInt8(bump)]], programID: programID) {138                return (address, UInt8(bump))139            }140        }141        throw SolanaError.invalidProgramAddressSeeds142    }143144    /// The associated token account of `owner` for `mint`: the program-derived address of the Associated Token145    /// Account program for the seeds [owner, token program, mint]. The token program is part of the seeds: the same146    /// owner and mint give different accounts under Token and Token-2022, so it must be the program that owns the mint.147    public static func associatedTokenAccount(owner: SolanaPublicKey, mint: SolanaPublicKey,148                                              tokenProgram: SolanaTokenProgram.Kind = .token) throws -> SolanaPublicKey {149        try findProgramAddress(seeds: [owner.bytes, tokenProgram.programID.bytes, mint.bytes], programID: SolanaProgram.associatedToken).address150    }151}152153/// Key derivation for Solana accounts (SLIP-0010 Ed25519 from a BIP-39 seed).154public enum SolanaKeys {155    /// Where the account key sits under the BIP-39 seed.156    public enum DerivationStyle: String, Codable, Sendable, CaseIterable {157        /// m/44'/501'/account'/0' — the default of Phantom, Solflare, Backpack and most wallets. QYVORA's default.158        case bip44Change159        /// m/44'/501'/account' — Ledger Live style, also offered by Phantom and Solflare on import ("bip44").160        case bip44161        /// m/44'/501' — a single account; the oldest derivation of the Solana tools (account index ignored).162        case bip44Root163    }164165    /// The derivation path of an account (every step is hardened: Ed25519 has no public derivation).166    /// Not covered: the `solana-keygen` default, which uses the first 32 bytes of the BIP-39 seed directly with no path.167    public static func derivationPath(account: UInt32 = 0, style: DerivationStyle = .bip44Change) -> DerivationPath {168        switch style {169        case .bip44Change: return DerivationPath([.hardened(44), .hardened(SolanaNetwork.coinType), .hardened(account), .hardened(0)])170        case .bip44: return DerivationPath([.hardened(44), .hardened(SolanaNetwork.coinType), .hardened(account)])171        case .bip44Root: return DerivationPath([.hardened(44), .hardened(SolanaNetwork.coinType)])172        }173    }174175    /// The 32-byte Ed25519 seed (private key) of an account, from a BIP-39 seed (64 bytes, see `BIP39.seed`).176    /// The caller erases the result with `SecureMemory.zero` when done.177    public static func privateSeed(bip39Seed: Bytes, account: UInt32 = 0, style: DerivationStyle = .bip44Change) throws -> Bytes {178        guard account < ChildIndex.hardenedBit else { throw SolanaError.invalidSeed }179        do {180            var node = try Ed25519.SLIP10.derive(seed: bip39Seed, path: derivationPath(account: account, style: style).indices.map(\.index))181            defer { node.wipe() }182            return node.privateKey183        } catch {184            throw SolanaError.invalidSeed185        }186    }187188    /// The address of a 32-byte Ed25519 seed.189    public static func publicKey(privateSeed: Bytes) throws -> SolanaPublicKey {190        guard let bytes = try? Ed25519.publicKey(seed: privateSeed), let key = SolanaPublicKey(bytes: bytes) else { throw SolanaError.invalidSeed }191        return key192    }193194    /// The address of an account, from a BIP-39 seed.195    public static func address(bip39Seed: Bytes, account: UInt32 = 0, style: DerivationStyle = .bip44Change) throws -> SolanaPublicKey {196        var seed = try privateSeed(bip39Seed: bip39Seed, account: account, style: style)197        defer { SecureMemory.zero(&seed) }198        return try publicKey(privateSeed: seed)199    }200}201
Files main
Menu

Theme