SPB Git

spb/os-vault Public

Self-custody, multi-chain crypto wallet for macOS. One recovery phrase, six chain families, zero API keys — nothing leaves your Mac.

Swift 96% Shell 3.4% Makefile 0.6%
2.5 KB · 84 lines swift
Raw Blame History
1import Foundation23public typealias AccountKeysFromLookups = LoadedAddresses45public struct LoadedAddresses {6    var readonly: [PublicKey]7    var writable: [PublicKey]89    public init(readonly: [PublicKey], writable: [PublicKey]) {10        self.readonly = readonly11        self.writable = writable12    }13}1415public struct MessageAccountKeys {16    public var staticAccountKeys: [PublicKey]17    public var accountKeysFromLookups: AccountKeysFromLookups?1819    public init(20        staticAccountKeys: [PublicKey],21        accountKeysFromLookups: AccountKeysFromLookups? = nil22    ) {23        self.staticAccountKeys = staticAccountKeys24        self.accountKeysFromLookups = accountKeysFromLookups25    }2627    public var keySegments: [[PublicKey]] {28        var keySegments = [staticAccountKeys]29        if let accountKeysFromLookups = accountKeysFromLookups {30            keySegments.append(accountKeysFromLookups.writable)31            keySegments.append(accountKeysFromLookups.readonly)32        }3334        return keySegments35    }3637    public subscript(index: Int) -> PublicKey? {38        var index = index3940        for keySegment in keySegments {41            if index < keySegment.count {42                return keySegment[index]43            } else {44                index -= keySegment.count45            }46        }47        return nil48    }4950    public var count: Int {51        keySegments.reduce([], +).count52    }5354    public func compileInstructions(55        instructions: [TransactionInstruction]56    ) throws -> [MessageCompiledInstruction] {57        if count > UInt8.max {58            throw VersionedMessageError.other("Account index overflow encountered during compilation")59        }60        var keyIndexMap: [String: Int] = [:]61        keySegments62            .reduce([], +)63            .enumerated()64            .forEach { index, key in65                keyIndexMap[key.base58EncodedString] = index66            }6768        func findKeyIndex(key: PublicKey) throws -> Int {69            if let keyIndex = keyIndexMap[key.base58EncodedString] {70                return keyIndex71            }72            throw VersionedMessageError.other("Encountered an unknown instruction account key during compilation")73        }7475        return try instructions.map { (instruction: TransactionInstruction) in76            try .init(77                programIdIndex: UInt8(findKeyIndex(key: instruction.programId)),78                accountKeyIndexes: instruction.keys.map { meta in try UInt8(findKeyIndex(key: meta.publicKey)) },79                data: instruction.data80            )81        }82    }83}84