From 7346e3ddd9ae8753734ba21380a5f80344dcad22 Mon Sep 17 00:00:00 2001 From: Jerry Liu <33166884+Ethella@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:50:55 -0700 Subject: [PATCH 1/5] Add Solana and Bitcoin extensions Ports @magic-ext/solana and @magic-ext/bitcoin from magic-js so native iOS apps can get addresses and sign on Solana and Bitcoin. - Magic(apiKey:extensions:) sends extension config to the relayer as `ext`, in the same shape as magic-js. - magic.solana: signTransaction, partialSignTransaction, signMessage, getPublicAddress, revealPrivateKey. - magic.bitcoin: signTransaction, getPublicAddress, revealPrivateKey. - Binary data uses the mgbox typed-array wire format, so the relayer receives a real Uint8Array, as it does from react-native-bare. Co-Authored-By: Claude Opus 5.5 --- Sources/MagicSDK/Core/Magic.swift | 19 ++- .../Core/Relayer/Types/TypedArray.swift | 56 ++++++ .../MagicSDK/Core/Relayer/URLBuilder.swift | 12 +- .../Bitcoin/BitcoinConfiguration.swift | 86 ++++++++++ .../Modules/Bitcoin/BitcoinExtension.swift | 60 +++++++ .../Extension/ExtensionConfiguration.swift | 41 +++++ .../Multichain/MultichainExtension.swift | 66 +++++++ .../Modules/Solana/SolanaConfiguration.swift | 146 ++++++++++++++++ .../Modules/Solana/SolanaExtension.swift | 124 ++++++++++++++ .../MultichainExtensionTests.swift | 161 ++++++++++++++++++ 10 files changed, 761 insertions(+), 10 deletions(-) create mode 100644 Sources/MagicSDK/Core/Relayer/Types/TypedArray.swift create mode 100644 Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift create mode 100644 Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift create mode 100644 Sources/MagicSDK/Modules/Extension/ExtensionConfiguration.swift create mode 100644 Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift create mode 100644 Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift create mode 100644 Sources/MagicSDK/Modules/Solana/SolanaExtension.swift create mode 100644 Tests/MagicSDKTests/MultichainExtensionTests.swift diff --git a/Sources/MagicSDK/Core/Magic.swift b/Sources/MagicSDK/Core/Magic.swift index 08e21fd..e9580df 100644 --- a/Sources/MagicSDK/Core/Magic.swift +++ b/Sources/MagicSDK/Core/Magic.swift @@ -22,6 +22,9 @@ public class Magic: NSObject { // MARK: - Property public var rpcProvider: RpcProvider + /// Extensions this instance was created with + let extensionConfigurations: [ExtensionConfiguration] + /// Shared instance of `Magic` public static var shared: Magic! @@ -33,20 +36,22 @@ public class Magic: NSObject { /// - apiKey: Your client ID. From https://dashboard.Magic.com /// - ethNetwork: Etherum Network setting (ie. mainnet or goerli) /// - customNode: A custom RPC node - public convenience init(apiKey: String, ethNetwork: EthNetwork, locale: String = Locale.current.identifier) { - self.init(urlBuilder: URLBuilder(apiKey: apiKey, network: ethNetwork, locale: locale)) + /// - extensions: Chain extensions to enable, e.g. `SolanaConfiguration` or `BitcoinConfiguration` + public convenience init(apiKey: String, ethNetwork: EthNetwork, extensions: [ExtensionConfiguration] = [], locale: String = Locale.current.identifier) { + self.init(urlBuilder: URLBuilder(apiKey: apiKey, network: ethNetwork, extensions: extensions, locale: locale), extensions: extensions) } - public convenience init(apiKey: String, customNode: CustomNodeConfiguration, locale: String = Locale.current.identifier) { - self.init(urlBuilder: URLBuilder(apiKey: apiKey, customNode: customNode, locale: locale)) + public convenience init(apiKey: String, customNode: CustomNodeConfiguration, extensions: [ExtensionConfiguration] = [], locale: String = Locale.current.identifier) { + self.init(urlBuilder: URLBuilder(apiKey: apiKey, customNode: customNode, extensions: extensions, locale: locale), extensions: extensions) } - public convenience init(apiKey: String, locale: String = Locale.current.identifier) { - self.init(urlBuilder: URLBuilder(apiKey: apiKey, network: EthNetwork.mainnet, locale: locale)) + public convenience init(apiKey: String, extensions: [ExtensionConfiguration] = [], locale: String = Locale.current.identifier) { + self.init(urlBuilder: URLBuilder(apiKey: apiKey, network: EthNetwork.mainnet, extensions: extensions, locale: locale), extensions: extensions) } /// Core constructor - private init(urlBuilder: URLBuilder) { + private init(urlBuilder: URLBuilder, extensions: [ExtensionConfiguration]) { + self.extensionConfigurations = extensions self.rpcProvider = RpcProvider(urlBuilder: urlBuilder) self.user = UserModule(rpcProvider: self.rpcProvider) diff --git a/Sources/MagicSDK/Core/Relayer/Types/TypedArray.swift b/Sources/MagicSDK/Core/Relayer/Types/TypedArray.swift new file mode 100644 index 0000000..467b586 --- /dev/null +++ b/Sources/MagicSDK/Core/Relayer/Types/TypedArray.swift @@ -0,0 +1,56 @@ +// +// TypedArray.swift +// MagicSDK +// + +import Foundation + +/// Binary data in the typed-array wire format that mgbox uses in both directions. +/// +/// JSON has no binary type, so mgbox and `@magic-sdk/react-native-bare` send a +/// `Uint8Array` as +/// `{"constructor":"Uint8Array","data":"99,53,247","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}`. +/// mgbox turns this back into a real `Uint8Array` before the relayer sees it. It +/// also encodes typed arrays in responses (e.g. Solana signatures) the same way. +public struct TypedArray: Codable, Equatable { + + static let flag = "MAGIC_PAYLOAD_FLAG_TYPED_ARRAY" + + public let data: Data + + public init(_ data: Data) { + self.data = data + } + + enum CodingKeys: String, CodingKey { + case constructor, data, flag + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode("Uint8Array", forKey: .constructor) + try container.encode(data.map { $0.description }.joined(separator: ","), forKey: .data) + try container.encode(TypedArray.flag, forKey: .flag) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard try container.decode(String.self, forKey: .flag) == TypedArray.flag else { + throw DecodingError.dataCorruptedError(forKey: .flag, in: container, debugDescription: "Not a typed array") + } + // `Buffer` and `Uint8Array` both arrive here. Their bytes are joined the same way. + let joined = try container.decode(String.self, forKey: .data) + if joined.isEmpty { + self.data = Data() + return + } + var bytes: [UInt8] = [] + for part in joined.split(separator: ",", omittingEmptySubsequences: false) { + guard let byte = UInt8(part) else { + throw DecodingError.dataCorruptedError(forKey: .data, in: container, debugDescription: "Invalid byte: \(part)") + } + bytes.append(byte) + } + self.data = Data(bytes) + } +} diff --git a/Sources/MagicSDK/Core/Relayer/URLBuilder.swift b/Sources/MagicSDK/Core/Relayer/URLBuilder.swift index e8e8ffa..5397998 100644 --- a/Sources/MagicSDK/Core/Relayer/URLBuilder.swift +++ b/Sources/MagicSDK/Core/Relayer/URLBuilder.swift @@ -19,13 +19,14 @@ public struct URLBuilder { static let host = "https://box.magic.link" public let apiKey: String - init(apiKey: String, customNode: CustomNodeConfiguration? = nil, network: EthNetwork? = nil, locale: String) { + init(apiKey: String, customNode: CustomNodeConfiguration? = nil, network: EthNetwork? = nil, extensions: [ExtensionConfiguration] = [], locale: String) { let data = try! JSONEncoder().encode( UrlParamsEncodable( apiKey: apiKey, ethNetwork: network, customNode: customNode, + extensions: ExtensionConfigurations(configurations: extensions), locale: locale ) ) @@ -52,18 +53,20 @@ public struct URLBuilder { let locale: String let customNode: CustomNodeConfiguration? let ethNetwork: EthNetwork? + let extensions: ExtensionConfigurations - init(apiKey: String, ethNetwork: EthNetwork?, customNode: CustomNodeConfiguration?, locale: String) { + init(apiKey: String, ethNetwork: EthNetwork?, customNode: CustomNodeConfiguration?, extensions: ExtensionConfigurations, locale: String) { self.apiKey = apiKey self.locale = locale self.customNode = customNode self.ethNetwork = ethNetwork + self.extensions = extensions } enum CodingKeys: String, CodingKey { case apiKey = "API_KEY" case ethNetwork = "ETH_NETWORK" - case bundleId, host, sdk, locale + case bundleId, host, sdk, locale, ext } func encode(to encoder: Encoder) throws { @@ -83,6 +86,9 @@ public struct URLBuilder { if let network = ethNetwork { try container.encode(network.rawValue, forKey: .ethNetwork) } + if !extensions.isEmpty { + try container.encode(extensions, forKey: .ext) + } } } } diff --git a/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift b/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift new file mode 100644 index 0000000..33105a4 --- /dev/null +++ b/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift @@ -0,0 +1,86 @@ +// +// BitcoinConfiguration.swift +// MagicSDK +// + +import Foundation + +internal enum BitcoinMethod: String { + case btc_signTransaction +} + +/// Enables the Bitcoin extension. Mirrors `BitcoinConfig` in `@magic-ext/bitcoin`. +public struct BitcoinConfiguration: ExtensionConfiguration { + public let name = "bitcoin" + public let rpcUrl: String + public let network: String + + public init(rpcUrl: String, network: String) { + self.rpcUrl = rpcUrl + self.network = network + } + + enum CodingKeys: String, CodingKey { + case rpcUrl, chainType, options + } + + enum OptionsKeys: String, CodingKey { + case network + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rpcUrl, forKey: .rpcUrl) + try container.encode(BitcoinExtension.chainType, forKey: .chainType) + var options = container.nestedContainer(keyedBy: OptionsKeys.self, forKey: .options) + try options.encode(network, forKey: .network) + } +} + +/// A UTXO to spend. `value` is in BTC (not satoshis), with at most eight decimal +/// places. The enclave needs this value to compute its segwit (BIP143) sighash. +/// `txNum` is the output index (vout) of the UTXO within its source transaction. +public struct BitcoinTransactionInput: Codable { + public let txid: String + public let txNum: Int + public let value: Double + public let address: String? + + public init(txid: String, txNum: Int, value: Double, address: String? = nil) { + self.txid = txid + self.txNum = txNum + self.value = value + self.address = address + } + + enum CodingKeys: String, CodingKey { + case txid + case txNum = "tx_num" + case value, address + } +} + +/// A transaction output. `value` is in BTC with at most eight decimal places. +public struct BitcoinTransactionOutput: Codable { + public let address: String + public let value: Double + + public init(address: String, value: Double) { + self.address = address + self.value = value + } +} + +/// The result of `signTransaction`. +public struct BitcoinSignedTransaction: MagicResponse { + /// The broadcast-ready, fully-signed transaction as hex. + public let signedTransaction: String + /// The transaction hash (txid). + public let transactionHash: String +} + +/// Params for `btc_signTransaction`. +struct BitcoinTransactionParams: Codable { + let inputs: [BitcoinTransactionInput] + let outputs: [BitcoinTransactionOutput] +} diff --git a/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift b/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift new file mode 100644 index 0000000..0ad699f --- /dev/null +++ b/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift @@ -0,0 +1,60 @@ +// +// BitcoinExtension.swift +// MagicSDK +// + +import Foundation +import MagicSDK_Web3 +import PromiseKit + +/// Bitcoin extension for signing transactions. +/// Mirrors the `@magic-ext/bitcoin` package in magic-js. +public class BitcoinExtension: MultichainExtension { + + static let chainType = "BITCOIN" + + init(rpcProvider: RpcProvider) { + super.init(rpcProvider: rpcProvider, chain: BitcoinExtension.chainType) + } + + // MARK: - Sign Transaction + + /// Signs a Bitcoin transaction in the TEE. The caller supplies fully-formed + /// inputs (the UTXOs to spend, each with its value) and outputs. Coin + /// selection, fee, and change are the caller's job. Resolves with the + /// broadcast-ready signed transaction. + /// + /// Input and output values are non-negative BTC amounts with at most eight + /// decimal places. Tiny floating-point errors (up to 0.001 sat) are + /// tolerated. Work out fees and change in integer satoshis, then convert to + /// BTC for this method. Total outputs must not exceed total inputs. The + /// difference is the fee. There is no minimum or maximum signing fee, and + /// no dust threshold is enforced. Check the fee rate (sats/vB) and output + /// amounts against the broadcasting node's policy. Signing does not + /// guarantee relay, confirmation, or UTXO availability. Invalid + /// transaction params fail with an RPC error that describes the problem. + public func signTransaction(inputs: [BitcoinTransactionInput], outputs: [BitcoinTransactionOutput], response: @escaping Web3ResponseCompletion) { + let request = RPCRequest<[BitcoinTransactionParams]>( + method: BitcoinMethod.btc_signTransaction.rawValue, + params: [BitcoinTransactionParams(inputs: inputs, outputs: outputs)] + ) + self.provider.send(request: request, response: response) + } + + /// Promise-based overload of `signTransaction`. + public func signTransaction(inputs: [BitcoinTransactionInput], outputs: [BitcoinTransactionOutput]) -> Promise { + return Promise { resolver in + signTransaction(inputs: inputs, outputs: outputs, response: promiseResolver(resolver)) + } + } +} + +// MARK: - Magic extension + +public extension Magic { + /// Access Bitcoin methods. `nil` unless `Magic` was created with a `BitcoinConfiguration`. + var bitcoin: BitcoinExtension? { + guard extensionConfigurations.contains(where: { $0 is BitcoinConfiguration }) else { return nil } + return BitcoinExtension(rpcProvider: self.rpcProvider) + } +} diff --git a/Sources/MagicSDK/Modules/Extension/ExtensionConfiguration.swift b/Sources/MagicSDK/Modules/Extension/ExtensionConfiguration.swift new file mode 100644 index 0000000..973fb90 --- /dev/null +++ b/Sources/MagicSDK/Modules/Extension/ExtensionConfiguration.swift @@ -0,0 +1,41 @@ +// +// ExtensionConfiguration.swift +// MagicSDK +// + +import Foundation + +/// Configuration for an official Magic extension, such as Solana or Bitcoin. +/// +/// Pass these to `Magic(apiKey:extensions:)`. Each one is sent to the relayer +/// under `ext.` in the URL params, the same as extensions in magic-js. +public protocol ExtensionConfiguration: Encodable { + /// The extension name, e.g. `solana`. Matches the `name` field in magic-js. + var name: String { get } +} + +/// Encodes a list of extension configs as `{ "": , ... }`. +/// A later config with the same name replaces an earlier one, as in magic-js. +struct ExtensionConfigurations: Encodable { + + let configurations: [ExtensionConfiguration] + + var isEmpty: Bool { configurations.isEmpty } + + struct NameKey: CodingKey { + let stringValue: String + var intValue: Int? { nil } + init(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + func encode(to encoder: Encoder) throws { + var byName: [String: ExtensionConfiguration] = [:] + configurations.forEach { byName[$0.name] = $0 } + + var container = encoder.container(keyedBy: NameKey.self) + for (name, configuration) in byName.sorted(by: { $0.key < $1.key }) { + try configuration.encode(to: container.superEncoder(forKey: NameKey(stringValue: name))) + } + } +} diff --git a/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift b/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift new file mode 100644 index 0000000..e29e4c0 --- /dev/null +++ b/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift @@ -0,0 +1,66 @@ +// +// MultichainExtension.swift +// MagicSDK +// + +import Foundation +import MagicSDK_Web3 +import PromiseKit + +internal enum MultichainMethod: String { + case magic_get_multichain_public_address + case magic_reveal_key +} + +/// Base class for non-EVM chain extensions. +/// Mirrors `MultichainExtension` in `@magic-sdk/provider`. +public class MultichainExtension: BaseModule { + + /// The chain type sent to the relayer, e.g. `SOLANA` or `BITCOIN`. + public let chain: String + + init(rpcProvider: RpcProvider, chain: String) { + self.chain = chain + super.init(rpcProvider: rpcProvider) + } + + struct ChainParams: Codable { + let chain: String + } + + // MARK: - Get Public Address + + /// Gets the user's public address on this chain. + public func getPublicAddress(response: @escaping Web3ResponseCompletion) { + let request = RPCRequest<[ChainParams]>( + method: MultichainMethod.magic_get_multichain_public_address.rawValue, + params: [ChainParams(chain: chain)] + ) + self.provider.send(request: request, response: response) + } + + /// Promise-based overload of `getPublicAddress`. + public func getPublicAddress() -> Promise { + return Promise { resolver in + getPublicAddress(response: promiseResolver(resolver)) + } + } + + // MARK: - Reveal Private Key + + /// Shows the Magic UI that reveals the user's private key for this chain. + public func revealPrivateKey(response: @escaping Web3ResponseCompletion) { + let request = RPCRequest<[ChainParams]>( + method: MultichainMethod.magic_reveal_key.rawValue, + params: [ChainParams(chain: chain)] + ) + self.provider.send(request: request, response: response) + } + + /// Promise-based overload of `revealPrivateKey`. + public func revealPrivateKey() -> Promise { + return Promise { resolver in + revealPrivateKey(response: promiseResolver(resolver)) + } + } +} diff --git a/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift b/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift new file mode 100644 index 0000000..23eea56 --- /dev/null +++ b/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift @@ -0,0 +1,146 @@ +// +// SolanaConfiguration.swift +// MagicSDK +// + +import Foundation + +internal enum SolanaMethod: String { + case sol_signTransaction + case sol_signMessage + case sol_partialSignTransaction +} + +/// Enables the Solana extension. Mirrors `SolanaConfig` in `@magic-ext/solana`. +public struct SolanaConfiguration: ExtensionConfiguration { + public let name = "solana" + public let rpcUrl: String + + public init(rpcUrl: String) { + self.rpcUrl = rpcUrl + } + + enum CodingKeys: String, CodingKey { + case rpcUrl, chainType + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rpcUrl, forKey: .rpcUrl) + try container.encode(SolanaExtension.chainType, forKey: .chainType) + } +} + +/// The format of a serialized Solana transaction. +public enum SolanaTransactionType { + /// A legacy `Transaction`. + case legacy + /// A version 0 `VersionedTransaction`. + case v0 +} + +/// Options for serializing a legacy transaction. +/// Mirrors `SerializeConfig` in `@solana/web3.js`. +public struct SolanaSerializeConfig: Codable { + public let requireAllSignatures: Bool? + public let verifySignatures: Bool? + + public init(requireAllSignatures: Bool? = nil, verifySignatures: Bool? = nil) { + self.requireAllSignatures = requireAllSignatures + self.verifySignatures = verifySignatures + } +} + +/// The signed transaction returned by `signTransaction` and `partialSignTransaction`. +public struct SolanaSignedTransaction: MagicResponse { + /// The serialized signed transaction. + public let rawTransaction: Data + + enum CodingKeys: String, CodingKey { + case rawTransaction + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.rawTransaction = try container.decode(TypedArray.self, forKey: .rawTransaction).data + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(TypedArray(rawTransaction), forKey: .rawTransaction) + } +} + +/// Params for `sol_signTransaction` and `sol_partialSignTransaction`. +/// magic-js sends `type` as the string `legacy` or the number `0`. +struct SolanaTransactionParams: Codable { + let type: SolanaTransactionType + let serialized: TypedArray + let serializeConfig: SolanaSerializeConfig? + + enum CodingKeys: String, CodingKey { + case type, serialized, serializeConfig + } + + init(type: SolanaTransactionType, serialized: Data, serializeConfig: SolanaSerializeConfig?) { + self.type = type + self.serialized = TypedArray(serialized) + self.serializeConfig = serializeConfig + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch type { + case .legacy: + try container.encode("legacy", forKey: .type) + case .v0: + try container.encode(0, forKey: .type) + } + try container.encode(serialized, forKey: .serialized) + try container.encodeIfPresent(serializeConfig, forKey: .serializeConfig) + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.type = (try? container.decode(String.self, forKey: .type)) == "legacy" ? .legacy : .v0 + self.serialized = try container.decode(TypedArray.self, forKey: .serialized) + self.serializeConfig = try container.decodeIfPresent(SolanaSerializeConfig.self, forKey: .serializeConfig) + } +} + +/// Params for `sol_signMessage`. The message is sent as a string or as bytes. +struct SolanaSignMessageParams: Codable { + enum Message { + case string(String) + case bytes(TypedArray) + } + + let message: Message + + enum CodingKeys: String, CodingKey { + case message + } + + init(message: Message) { + self.message = message + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch message { + case .string(let value): + try container.encode(value, forKey: .message) + case .bytes(let value): + try container.encode(value, forKey: .message) + } + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if let value = try? container.decode(String.self, forKey: .message) { + self.message = .string(value) + } else { + self.message = .bytes(try container.decode(TypedArray.self, forKey: .message)) + } + } +} diff --git a/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift b/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift new file mode 100644 index 0000000..ab21bff --- /dev/null +++ b/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift @@ -0,0 +1,124 @@ +// +// SolanaExtension.swift +// MagicSDK +// + +import Foundation +import MagicSDK_Web3 +import PromiseKit + +/// Solana extension for signing transactions and messages. +/// Mirrors the `@magic-ext/solana` package in magic-js. +/// +/// magic-js takes `Transaction` and `VersionedTransaction` objects from +/// `@solana/web3.js`. This SDK has no Solana dependency, so it takes the +/// serialized transaction bytes and their `SolanaTransactionType` instead. +/// Serialize a legacy transaction the same way you would pass it to magic-js, +/// usually with `requireAllSignatures: false`. +public class SolanaExtension: MultichainExtension { + + static let chainType = "SOLANA" + + init(rpcProvider: RpcProvider) { + super.init(rpcProvider: rpcProvider, chain: SolanaExtension.chainType) + } + + // MARK: - Sign Transaction + + /// Signs a Solana transaction. + /// + /// - Parameters: + /// - serialized: The serialized transaction. + /// - type: `.legacy` for a `Transaction`, `.v0` for a `VersionedTransaction`. + /// - serializeConfig: The config used to serialize the signed legacy transaction. + /// - response: Completion handler called with the signed transaction or an error. + public func signTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil, response: @escaping Web3ResponseCompletion) { + let request = RPCRequest( + method: SolanaMethod.sol_signTransaction.rawValue, + params: SolanaTransactionParams(type: type, serialized: serialized, serializeConfig: serializeConfig) + ) + self.provider.send(request: request, response: response) + } + + /// Promise-based overload of `signTransaction`. + public func signTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil) -> Promise { + return Promise { resolver in + signTransaction(serialized, type: type, serializeConfig: serializeConfig, response: promiseResolver(resolver)) + } + } + + // MARK: - Partial Sign Transaction + + /// Adds the user's signature to a transaction that other parties also sign. + /// + /// - Parameters: + /// - serialized: The serialized transaction. + /// - type: `.legacy` for a `Transaction`, `.v0` for a `VersionedTransaction`. + /// - serializeConfig: The config used to serialize the signed legacy transaction. + /// - response: Completion handler called with the partly signed transaction or an error. + public func partialSignTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil, response: @escaping Web3ResponseCompletion) { + let request = RPCRequest( + method: SolanaMethod.sol_partialSignTransaction.rawValue, + params: SolanaTransactionParams(type: type, serialized: serialized, serializeConfig: serializeConfig) + ) + self.provider.send(request: request, response: response) + } + + /// Promise-based overload of `partialSignTransaction`. + public func partialSignTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil) -> Promise { + return Promise { resolver in + partialSignTransaction(serialized, type: type, serializeConfig: serializeConfig, response: promiseResolver(resolver)) + } + } + + // MARK: - Sign Message + + /// Signs a UTF-8 message. Resolves with the 64-byte ed25519 signature. + public func signMessage(_ message: String, response: @escaping Web3ResponseCompletion) { + signMessage(.string(message), response: response) + } + + /// Signs raw bytes. Resolves with the 64-byte ed25519 signature. + public func signMessage(_ message: Data, response: @escaping Web3ResponseCompletion) { + signMessage(.bytes(TypedArray(message)), response: response) + } + + /// Promise-based overload of `signMessage` for a UTF-8 message. + public func signMessage(_ message: String) -> Promise { + return Promise { resolver in + signMessage(message, response: promiseResolver(resolver)) + } + } + + /// Promise-based overload of `signMessage` for raw bytes. + public func signMessage(_ message: Data) -> Promise { + return Promise { resolver in + signMessage(message, response: promiseResolver(resolver)) + } + } + + private func signMessage(_ message: SolanaSignMessageParams.Message, response: @escaping Web3ResponseCompletion) { + let request = RPCRequest( + method: SolanaMethod.sol_signMessage.rawValue, + params: SolanaSignMessageParams(message: message) + ) + self.provider.send(request: request) { (result: Web3Response) in + switch result.status { + case let .success(signature): + response(Web3Response(status: .success(signature.data))) + case let .failure(error): + response(Web3Response(error: error)) + } + } + } +} + +// MARK: - Magic extension + +public extension Magic { + /// Access Solana methods. `nil` unless `Magic` was created with a `SolanaConfiguration`. + var solana: SolanaExtension? { + guard extensionConfigurations.contains(where: { $0 is SolanaConfiguration }) else { return nil } + return SolanaExtension(rpcProvider: self.rpcProvider) + } +} diff --git a/Tests/MagicSDKTests/MultichainExtensionTests.swift b/Tests/MagicSDKTests/MultichainExtensionTests.swift new file mode 100644 index 0000000..27dcb62 --- /dev/null +++ b/Tests/MagicSDKTests/MultichainExtensionTests.swift @@ -0,0 +1,161 @@ +import XCTest +import MagicSDK_Web3 +@testable import MagicSDK + +final class MultichainExtensionTests: XCTestCase { + + private func json(_ value: Encodable) throws -> [String: Any] { + struct Box: Encodable { + let value: Encodable + func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } + } + let data = try JSONEncoder().encode(Box(value: value)) + return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private func urlParams(_ urlBuilder: URLBuilder) throws -> [String: Any] { + let decoded = atob(encodedString: urlBuilder.encodedParams) + return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(decoded.utf8)) as? [String: Any]) + } + + // MARK: - Typed array + + func testTypedArrayEncodesInMgboxFormat() throws { + let encoded = try json(TypedArray(Data([99, 53, 247]))) + XCTAssertEqual(encoded["constructor"] as? String, "Uint8Array") + XCTAssertEqual(encoded["data"] as? String, "99,53,247") + XCTAssertEqual(encoded["flag"] as? String, "MAGIC_PAYLOAD_FLAG_TYPED_ARRAY") + } + + func testTypedArrayDecodesBufferAndEmpty() throws { + let buffer = #"{"constructor":"Buffer","data":"1,2,255","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}"# + XCTAssertEqual(try JSONDecoder().decode(TypedArray.self, from: Data(buffer.utf8)).data, Data([1, 2, 255])) + + let empty = #"{"constructor":"Uint8Array","data":"","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}"# + XCTAssertEqual(try JSONDecoder().decode(TypedArray.self, from: Data(empty.utf8)).data, Data()) + } + + func testTypedArrayRejectsBadInput() { + let noFlag = #"{"constructor":"Uint8Array","data":"1,2","flag":"OTHER"}"# + XCTAssertThrowsError(try JSONDecoder().decode(TypedArray.self, from: Data(noFlag.utf8))) + + let badByte = #"{"constructor":"Uint8Array","data":"1,256","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}"# + XCTAssertThrowsError(try JSONDecoder().decode(TypedArray.self, from: Data(badByte.utf8))) + } + + // MARK: - URL params + + func testUrlParamsOmitExtWithoutExtensions() throws { + let params = try urlParams(URLBuilder(apiKey: "pk_test", network: .mainnet, locale: "en_US")) + XCTAssertNil(params["ext"]) + XCTAssertEqual(params["ETH_NETWORK"] as? String, "mainnet") + } + + func testUrlParamsEncodeExtLikeMagicJs() throws { + let urlBuilder = URLBuilder( + apiKey: "pk_test", + network: .mainnet, + extensions: [ + SolanaConfiguration(rpcUrl: "https://api.devnet.solana.com"), + BitcoinConfiguration(rpcUrl: "https://btc.example.com", network: "testnet"), + ], + locale: "en_US" + ) + let ext = try XCTUnwrap(try urlParams(urlBuilder)["ext"] as? [String: Any]) + + let solana = try XCTUnwrap(ext["solana"] as? [String: Any]) + XCTAssertEqual(solana.count, 2) + XCTAssertEqual(solana["rpcUrl"] as? String, "https://api.devnet.solana.com") + XCTAssertEqual(solana["chainType"] as? String, "SOLANA") + + let bitcoin = try XCTUnwrap(ext["bitcoin"] as? [String: Any]) + XCTAssertEqual(bitcoin.count, 3) + XCTAssertEqual(bitcoin["rpcUrl"] as? String, "https://btc.example.com") + XCTAssertEqual(bitcoin["chainType"] as? String, "BITCOIN") + XCTAssertEqual(bitcoin["options"] as? [String: String], ["network": "testnet"]) + } + + func testLaterExtensionWithSameNameWins() throws { + let urlBuilder = URLBuilder( + apiKey: "pk_test", + extensions: [SolanaConfiguration(rpcUrl: "https://a"), SolanaConfiguration(rpcUrl: "https://b")], + locale: "en_US" + ) + let ext = try XCTUnwrap(try urlParams(urlBuilder)["ext"] as? [String: Any]) + XCTAssertEqual((ext["solana"] as? [String: Any])?["rpcUrl"] as? String, "https://b") + } + + // MARK: - Solana params + + func testSolanaLegacyTransactionParams() throws { + let params = try json(SolanaTransactionParams( + type: .legacy, + serialized: Data([1, 2, 3]), + serializeConfig: SolanaSerializeConfig(requireAllSignatures: false) + )) + XCTAssertEqual(params["type"] as? String, "legacy") + XCTAssertEqual((params["serialized"] as? [String: Any])?["data"] as? String, "1,2,3") + XCTAssertEqual(params["serializeConfig"] as? [String: Bool], ["requireAllSignatures": false]) + } + + func testSolanaVersionedTransactionParams() throws { + let params = try json(SolanaTransactionParams(type: .v0, serialized: Data([4]), serializeConfig: nil)) + XCTAssertEqual(params["type"] as? Int, 0) + XCTAssertNil(params["serializeConfig"]) + } + + func testSolanaSignMessageParams() throws { + XCTAssertEqual(try json(SolanaSignMessageParams(message: .string("hello")))["message"] as? String, "hello") + + let bytes = try json(SolanaSignMessageParams(message: .bytes(TypedArray(Data([7, 8]))))) + XCTAssertEqual((bytes["message"] as? [String: Any])?["data"] as? String, "7,8") + } + + func testSolanaSignedTransactionDecodesMgboxResponse() throws { + let response = #""" + {"rawTransaction":{"constructor":"Buffer","data":"9,8,7","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}, + "signature":[{"signature":null,"publicKey":"11111111111111111111111111111111"}]} + """# + let signed = try JSONDecoder().decode(SolanaSignedTransaction.self, from: Data(response.utf8)) + XCTAssertEqual(signed.rawTransaction, Data([9, 8, 7])) + } + + // MARK: - Bitcoin params + + func testBitcoinTransactionParams() throws { + let params = try json(BitcoinTransactionParams( + inputs: [BitcoinTransactionInput(txid: "abc", txNum: 1, value: 0.0001)], + outputs: [BitcoinTransactionOutput(address: "tb1q", value: 0.00005)] + )) + let input = try XCTUnwrap((params["inputs"] as? [[String: Any]])?.first) + XCTAssertEqual(input["txid"] as? String, "abc") + XCTAssertEqual(input["tx_num"] as? Int, 1) + XCTAssertEqual(input["value"] as? Double, 0.0001) + XCTAssertNil(input["address"]) + XCTAssertNil(input["txNum"]) + + let output = try XCTUnwrap((params["outputs"] as? [[String: Any]])?.first) + XCTAssertEqual(output["address"] as? String, "tb1q") + XCTAssertEqual(output["value"] as? Double, 0.00005) + } + + // MARK: - Request shape + + func testMultichainRequestShape() throws { + let request = RPCRequest<[MultichainExtension.ChainParams]>( + method: MultichainMethod.magic_get_multichain_public_address.rawValue, + params: [MultichainExtension.ChainParams(chain: SolanaExtension.chainType)] + ) + let encoded = try json(request) + XCTAssertEqual(encoded["method"] as? String, "magic_get_multichain_public_address") + XCTAssertEqual(encoded["params"] as? [[String: String]], [["chain": "SOLANA"]]) + } + + func testMethodNamesMatchMagicJs() { + XCTAssertEqual(SolanaMethod.sol_signTransaction.rawValue, "sol_signTransaction") + XCTAssertEqual(SolanaMethod.sol_signMessage.rawValue, "sol_signMessage") + XCTAssertEqual(SolanaMethod.sol_partialSignTransaction.rawValue, "sol_partialSignTransaction") + XCTAssertEqual(BitcoinMethod.btc_signTransaction.rawValue, "btc_signTransaction") + XCTAssertEqual(MultichainMethod.magic_reveal_key.rawValue, "magic_reveal_key") + } +} From 1dcc82c713ef52506ca755f3a5113b7938ab52f3 Mon Sep 17 00:00:00 2001 From: Jerry Liu Date: Fri, 16 Oct 2026 12:31:24 -0700 Subject: [PATCH 2/5] Stop String(format:) from changing messages that contain a percent sign postMessage put the whole request into a format string, so a message such as a URL with %2F was altered before signing, and %@ could crash the app. Build the script by concatenation instead and test it. Co-Authored-By: Claude Sonnet 5.5 --- .../Core/Relayer/WebViewController.swift | 17 +++++++--- .../WebViewControllerTests.swift | 34 +++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) create mode 100644 Tests/MagicSDKTests/WebViewControllerTests.swift diff --git a/Sources/MagicSDK/Core/Relayer/WebViewController.swift b/Sources/MagicSDK/Core/Relayer/WebViewController.swift index 2aec038..941c7b3 100644 --- a/Sources/MagicSDK/Core/Relayer/WebViewController.swift +++ b/Sources/MagicSDK/Core/Relayer/WebViewController.swift @@ -202,7 +202,18 @@ class WebViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, /// post Message to HTML via evaluateJavaScript /// internal func postMessage(message: String) throws -> Void { + let execString = try WebViewController.dispatchScript(for: message) + webView.evaluateJavaScript(execString) { _, err in + if let err = err { print("Magic internal error evaluateJavaScript: \(err)") } + } + } + /// The script that delivers `message` to the relayer page. + /// + /// The message is joined by concatenation, not `String(format:)`. A message + /// holding a `%`, such as a URL with `%2F` in a text to sign, would otherwise + /// be read as a format specifier and change before it is signed. + internal static func dispatchScript(for message: String) throws -> String { let data: [String: String] = ["data": message] guard let json = try? JSONEncoder().encode(data), @@ -210,15 +221,11 @@ class WebViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, throw AuthRelayerError.messageEncodeFailed(message: message) } - let execString = String(format: "window.dispatchEvent(new MessageEvent('message', \(jsonString)));") - webView.evaluateJavaScript(execString) { _, err in - if let err = err { print("Magic internal error evaluateJavaScript: \(err)") } - } + return "window.dispatchEvent(new MessageEvent('message', " + jsonString + "));" } - // MARK: - view loading /// loadView will be triggered when addsubview is called. It will create a webview to post messages to auth relayer override func loadView() { diff --git a/Tests/MagicSDKTests/WebViewControllerTests.swift b/Tests/MagicSDKTests/WebViewControllerTests.swift new file mode 100644 index 0000000..4658360 --- /dev/null +++ b/Tests/MagicSDKTests/WebViewControllerTests.swift @@ -0,0 +1,34 @@ +// +// WebViewControllerTests.swift +// MagicSDKTests +// + +import XCTest +@testable import MagicSDK + +class WebViewControllerTests: XCTestCase { + + /// Pulls the message back out of the script, the way the relayer page reads it. + private func decodedMessage(from script: String) throws -> String { + let prefix = "window.dispatchEvent(new MessageEvent('message', " + let suffix = "));" + XCTAssertTrue(script.hasPrefix(prefix) && script.hasSuffix(suffix)) + let json = String(script.dropFirst(prefix.count).dropLast(suffix.count)) + let object = try JSONDecoder().decode([String: String].self, from: Data(json.utf8)) + return try XCTUnwrap(object["data"]) + } + + func testDispatchScriptKeepsPercentSignsUnchanged() throws { + let messages = [ + "hello", + "https://example.com/?q=a%2Fb&x=1", + "growth 100%", + "price %d units", + "%@ %s %n %%", + ] + for message in messages { + let script = try WebViewController.dispatchScript(for: message) + XCTAssertEqual(try decodedMessage(from: script), message) + } + } +} From fa4f697b7a6d8417bab997189e687bdcf1516688 Mon Sep 17 00:00:00 2001 From: Jerry Liu Date: Mon, 19 Oct 2026 14:30:23 -0700 Subject: [PATCH 3/5] Document Solana and Bitcoin in the README Adds setup, signing a message, signing and partly signing Solana transactions (legacy and v0), and signing a Bitcoin transaction. Points the example section at magic-ios-demo, since Example/MagicDemo does not exist. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 114 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bcf1586..61f5d6f 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,121 @@ dependencies: [ ] ``` +## Quick start + +```swift +import MagicSDK + +Magic.shared = Magic(apiKey: "YOUR_PUBLISHABLE_API_KEY") +``` + +## Solana and Bitcoin + +Solana and Bitcoin work like the `@magic-ext/solana` and `@magic-ext/bitcoin` packages in magic-js. Turn them on by passing a configuration when you create `Magic`: + +```swift +Magic.shared = Magic( + apiKey: "YOUR_PUBLISHABLE_API_KEY", + extensions: [ + SolanaConfiguration(rpcUrl: "https://api.devnet.solana.com"), + BitcoinConfiguration(rpcUrl: "https://blockstream.info/testnet/api", network: "testnet") + ] +) +``` + +`Magic.shared.solana` and `Magic.shared.bitcoin` are `nil` until you pass the matching configuration. The user must be logged in first. + +Both extensions have these methods. Each one has a completion-handler version and a PromiseKit version. + +- `getPublicAddress` returns the user's address on that chain. +- `revealPrivateKey` shows Magic's UI for exporting the key. The key never reaches your app. + +```swift +Magic.shared.solana?.getPublicAddress { response in + print(response.result ?? response.error?.localizedDescription ?? "") +} +``` + +### Sign a Solana message + +```swift +// A String is signed as UTF-8. You can also pass Data. +Magic.shared.solana?.signMessage("Sign in to Example") { response in + // response.result is the 64-byte ed25519 signature, as Data +} +``` + +### Sign a Solana transaction + +The SDK has no Solana dependency, so you give it the serialized transaction bytes and say which kind it is. Build the bytes with a Solana library or by hand. In `@solana/web3.js` this is `Transaction.serialize({ requireAllSignatures: false })` for a legacy transaction, or `VersionedTransaction.serialize()` for a version 0 transaction. + +- `.legacy` is for a legacy `Transaction`. +- `.v0` is for a `VersionedTransaction`. + +```swift +let serialized: Data = ... // the serialized, unsigned transaction + +Magic.shared.solana?.signTransaction(serialized, type: .legacy) { response in + if let signed = response.result { + let rawTransaction: Data = signed.rawTransaction + // Send rawTransaction to a Solana node, for example with sendRawTransaction. + } else if let error = response.error { + print(error.localizedDescription) + } +} +``` + +Use `type: .v0` for a version 0 transaction. + +### Partly sign a Solana transaction + +Use `partialSignTransaction` when other people also have to sign, such as a fee payer. It adds the user's signature and leaves the other slots empty. + +```swift +// serializeConfig only applies to legacy transactions, as in magic-js. +let config = SolanaSerializeConfig(requireAllSignatures: false, verifySignatures: false) + +Magic.shared.solana?.partialSignTransaction(serialized, type: .legacy, serializeConfig: config) { response in + let partlySigned = response.result?.rawTransaction + // Pass it on to the next signer. +} +``` + +### Sign a Bitcoin transaction + +You choose the inputs (the UTXOs to spend), the outputs and the change. Magic signs the result and returns a transaction that is ready to broadcast. + +- Amounts are in BTC, not satoshis, with at most eight decimal places. +- `txNum` is the output index (vout) of the UTXO in its source transaction. +- Each input needs its `value`, because the signature covers the amount being spent. +- The fee is whatever is left after the outputs. Total outputs must not be more than total inputs. There is no minimum or maximum fee, so check it yourself. + +```swift +let inputs = [ + BitcoinTransactionInput(txid: "", txNum: 0, value: 0.001) +] +let outputs = [ + BitcoinTransactionOutput(address: "", value: 0.0009) // 0.0001 BTC fee +] + +Magic.shared.bitcoin?.signTransaction(inputs: inputs, outputs: outputs) { response in + if let signed = response.result { + print(signed.signedTransaction) // hex, ready to broadcast + print(signed.transactionHash) // txid + } else if let error = response.error { + print(error.localizedDescription) + } +} +``` + +Work out fees and change in whole satoshis, then convert to BTC for the call. Signing does not mean the network will accept the transaction. + +### Before you broadcast + +The signed result comes back through Magic's relayer. Decode `rawTransaction` or `signedTransaction` and check the amounts and addresses before you send it. + ## Example -A SwiftUI demo app is included in `Example/MagicDemo`. Add the MagicSDK package to your app (Swift Package Manager) and copy the example source files into your target. Set your publishable API key in `MagicDemoApp.swift`. +The [magic-ios-demo](https://github.com/magiclabs/magic-ios-demo) app shows login, EVM, Solana (legacy and v0 transactions) and Bitcoin. Open `magic-ios-spm-demo.xcodeproj`, not the workspace, and set your publishable API key in `AppDelegate.swift`. --- From 05520122296e4a6f8b0226719c363d71e4654586 Mon Sep 17 00:00:00 2001 From: Jerry Liu Date: Mon, 19 Oct 2026 14:36:59 -0700 Subject: [PATCH 4/5] Update stale README information Removes the v9.0.0 loginWithMagicLink banner (the API is gone and its link now redirects to the docs home), bumps the install version to the latest release 10.3.0, and links the iOS SDK reference. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61f5d6f..e19a17e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # MagicSDK -## ⚠️ Removal of `loginWithMagicLink()` ⚠️ -As of `v9.0.0`, passcodes (ie. `loginWithSMS()`, `loginWithEmailOTP()`) are replacing Magic Links (ie. `loginWithMagicLink()`) for all of our Mobile SDKs⁠. [Learn more](https://magic.link/docs/auth/login-methods/email/email-link-update-march-2023) +The Magic SDK for iOS. It adds passwordless login and an embedded wallet to your app. See the [iOS SDK reference](https://docs.magic.link/embedded-wallets/sdk/client-side/ios) for the full guide. + +Requires iOS 13 or later. ## Swift Package Manager @@ -15,7 +16,7 @@ Or add it to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/magiclabs/magic-ios.git", from: "10.2.0") + .package(url: "https://github.com/magiclabs/magic-ios.git", from: "10.3.0") ] ``` From e9f4486b798c09830ddffbfd56c981e35748d727 Mon Sep 17 00:00:00 2001 From: Jerry Liu Date: Thu, 22 Oct 2026 08:37:37 -0700 Subject: [PATCH 5/5] Move Solana and Bitcoin to magic-ios-ext, keep the shared hooks Solana and Bitcoin are now the MagicExt-Solana and MagicExt-Bitcoin products in magic-ios-ext, like magic-js ships them as separate @magic-ext packages. This package keeps what they need: ExtensionConfiguration, Magic(apiKey:extensions:), the ext URL param, the open MultichainExtension base class, TypedArray, and the postMessage percent-sign fix. Magic.extensionConfigurations is now public. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 103 +----------- Sources/MagicSDK/Core/Magic.swift | 7 +- .../Bitcoin/BitcoinConfiguration.swift | 86 ----------- .../Modules/Bitcoin/BitcoinExtension.swift | 60 ------- .../Multichain/MultichainExtension.swift | 8 +- .../Modules/Solana/SolanaConfiguration.swift | 146 ------------------ .../Modules/Solana/SolanaExtension.swift | 124 --------------- .../MultichainExtensionTests.swift | 84 +++------- 8 files changed, 31 insertions(+), 587 deletions(-) delete mode 100644 Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift delete mode 100644 Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift delete mode 100644 Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift delete mode 100644 Sources/MagicSDK/Modules/Solana/SolanaExtension.swift diff --git a/README.md b/README.md index e19a17e..391a6ee 100644 --- a/README.md +++ b/README.md @@ -30,108 +30,7 @@ Magic.shared = Magic(apiKey: "YOUR_PUBLISHABLE_API_KEY") ## Solana and Bitcoin -Solana and Bitcoin work like the `@magic-ext/solana` and `@magic-ext/bitcoin` packages in magic-js. Turn them on by passing a configuration when you create `Magic`: - -```swift -Magic.shared = Magic( - apiKey: "YOUR_PUBLISHABLE_API_KEY", - extensions: [ - SolanaConfiguration(rpcUrl: "https://api.devnet.solana.com"), - BitcoinConfiguration(rpcUrl: "https://blockstream.info/testnet/api", network: "testnet") - ] -) -``` - -`Magic.shared.solana` and `Magic.shared.bitcoin` are `nil` until you pass the matching configuration. The user must be logged in first. - -Both extensions have these methods. Each one has a completion-handler version and a PromiseKit version. - -- `getPublicAddress` returns the user's address on that chain. -- `revealPrivateKey` shows Magic's UI for exporting the key. The key never reaches your app. - -```swift -Magic.shared.solana?.getPublicAddress { response in - print(response.result ?? response.error?.localizedDescription ?? "") -} -``` - -### Sign a Solana message - -```swift -// A String is signed as UTF-8. You can also pass Data. -Magic.shared.solana?.signMessage("Sign in to Example") { response in - // response.result is the 64-byte ed25519 signature, as Data -} -``` - -### Sign a Solana transaction - -The SDK has no Solana dependency, so you give it the serialized transaction bytes and say which kind it is. Build the bytes with a Solana library or by hand. In `@solana/web3.js` this is `Transaction.serialize({ requireAllSignatures: false })` for a legacy transaction, or `VersionedTransaction.serialize()` for a version 0 transaction. - -- `.legacy` is for a legacy `Transaction`. -- `.v0` is for a `VersionedTransaction`. - -```swift -let serialized: Data = ... // the serialized, unsigned transaction - -Magic.shared.solana?.signTransaction(serialized, type: .legacy) { response in - if let signed = response.result { - let rawTransaction: Data = signed.rawTransaction - // Send rawTransaction to a Solana node, for example with sendRawTransaction. - } else if let error = response.error { - print(error.localizedDescription) - } -} -``` - -Use `type: .v0` for a version 0 transaction. - -### Partly sign a Solana transaction - -Use `partialSignTransaction` when other people also have to sign, such as a fee payer. It adds the user's signature and leaves the other slots empty. - -```swift -// serializeConfig only applies to legacy transactions, as in magic-js. -let config = SolanaSerializeConfig(requireAllSignatures: false, verifySignatures: false) - -Magic.shared.solana?.partialSignTransaction(serialized, type: .legacy, serializeConfig: config) { response in - let partlySigned = response.result?.rawTransaction - // Pass it on to the next signer. -} -``` - -### Sign a Bitcoin transaction - -You choose the inputs (the UTXOs to spend), the outputs and the change. Magic signs the result and returns a transaction that is ready to broadcast. - -- Amounts are in BTC, not satoshis, with at most eight decimal places. -- `txNum` is the output index (vout) of the UTXO in its source transaction. -- Each input needs its `value`, because the signature covers the amount being spent. -- The fee is whatever is left after the outputs. Total outputs must not be more than total inputs. There is no minimum or maximum fee, so check it yourself. - -```swift -let inputs = [ - BitcoinTransactionInput(txid: "", txNum: 0, value: 0.001) -] -let outputs = [ - BitcoinTransactionOutput(address: "", value: 0.0009) // 0.0001 BTC fee -] - -Magic.shared.bitcoin?.signTransaction(inputs: inputs, outputs: outputs) { response in - if let signed = response.result { - print(signed.signedTransaction) // hex, ready to broadcast - print(signed.transactionHash) // txid - } else if let error = response.error { - print(error.localizedDescription) - } -} -``` - -Work out fees and change in whole satoshis, then convert to BTC for the call. Signing does not mean the network will accept the transaction. - -### Before you broadcast - -The signed result comes back through Magic's relayer. Decode `rawTransaction` or `signedTransaction` and check the amounts and addresses before you send it. +Solana and Bitcoin live in the [magic-ios-ext](https://github.com/magiclabs/magic-ios-ext) package, as the `MagicExt-Solana` and `MagicExt-Bitcoin` products. This SDK has the hooks they use: pass their configurations to `Magic(apiKey:extensions:)`, and read the result from `Magic.shared.solana` or `Magic.shared.bitcoin`. See that repo's README for how to sign messages and transactions. ## Example diff --git a/Sources/MagicSDK/Core/Magic.swift b/Sources/MagicSDK/Core/Magic.swift index e9580df..9e183da 100644 --- a/Sources/MagicSDK/Core/Magic.swift +++ b/Sources/MagicSDK/Core/Magic.swift @@ -22,8 +22,9 @@ public class Magic: NSObject { // MARK: - Property public var rpcProvider: RpcProvider - /// Extensions this instance was created with - let extensionConfigurations: [ExtensionConfiguration] + /// Extensions this instance was created with. Extension packages such as + /// `MagicExt-Solana` read this to tell whether they were enabled. + public let extensionConfigurations: [ExtensionConfiguration] /// Shared instance of `Magic` public static var shared: Magic! @@ -36,7 +37,7 @@ public class Magic: NSObject { /// - apiKey: Your client ID. From https://dashboard.Magic.com /// - ethNetwork: Etherum Network setting (ie. mainnet or goerli) /// - customNode: A custom RPC node - /// - extensions: Chain extensions to enable, e.g. `SolanaConfiguration` or `BitcoinConfiguration` + /// - extensions: Chain extensions to enable, e.g. `SolanaConfiguration` from `MagicExt-Solana` public convenience init(apiKey: String, ethNetwork: EthNetwork, extensions: [ExtensionConfiguration] = [], locale: String = Locale.current.identifier) { self.init(urlBuilder: URLBuilder(apiKey: apiKey, network: ethNetwork, extensions: extensions, locale: locale), extensions: extensions) } diff --git a/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift b/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift deleted file mode 100644 index 33105a4..0000000 --- a/Sources/MagicSDK/Modules/Bitcoin/BitcoinConfiguration.swift +++ /dev/null @@ -1,86 +0,0 @@ -// -// BitcoinConfiguration.swift -// MagicSDK -// - -import Foundation - -internal enum BitcoinMethod: String { - case btc_signTransaction -} - -/// Enables the Bitcoin extension. Mirrors `BitcoinConfig` in `@magic-ext/bitcoin`. -public struct BitcoinConfiguration: ExtensionConfiguration { - public let name = "bitcoin" - public let rpcUrl: String - public let network: String - - public init(rpcUrl: String, network: String) { - self.rpcUrl = rpcUrl - self.network = network - } - - enum CodingKeys: String, CodingKey { - case rpcUrl, chainType, options - } - - enum OptionsKeys: String, CodingKey { - case network - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(rpcUrl, forKey: .rpcUrl) - try container.encode(BitcoinExtension.chainType, forKey: .chainType) - var options = container.nestedContainer(keyedBy: OptionsKeys.self, forKey: .options) - try options.encode(network, forKey: .network) - } -} - -/// A UTXO to spend. `value` is in BTC (not satoshis), with at most eight decimal -/// places. The enclave needs this value to compute its segwit (BIP143) sighash. -/// `txNum` is the output index (vout) of the UTXO within its source transaction. -public struct BitcoinTransactionInput: Codable { - public let txid: String - public let txNum: Int - public let value: Double - public let address: String? - - public init(txid: String, txNum: Int, value: Double, address: String? = nil) { - self.txid = txid - self.txNum = txNum - self.value = value - self.address = address - } - - enum CodingKeys: String, CodingKey { - case txid - case txNum = "tx_num" - case value, address - } -} - -/// A transaction output. `value` is in BTC with at most eight decimal places. -public struct BitcoinTransactionOutput: Codable { - public let address: String - public let value: Double - - public init(address: String, value: Double) { - self.address = address - self.value = value - } -} - -/// The result of `signTransaction`. -public struct BitcoinSignedTransaction: MagicResponse { - /// The broadcast-ready, fully-signed transaction as hex. - public let signedTransaction: String - /// The transaction hash (txid). - public let transactionHash: String -} - -/// Params for `btc_signTransaction`. -struct BitcoinTransactionParams: Codable { - let inputs: [BitcoinTransactionInput] - let outputs: [BitcoinTransactionOutput] -} diff --git a/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift b/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift deleted file mode 100644 index 0ad699f..0000000 --- a/Sources/MagicSDK/Modules/Bitcoin/BitcoinExtension.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// BitcoinExtension.swift -// MagicSDK -// - -import Foundation -import MagicSDK_Web3 -import PromiseKit - -/// Bitcoin extension for signing transactions. -/// Mirrors the `@magic-ext/bitcoin` package in magic-js. -public class BitcoinExtension: MultichainExtension { - - static let chainType = "BITCOIN" - - init(rpcProvider: RpcProvider) { - super.init(rpcProvider: rpcProvider, chain: BitcoinExtension.chainType) - } - - // MARK: - Sign Transaction - - /// Signs a Bitcoin transaction in the TEE. The caller supplies fully-formed - /// inputs (the UTXOs to spend, each with its value) and outputs. Coin - /// selection, fee, and change are the caller's job. Resolves with the - /// broadcast-ready signed transaction. - /// - /// Input and output values are non-negative BTC amounts with at most eight - /// decimal places. Tiny floating-point errors (up to 0.001 sat) are - /// tolerated. Work out fees and change in integer satoshis, then convert to - /// BTC for this method. Total outputs must not exceed total inputs. The - /// difference is the fee. There is no minimum or maximum signing fee, and - /// no dust threshold is enforced. Check the fee rate (sats/vB) and output - /// amounts against the broadcasting node's policy. Signing does not - /// guarantee relay, confirmation, or UTXO availability. Invalid - /// transaction params fail with an RPC error that describes the problem. - public func signTransaction(inputs: [BitcoinTransactionInput], outputs: [BitcoinTransactionOutput], response: @escaping Web3ResponseCompletion) { - let request = RPCRequest<[BitcoinTransactionParams]>( - method: BitcoinMethod.btc_signTransaction.rawValue, - params: [BitcoinTransactionParams(inputs: inputs, outputs: outputs)] - ) - self.provider.send(request: request, response: response) - } - - /// Promise-based overload of `signTransaction`. - public func signTransaction(inputs: [BitcoinTransactionInput], outputs: [BitcoinTransactionOutput]) -> Promise { - return Promise { resolver in - signTransaction(inputs: inputs, outputs: outputs, response: promiseResolver(resolver)) - } - } -} - -// MARK: - Magic extension - -public extension Magic { - /// Access Bitcoin methods. `nil` unless `Magic` was created with a `BitcoinConfiguration`. - var bitcoin: BitcoinExtension? { - guard extensionConfigurations.contains(where: { $0 is BitcoinConfiguration }) else { return nil } - return BitcoinExtension(rpcProvider: self.rpcProvider) - } -} diff --git a/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift b/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift index e29e4c0..52064fb 100644 --- a/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift +++ b/Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift @@ -12,14 +12,14 @@ internal enum MultichainMethod: String { case magic_reveal_key } -/// Base class for non-EVM chain extensions. -/// Mirrors `MultichainExtension` in `@magic-sdk/provider`. -public class MultichainExtension: BaseModule { +/// Base class for non-EVM chain extensions, such as `SolanaExtension` in the +/// `MagicExt-Solana` package. Mirrors `MultichainExtension` in `@magic-sdk/provider`. +open class MultichainExtension: BaseModule { /// The chain type sent to the relayer, e.g. `SOLANA` or `BITCOIN`. public let chain: String - init(rpcProvider: RpcProvider, chain: String) { + public init(rpcProvider: RpcProvider, chain: String) { self.chain = chain super.init(rpcProvider: rpcProvider) } diff --git a/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift b/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift deleted file mode 100644 index 23eea56..0000000 --- a/Sources/MagicSDK/Modules/Solana/SolanaConfiguration.swift +++ /dev/null @@ -1,146 +0,0 @@ -// -// SolanaConfiguration.swift -// MagicSDK -// - -import Foundation - -internal enum SolanaMethod: String { - case sol_signTransaction - case sol_signMessage - case sol_partialSignTransaction -} - -/// Enables the Solana extension. Mirrors `SolanaConfig` in `@magic-ext/solana`. -public struct SolanaConfiguration: ExtensionConfiguration { - public let name = "solana" - public let rpcUrl: String - - public init(rpcUrl: String) { - self.rpcUrl = rpcUrl - } - - enum CodingKeys: String, CodingKey { - case rpcUrl, chainType - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(rpcUrl, forKey: .rpcUrl) - try container.encode(SolanaExtension.chainType, forKey: .chainType) - } -} - -/// The format of a serialized Solana transaction. -public enum SolanaTransactionType { - /// A legacy `Transaction`. - case legacy - /// A version 0 `VersionedTransaction`. - case v0 -} - -/// Options for serializing a legacy transaction. -/// Mirrors `SerializeConfig` in `@solana/web3.js`. -public struct SolanaSerializeConfig: Codable { - public let requireAllSignatures: Bool? - public let verifySignatures: Bool? - - public init(requireAllSignatures: Bool? = nil, verifySignatures: Bool? = nil) { - self.requireAllSignatures = requireAllSignatures - self.verifySignatures = verifySignatures - } -} - -/// The signed transaction returned by `signTransaction` and `partialSignTransaction`. -public struct SolanaSignedTransaction: MagicResponse { - /// The serialized signed transaction. - public let rawTransaction: Data - - enum CodingKeys: String, CodingKey { - case rawTransaction - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.rawTransaction = try container.decode(TypedArray.self, forKey: .rawTransaction).data - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(TypedArray(rawTransaction), forKey: .rawTransaction) - } -} - -/// Params for `sol_signTransaction` and `sol_partialSignTransaction`. -/// magic-js sends `type` as the string `legacy` or the number `0`. -struct SolanaTransactionParams: Codable { - let type: SolanaTransactionType - let serialized: TypedArray - let serializeConfig: SolanaSerializeConfig? - - enum CodingKeys: String, CodingKey { - case type, serialized, serializeConfig - } - - init(type: SolanaTransactionType, serialized: Data, serializeConfig: SolanaSerializeConfig?) { - self.type = type - self.serialized = TypedArray(serialized) - self.serializeConfig = serializeConfig - } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - switch type { - case .legacy: - try container.encode("legacy", forKey: .type) - case .v0: - try container.encode(0, forKey: .type) - } - try container.encode(serialized, forKey: .serialized) - try container.encodeIfPresent(serializeConfig, forKey: .serializeConfig) - } - - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.type = (try? container.decode(String.self, forKey: .type)) == "legacy" ? .legacy : .v0 - self.serialized = try container.decode(TypedArray.self, forKey: .serialized) - self.serializeConfig = try container.decodeIfPresent(SolanaSerializeConfig.self, forKey: .serializeConfig) - } -} - -/// Params for `sol_signMessage`. The message is sent as a string or as bytes. -struct SolanaSignMessageParams: Codable { - enum Message { - case string(String) - case bytes(TypedArray) - } - - let message: Message - - enum CodingKeys: String, CodingKey { - case message - } - - init(message: Message) { - self.message = message - } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - switch message { - case .string(let value): - try container.encode(value, forKey: .message) - case .bytes(let value): - try container.encode(value, forKey: .message) - } - } - - init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - if let value = try? container.decode(String.self, forKey: .message) { - self.message = .string(value) - } else { - self.message = .bytes(try container.decode(TypedArray.self, forKey: .message)) - } - } -} diff --git a/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift b/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift deleted file mode 100644 index ab21bff..0000000 --- a/Sources/MagicSDK/Modules/Solana/SolanaExtension.swift +++ /dev/null @@ -1,124 +0,0 @@ -// -// SolanaExtension.swift -// MagicSDK -// - -import Foundation -import MagicSDK_Web3 -import PromiseKit - -/// Solana extension for signing transactions and messages. -/// Mirrors the `@magic-ext/solana` package in magic-js. -/// -/// magic-js takes `Transaction` and `VersionedTransaction` objects from -/// `@solana/web3.js`. This SDK has no Solana dependency, so it takes the -/// serialized transaction bytes and their `SolanaTransactionType` instead. -/// Serialize a legacy transaction the same way you would pass it to magic-js, -/// usually with `requireAllSignatures: false`. -public class SolanaExtension: MultichainExtension { - - static let chainType = "SOLANA" - - init(rpcProvider: RpcProvider) { - super.init(rpcProvider: rpcProvider, chain: SolanaExtension.chainType) - } - - // MARK: - Sign Transaction - - /// Signs a Solana transaction. - /// - /// - Parameters: - /// - serialized: The serialized transaction. - /// - type: `.legacy` for a `Transaction`, `.v0` for a `VersionedTransaction`. - /// - serializeConfig: The config used to serialize the signed legacy transaction. - /// - response: Completion handler called with the signed transaction or an error. - public func signTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil, response: @escaping Web3ResponseCompletion) { - let request = RPCRequest( - method: SolanaMethod.sol_signTransaction.rawValue, - params: SolanaTransactionParams(type: type, serialized: serialized, serializeConfig: serializeConfig) - ) - self.provider.send(request: request, response: response) - } - - /// Promise-based overload of `signTransaction`. - public func signTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil) -> Promise { - return Promise { resolver in - signTransaction(serialized, type: type, serializeConfig: serializeConfig, response: promiseResolver(resolver)) - } - } - - // MARK: - Partial Sign Transaction - - /// Adds the user's signature to a transaction that other parties also sign. - /// - /// - Parameters: - /// - serialized: The serialized transaction. - /// - type: `.legacy` for a `Transaction`, `.v0` for a `VersionedTransaction`. - /// - serializeConfig: The config used to serialize the signed legacy transaction. - /// - response: Completion handler called with the partly signed transaction or an error. - public func partialSignTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil, response: @escaping Web3ResponseCompletion) { - let request = RPCRequest( - method: SolanaMethod.sol_partialSignTransaction.rawValue, - params: SolanaTransactionParams(type: type, serialized: serialized, serializeConfig: serializeConfig) - ) - self.provider.send(request: request, response: response) - } - - /// Promise-based overload of `partialSignTransaction`. - public func partialSignTransaction(_ serialized: Data, type: SolanaTransactionType, serializeConfig: SolanaSerializeConfig? = nil) -> Promise { - return Promise { resolver in - partialSignTransaction(serialized, type: type, serializeConfig: serializeConfig, response: promiseResolver(resolver)) - } - } - - // MARK: - Sign Message - - /// Signs a UTF-8 message. Resolves with the 64-byte ed25519 signature. - public func signMessage(_ message: String, response: @escaping Web3ResponseCompletion) { - signMessage(.string(message), response: response) - } - - /// Signs raw bytes. Resolves with the 64-byte ed25519 signature. - public func signMessage(_ message: Data, response: @escaping Web3ResponseCompletion) { - signMessage(.bytes(TypedArray(message)), response: response) - } - - /// Promise-based overload of `signMessage` for a UTF-8 message. - public func signMessage(_ message: String) -> Promise { - return Promise { resolver in - signMessage(message, response: promiseResolver(resolver)) - } - } - - /// Promise-based overload of `signMessage` for raw bytes. - public func signMessage(_ message: Data) -> Promise { - return Promise { resolver in - signMessage(message, response: promiseResolver(resolver)) - } - } - - private func signMessage(_ message: SolanaSignMessageParams.Message, response: @escaping Web3ResponseCompletion) { - let request = RPCRequest( - method: SolanaMethod.sol_signMessage.rawValue, - params: SolanaSignMessageParams(message: message) - ) - self.provider.send(request: request) { (result: Web3Response) in - switch result.status { - case let .success(signature): - response(Web3Response(status: .success(signature.data))) - case let .failure(error): - response(Web3Response(error: error)) - } - } - } -} - -// MARK: - Magic extension - -public extension Magic { - /// Access Solana methods. `nil` unless `Magic` was created with a `SolanaConfiguration`. - var solana: SolanaExtension? { - guard extensionConfigurations.contains(where: { $0 is SolanaConfiguration }) else { return nil } - return SolanaExtension(rpcProvider: self.rpcProvider) - } -} diff --git a/Tests/MagicSDKTests/MultichainExtensionTests.swift b/Tests/MagicSDKTests/MultichainExtensionTests.swift index 27dcb62..a4fb698 100644 --- a/Tests/MagicSDKTests/MultichainExtensionTests.swift +++ b/Tests/MagicSDKTests/MultichainExtensionTests.swift @@ -2,6 +2,23 @@ import XCTest import MagicSDK_Web3 @testable import MagicSDK +/// Stands in for an extension package's configuration, such as `SolanaConfiguration`. +private struct TestConfiguration: ExtensionConfiguration { + let name: String + let rpcUrl: String + var chainType: String { name.uppercased() } + var options: [String: String]? + + enum CodingKeys: String, CodingKey { case rpcUrl, chainType, options } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rpcUrl, forKey: .rpcUrl) + try container.encode(chainType, forKey: .chainType) + try container.encodeIfPresent(options, forKey: .options) + } +} + final class MultichainExtensionTests: XCTestCase { private func json(_ value: Encodable) throws -> [String: Any] { @@ -56,8 +73,8 @@ final class MultichainExtensionTests: XCTestCase { apiKey: "pk_test", network: .mainnet, extensions: [ - SolanaConfiguration(rpcUrl: "https://api.devnet.solana.com"), - BitcoinConfiguration(rpcUrl: "https://btc.example.com", network: "testnet"), + TestConfiguration(name: "solana", rpcUrl: "https://api.devnet.solana.com"), + TestConfiguration(name: "bitcoin", rpcUrl: "https://btc.example.com", options: ["network": "testnet"]), ], locale: "en_US" ) @@ -78,73 +95,19 @@ final class MultichainExtensionTests: XCTestCase { func testLaterExtensionWithSameNameWins() throws { let urlBuilder = URLBuilder( apiKey: "pk_test", - extensions: [SolanaConfiguration(rpcUrl: "https://a"), SolanaConfiguration(rpcUrl: "https://b")], + extensions: [TestConfiguration(name: "solana", rpcUrl: "https://a"), TestConfiguration(name: "solana", rpcUrl: "https://b")], locale: "en_US" ) let ext = try XCTUnwrap(try urlParams(urlBuilder)["ext"] as? [String: Any]) XCTAssertEqual((ext["solana"] as? [String: Any])?["rpcUrl"] as? String, "https://b") } - // MARK: - Solana params - - func testSolanaLegacyTransactionParams() throws { - let params = try json(SolanaTransactionParams( - type: .legacy, - serialized: Data([1, 2, 3]), - serializeConfig: SolanaSerializeConfig(requireAllSignatures: false) - )) - XCTAssertEqual(params["type"] as? String, "legacy") - XCTAssertEqual((params["serialized"] as? [String: Any])?["data"] as? String, "1,2,3") - XCTAssertEqual(params["serializeConfig"] as? [String: Bool], ["requireAllSignatures": false]) - } - - func testSolanaVersionedTransactionParams() throws { - let params = try json(SolanaTransactionParams(type: .v0, serialized: Data([4]), serializeConfig: nil)) - XCTAssertEqual(params["type"] as? Int, 0) - XCTAssertNil(params["serializeConfig"]) - } - - func testSolanaSignMessageParams() throws { - XCTAssertEqual(try json(SolanaSignMessageParams(message: .string("hello")))["message"] as? String, "hello") - - let bytes = try json(SolanaSignMessageParams(message: .bytes(TypedArray(Data([7, 8]))))) - XCTAssertEqual((bytes["message"] as? [String: Any])?["data"] as? String, "7,8") - } - - func testSolanaSignedTransactionDecodesMgboxResponse() throws { - let response = #""" - {"rawTransaction":{"constructor":"Buffer","data":"9,8,7","flag":"MAGIC_PAYLOAD_FLAG_TYPED_ARRAY"}, - "signature":[{"signature":null,"publicKey":"11111111111111111111111111111111"}]} - """# - let signed = try JSONDecoder().decode(SolanaSignedTransaction.self, from: Data(response.utf8)) - XCTAssertEqual(signed.rawTransaction, Data([9, 8, 7])) - } - - // MARK: - Bitcoin params - - func testBitcoinTransactionParams() throws { - let params = try json(BitcoinTransactionParams( - inputs: [BitcoinTransactionInput(txid: "abc", txNum: 1, value: 0.0001)], - outputs: [BitcoinTransactionOutput(address: "tb1q", value: 0.00005)] - )) - let input = try XCTUnwrap((params["inputs"] as? [[String: Any]])?.first) - XCTAssertEqual(input["txid"] as? String, "abc") - XCTAssertEqual(input["tx_num"] as? Int, 1) - XCTAssertEqual(input["value"] as? Double, 0.0001) - XCTAssertNil(input["address"]) - XCTAssertNil(input["txNum"]) - - let output = try XCTUnwrap((params["outputs"] as? [[String: Any]])?.first) - XCTAssertEqual(output["address"] as? String, "tb1q") - XCTAssertEqual(output["value"] as? Double, 0.00005) - } - // MARK: - Request shape func testMultichainRequestShape() throws { let request = RPCRequest<[MultichainExtension.ChainParams]>( method: MultichainMethod.magic_get_multichain_public_address.rawValue, - params: [MultichainExtension.ChainParams(chain: SolanaExtension.chainType)] + params: [MultichainExtension.ChainParams(chain: "SOLANA")] ) let encoded = try json(request) XCTAssertEqual(encoded["method"] as? String, "magic_get_multichain_public_address") @@ -152,10 +115,7 @@ final class MultichainExtensionTests: XCTestCase { } func testMethodNamesMatchMagicJs() { - XCTAssertEqual(SolanaMethod.sol_signTransaction.rawValue, "sol_signTransaction") - XCTAssertEqual(SolanaMethod.sol_signMessage.rawValue, "sol_signMessage") - XCTAssertEqual(SolanaMethod.sol_partialSignTransaction.rawValue, "sol_partialSignTransaction") - XCTAssertEqual(BitcoinMethod.btc_signTransaction.rawValue, "btc_signTransaction") + XCTAssertEqual(MultichainMethod.magic_get_multichain_public_address.rawValue, "magic_get_multichain_public_address") XCTAssertEqual(MultichainMethod.magic_reveal_key.rawValue, "magic_reveal_key") } }