diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..81f2ed1 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,23 @@ +name: Build + +on: + pull_request: {} + push: + branches: [ main ] + +permissions: {} + +jobs: + build: + name: Build (iOS Simulator) + runs-on: macos-latest + permissions: + contents: read + steps: + - name: Checkout repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Build all products for the iOS Simulator + run: xcodebuild build -scheme MagicExtensions-Package -destination 'generic/platform=iOS Simulator' diff --git a/MagicExt-OAuth.podspec b/MagicExt-OAuth.podspec deleted file mode 100644 index e2832a6..0000000 --- a/MagicExt-OAuth.podspec +++ /dev/null @@ -1,27 +0,0 @@ -# -# Local Podspec for building local target -# - -Pod::Spec.new do |s| - s.name = 'MagicExt-OAuth' - s.version = '3.0.1' - s.summary = 'Magic IOS Extension - OAuth' - - s.description = <<-DESC -TODO: Add long description of the pod here. - DESC - - s.homepage = 'https://github.com/magicLabs/magic-ios-ext' - s.license = { :type => 'MIT', :file => 'LICENSE' } - s.author = { 'Jerry Liu' => 'jerry@magic.link' } - s.source = { :git => 'https://github.com/magicLabs/magic-ios-ext.git', :tag => s.version.to_s } - s.swift_version = '5.0' - s.ios.deployment_target = '13.0' -# s.osx.deployment_target = '10.15' - - s.source_files = 'Sources/MagicExt-OAuth/**/*' - - s.dependency 'MagicSDK', '~> 10.0' - - s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } -end diff --git a/MagicExt-OIDC.podspec b/MagicExt-OIDC.podspec deleted file mode 100644 index 1c3fa00..0000000 --- a/MagicExt-OIDC.podspec +++ /dev/null @@ -1,27 +0,0 @@ -# -# Local Podspec for building local target -# - -Pod::Spec.new do |s| - s.name = 'MagicExt-OIDC' - s.version = '2.0.2' - s.summary = 'Magic IOS Extension - OIDC' - - s.description = <<-DESC -TODO: Add long description of the pod here. - DESC - - s.homepage = 'https://github.com/magicLabs/magic-ios-ext' - s.license = { :type => 'MIT', :file => 'LICENSE' } - s.author = { 'Jerry Liu' => 'jerry@magic.link' } - s.source = { :git => 'https://github.com/magicLabs/magic-ios-ext.git', :tag => s.version.to_s } - s.swift_version = '5.0' - s.ios.deployment_target = '13.0' -# s.osx.deployment_target = '10.15' - - s.source_files = 'Sources/MagicExt-OIDC/**/*' - - s.dependency 'MagicSDK', '~> 10.0' - - s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } -end diff --git a/Package.swift b/Package.swift index 39fd67a..2a3ad74 100644 --- a/Package.swift +++ b/Package.swift @@ -15,11 +15,14 @@ let package = Package( name: "MagicExt-OAuth", targets: ["MagicExt-OAuth"]), .library( - name: "MagicExt-OIDC", - targets: ["MagicExt-OIDC"]), + name: "MagicExt-Solana", + targets: ["MagicExt-Solana"]), + .library( + name: "MagicExt-Bitcoin", + targets: ["MagicExt-Bitcoin"]), ], dependencies: [ - .package(url: "https://github.com/magiclabs/magic-ios.git", from: "10.1.1") + .package(url: "https://github.com/magiclabs/magic-ios.git", from: "10.4.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -30,7 +33,12 @@ let package = Package( .product(name: "MagicSDK", package: "magic-ios"), ]), .target( - name: "MagicExt-OIDC", + name: "MagicExt-Solana", + dependencies: [ + .product(name: "MagicSDK", package: "magic-ios"), + ]), + .target( + name: "MagicExt-Bitcoin", dependencies: [ .product(name: "MagicSDK", package: "magic-ios"), ]), @@ -38,7 +46,10 @@ let package = Package( name: "MagicExt-OAuthTests", dependencies: ["MagicExt-OAuth"]), .testTarget( - name: "MagicExt-OIDCTests", - dependencies: ["MagicExt-OIDC"]), + name: "MagicExt-SolanaTests", + dependencies: ["MagicExt-Solana"]), + .testTarget( + name: "MagicExt-BitcoinTests", + dependencies: ["MagicExt-Bitcoin"]), ] ) diff --git a/README.md b/README.md index a81795b..88fa28e 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,140 @@ -**We have decided to temporarily archive this repository and place it into maintenance mode. This decision allows us to focus our efforts and resources on advancing our core product line. During this period, active development and the addition of new features will be paused. We value the contributions of the community and appreciate your understanding as we prioritize our main projects. We look forward to resuming development in the future and will keep you updated on any changes.** +# MagicExt -# MagicExt-OAuth -[![CI Status](https://img.shields.io/travis/Ethella/MagicExt-OAuth.svg?style=flat)](https://travis-ci.org/Ethella/MagicExt-OAuth) -[![Version](https://img.shields.io/cocoapods/v/MagicExt-OAuth.svg?style=flat)](https://cocoapods.org/pods/MagicExt-OAuth) -[![License](https://img.shields.io/cocoapods/l/MagicExt-OAuth.svg?style=flat)](https://cocoapods.org/pods/MagicExt-OAuth) -[![Platform](https://img.shields.io/cocoapods/p/MagicExt-OAuth.svg?style=flat)](https://cocoapods.org/pods/MagicExt-OAuth) +Official extensions for the [Magic iOS SDK](https://github.com/magiclabs/magic-ios), shipped as Swift Package Manager products: -Cocoapods ---- -## Set up the local development env -1. To start the demo app with local development SDK, download following projects -```bash -# demo app -$ git clone https://github.com/magiclabs/magic-ios-demo -# ios SDK -$ git clone https://github.com/magiclabs/magic-ios -$ git clone https://github.com/magiclabs/magic-ios-ext +- `MagicExt-Solana` +- `MagicExt-Bitcoin` +- `MagicExt-OAuth` + +Requires iOS 13 or later. CocoaPods is not supported. + +## Solana and Bitcoin + +Solana and Bitcoin work like the `@magic-ext/solana` and `@magic-ext/bitcoin` packages in magic-js. They need [magic-ios](https://github.com/magiclabs/magic-ios) 10.4.0 or later, which has `Magic(apiKey:extensions:)`. + +Add the package with Swift Package Manager, then add the products you need to your target: `MagicExt-Solana`, `MagicExt-Bitcoin`, or both. + +```swift +.package(url: "https://github.com/magiclabs/magic-ios-ext.git", from: "X.Y.Z") // the first release with MagicExt-Solana and MagicExt-Bitcoin ``` -2. To enable the demo use the local development SDK. Navigate to `magic-ios-demo/Podfile` and edit the following lines. - This will make pod file install local dependencies instead of the ones distributed. +Turn them on by passing a configuration when you create `Magic`: + +```swift +import MagicSDK +import MagicExt_Solana +import MagicExt_Bitcoin -```ruby -# Distributed Library on Cocoapods -# pod 'MagicSDK', '~> 3.0' -# pod 'MagicExt-OAuth', '~> 1.0' - -# Local development library -pod 'MagicSDK', :path => '../magic-ios/MagicSDK.podspec' -pod 'MagicExt-OAuth', :path => '../magic-ios-ext/MagicExt-OAuth.podspec' +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") + ] +) ``` -```bash -$ cd /YOUR/PATH/TO/magic-ios-demo +`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 -# Install dependencies -$ pod install +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) + } +} ``` -3. Open `/YOUR/PATH/TO/magic-ios-demo/magic-ios-demo.xcworkspace` with XCode and try it out! +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. --- +## Develop locally + +Clone the SDK, this repo and the demo app side by side: + +```bash +git clone https://github.com/magiclabs/magic-ios +git clone https://github.com/magiclabs/magic-ios-ext +git clone https://github.com/magiclabs/magic-ios-demo +``` + +Open `magic-ios-demo/magic-ios-spm-demo.xcodeproj`. It uses the local `magic-ios` and `magic-ios-ext` folders, so your changes show up in the demo. If Xcode says a package product is missing, run File > Packages > Resolve Package Versions. diff --git a/Sources/MagicExt-Bitcoin/BitcoinConfiguration.swift b/Sources/MagicExt-Bitcoin/BitcoinConfiguration.swift new file mode 100644 index 0000000..f27e438 --- /dev/null +++ b/Sources/MagicExt-Bitcoin/BitcoinConfiguration.swift @@ -0,0 +1,87 @@ +// +// BitcoinConfiguration.swift +// MagicSDK +// + +import Foundation +import MagicSDK + +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/MagicExt-Bitcoin/BitcoinExtension.swift b/Sources/MagicExt-Bitcoin/BitcoinExtension.swift new file mode 100644 index 0000000..ba46b5f --- /dev/null +++ b/Sources/MagicExt-Bitcoin/BitcoinExtension.swift @@ -0,0 +1,61 @@ +// +// BitcoinExtension.swift +// MagicSDK +// + +import Foundation +import MagicSDK +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/MagicExt-OIDC/Core/OIDCExtension.swift b/Sources/MagicExt-OIDC/Core/OIDCExtension.swift deleted file mode 100644 index 0a70f72..0000000 --- a/Sources/MagicExt-OIDC/Core/OIDCExtension.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// OIDCExtension.swift -// MagicSDK -// -// Created by Jerry Liu on 10/16/22. -// - -import Foundation -import MagicSDK_Web3 -import MagicSDK - -public class OIDCExtension: BaseModule { - - public func loginWithOIDC (_ configuration: OpenIdConfiguration, response: @escaping Web3ResponseCompletion ) { - let request = RPCRequest<[OpenIdConfiguration]>(method: OIDCMethod.magic_auth_login_with_oidc.rawValue, params: [configuration]) - self.provider.send(request: request, response: response) - } -} - -extension Magic { - - public var openid: OIDCExtension { - print("\(self.MA_EXTENSION_ONLY_MSG)") - return OIDCExtension(rpcProvider: self.rpcProvider) - } -} diff --git a/Sources/MagicExt-OIDC/Types/OIDCMethod.swift b/Sources/MagicExt-OIDC/Types/OIDCMethod.swift deleted file mode 100644 index 79ba730..0000000 --- a/Sources/MagicExt-OIDC/Types/OIDCMethod.swift +++ /dev/null @@ -1,11 +0,0 @@ -// -// OIDCMethod.swift -// -// -// Created by Jerry Liu on 10/17/22. -// - -import Foundation -internal enum OIDCMethod: String, CaseIterable { - case magic_auth_login_with_oidc -} diff --git a/Sources/MagicExt-OIDC/Types/OpenIdConfiguration.swift b/Sources/MagicExt-OIDC/Types/OpenIdConfiguration.swift deleted file mode 100644 index de9361b..0000000 --- a/Sources/MagicExt-OIDC/Types/OpenIdConfiguration.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// OpenIdConfiguration.swift -// -// -// Created by Jerry Liu on 10/17/22. -// - -import Foundation -import MagicSDK - -public struct OpenIdConfiguration: BaseConfiguration { - public var jwt: String - public var providerId: String - - public init(jwt: String, providerId: String) { - self.jwt = jwt - self.providerId = providerId - } -} diff --git a/Sources/MagicExt-Solana/SolanaConfiguration.swift b/Sources/MagicExt-Solana/SolanaConfiguration.swift new file mode 100644 index 0000000..e47d8de --- /dev/null +++ b/Sources/MagicExt-Solana/SolanaConfiguration.swift @@ -0,0 +1,147 @@ +// +// SolanaConfiguration.swift +// MagicSDK +// + +import Foundation +import MagicSDK + +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/MagicExt-Solana/SolanaExtension.swift b/Sources/MagicExt-Solana/SolanaExtension.swift new file mode 100644 index 0000000..6561c27 --- /dev/null +++ b/Sources/MagicExt-Solana/SolanaExtension.swift @@ -0,0 +1,125 @@ +// +// SolanaExtension.swift +// MagicSDK +// + +import Foundation +import MagicSDK +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/MagicExt-BitcoinTests/BitcoinExtensionTests.swift b/Tests/MagicExt-BitcoinTests/BitcoinExtensionTests.swift new file mode 100644 index 0000000..28f2c48 --- /dev/null +++ b/Tests/MagicExt-BitcoinTests/BitcoinExtensionTests.swift @@ -0,0 +1,51 @@ +import XCTest +import MagicSDK +@testable import MagicExt_Bitcoin + +final class BitcoinExtensionTests: 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]) + } + + func testConfigurationEncodesNetworkUnderOptions() throws { + let configuration = BitcoinConfiguration(rpcUrl: "https://btc.example.com", network: "testnet") + XCTAssertEqual(configuration.name, "bitcoin") + let encoded = try json(configuration) + XCTAssertEqual(encoded.count, 3) + XCTAssertEqual(encoded["rpcUrl"] as? String, "https://btc.example.com") + XCTAssertEqual(encoded["chainType"] as? String, "BITCOIN") + XCTAssertEqual(encoded["options"] as? [String: String], ["network": "testnet"]) + } + + func testTransactionParams() 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) + } + + func testMethodNameMatchesMagicJs() { + XCTAssertEqual(BitcoinMethod.btc_signTransaction.rawValue, "btc_signTransaction") + } + + func testBitcoinIsOnlyAvailableWhenConfigured() { + XCTAssertNotNil(Magic(apiKey: "pk_test", extensions: [BitcoinConfiguration(rpcUrl: "https://a", network: "testnet")]).bitcoin) + XCTAssertNil(Magic(apiKey: "pk_test").bitcoin) + } +} diff --git a/Tests/MagicExt-OIDCTests/MagicExt_OIDCTests.swift b/Tests/MagicExt-OIDCTests/MagicExt_OIDCTests.swift deleted file mode 100644 index 69c320c..0000000 --- a/Tests/MagicExt-OIDCTests/MagicExt_OIDCTests.swift +++ /dev/null @@ -1,7 +0,0 @@ -import XCTest -@testable import MagicExt_OIDC - -final class MagicExt_OIDCTests: XCTestCase { - func testExample() throws { - } -} diff --git a/Tests/MagicExt-SolanaTests/SolanaExtensionTests.swift b/Tests/MagicExt-SolanaTests/SolanaExtensionTests.swift new file mode 100644 index 0000000..e34093b --- /dev/null +++ b/Tests/MagicExt-SolanaTests/SolanaExtensionTests.swift @@ -0,0 +1,68 @@ +import XCTest +import MagicSDK +@testable import MagicExt_Solana + +final class SolanaExtensionTests: 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]) + } + + func testConfigurationEncodesRpcUrlAndChainType() throws { + let configuration = SolanaConfiguration(rpcUrl: "https://api.devnet.solana.com") + XCTAssertEqual(configuration.name, "solana") + let encoded = try json(configuration) + XCTAssertEqual(encoded.count, 2) + XCTAssertEqual(encoded["rpcUrl"] as? String, "https://api.devnet.solana.com") + XCTAssertEqual(encoded["chainType"] as? String, "SOLANA") + } + + func testLegacyTransactionParams() 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 testVersionedTransactionParams() throws { + let params = try json(SolanaTransactionParams(type: .v0, serialized: Data([4]), serializeConfig: nil)) + XCTAssertEqual(params["type"] as? Int, 0) + XCTAssertNil(params["serializeConfig"]) + } + + func testSignMessageParams() 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 testSignedTransactionDecodesMgboxResponse() 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])) + } + + func testMethodNamesMatchMagicJs() { + XCTAssertEqual(SolanaMethod.sol_signTransaction.rawValue, "sol_signTransaction") + XCTAssertEqual(SolanaMethod.sol_signMessage.rawValue, "sol_signMessage") + XCTAssertEqual(SolanaMethod.sol_partialSignTransaction.rawValue, "sol_partialSignTransaction") + } + + func testSolanaIsOnlyAvailableWhenConfigured() { + XCTAssertNotNil(Magic(apiKey: "pk_test", extensions: [SolanaConfiguration(rpcUrl: "https://a")]).solana) + XCTAssertNil(Magic(apiKey: "pk_test").solana) + } +}