Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -15,12 +16,24 @@ 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")
]
```

## Quick start

```swift
import MagicSDK

Magic.shared = Magic(apiKey: "YOUR_PUBLISHABLE_API_KEY")
```

## Solana and Bitcoin

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

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`.

---
20 changes: 13 additions & 7 deletions Sources/MagicSDK/Core/Magic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ public class Magic: NSObject {
// MARK: - Property
public var rpcProvider: RpcProvider

/// 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!

Expand All @@ -33,20 +37,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` 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)
}

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)
Expand Down
56 changes: 56 additions & 0 deletions Sources/MagicSDK/Core/Relayer/Types/TypedArray.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
12 changes: 9 additions & 3 deletions Sources/MagicSDK/Core/Relayer/URLBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
)
Expand All @@ -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 {
Expand All @@ -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)
}
}
}
}
Expand Down
17 changes: 12 additions & 5 deletions Sources/MagicSDK/Core/Relayer/WebViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,23 +202,30 @@ 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),
let jsonString = String(data: json, encoding: .utf8) else {
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() {
Expand Down
41 changes: 41 additions & 0 deletions Sources/MagicSDK/Modules/Extension/ExtensionConfiguration.swift
Original file line number Diff line number Diff line change
@@ -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.<name>` 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 `{ "<name>": <config>, ... }`.
/// 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)))
}
}
}
66 changes: 66 additions & 0 deletions Sources/MagicSDK/Modules/Multichain/MultichainExtension.swift
Original file line number Diff line number Diff line change
@@ -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, 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

public 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<String>) {
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<String> {
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<Bool>) {
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<Bool> {
return Promise { resolver in
revealPrivateKey(response: promiseResolver(resolver))
}
}
}
Loading
Loading