From 9f783112759bc9ccb2d13e3a0bbdc75da7791d12 Mon Sep 17 00:00:00 2001 From: AyushBherwani1998 Date: Mon, 15 Apr 2024 17:01:18 +0530 Subject: [PATCH 1/6] initial commit --- .../mpc-core-kit-ios/authentication.mdx | 183 ++++++++++++ .../core-kit/mpc-core-kit-ios/initialize.mdx | 105 +++++++ .../sdk/core-kit/mpc-core-kit-ios/install.mdx | 47 ++++ .../mpc-core-kit-ios/mpc-core-kit-ios.mdx | 159 +++++++++++ docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx | 263 ++++++++++++++++++ sidebars.ts | 21 ++ 6 files changed, 778 insertions(+) create mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx create mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx create mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/install.mdx create mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx create mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx new file mode 100644 index 000000000..ce94e5249 --- /dev/null +++ b/docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx @@ -0,0 +1,183 @@ +--- +title: "Authentication in MPC Core Kit iOS SDK" +sidebar_label: "Authentication" +displayed_sidebar: sdk +description: "Web3Auth MPC Core Kit iOS SDK - Authentication | Documentation - Web3Auth" +--- + +import ServiceWorkerCode from "@site/src/common/sdk/core-kit/tkey/_sw-js.mdx"; +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +There are two ways to login your users, depending on the type of authentication method you've +chosen. If you are looking for an Authentication Flow in your application (like Auth0 SPA Flow), you +can use the `loginWithOAuth()` function. If you are looking to pass a JWT-based IdToken to the SDK +from your application (like Auth0 RWA Flow or even BYOA JWT provider), you can use the +`loginWithJWT()` function. + +As a prerequisite, before triggering the login function, you need to create a verifier for your +login method on the [Web3Auth Dashboard](https://dashboard.web3auth.io). + +## Creating a Verifier + +Since this is a Core Kit SDK, it does not provide any default authentication methods. You need to +create a custom verifier to use this SDK. This means that you need to authenticate users with your +own custom authentication service. For example, while authenticating with Google, you have to use +your own Google Client ID and Dashboard to authenticate users directly or use aggregate services +like Auth0, Firebase, AWS Cognito etc. Additionally, you can make your own JWT token authentication +system and pass over the ID Token to Web3Auth to generate a private key for them. + +For enabling this, you need [Create a Verifier](/auth-provider-setup/verifiers) from the **Custom +Auth** section of the [Web3Auth Developer Dashboard](https://dashboard.web3auth.io) with your +desired configuration. + +:::tip + +If you want to know more about setting up a verifier and how to use it, please refer to the +[Custom Authentication Documentation](/features/custom-authentication). + +::: + +:::warning + +Core Kit SDK only supports Sapphire Mainnet and Devnet networks. The other networks don't support +MPC functionalities. + +::: + +## Log In with OAuth + +If you wish to have SPA flow, similar to Auth0, you can use `loginWithOAuth` function. + +### Usage + +```swift +let result = try await mpcCoreKit.loginWithOAuth( + loginProvider: .google, + clientId: "Your Google Client id", + verifier: "Your Custom Verifier name" +); +``` + +### Arguements + +| Variable | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `loginProvider` | Defines the login provider to be used. Supported values are `LoginProviders.google`, `LoginProviders.facebook`, `LoginProviders.twitch`, `LoginProviders.reddit`, `LoginProviders.discord`, `LoginProviders.apple`, `LoginProviders.github`, `LoginProviders.linkedin`, `LoginProviders.kakao`, `LoginProviders.twitter`, `LoginProviders.weibo`, `LoginProviders.line`, `LoginProviders.wechat`, `LoginProviders.email_password`, `LoginProviders.jwt` | +| `clientId` | Client id for respective `loginProvider`. For instance google client id, auth0 client id, and etc. | +| `verifier` | Verifier name from the Web3Auth Dashboard. | +| `jwtParams` | JWT parameters. It takes `[Stirng: Stirng]` as an input. The default value is `[:]`. | +| `redirectURL` | | +| `browserRedirectURL` | | + +### Result + +The `loginWith0Auth`returns `MpcKeyDetails` upon success, which has infomration regarding +thresholds, required factors, and etc. + + + + + +| Parameter | Description | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tssPubKey` | It holds the value for the TSS PubKey in compressed form. The type of `tssPubKey` is `String`. | +| `metadataPubKey` | It holds the value for metadata PubKey which is used for interacting with metadata layer. | +| `requiredFactors` | It defines the total factors still required for SDK to be in write mode. If required factors are greater than 0, the SDK will be in read mode. You can use `inputFactor` function to input factor and refresh the instance. | +| `threshold` | Defines the threshold set by the SDK. Ideally it would be 2. | +| `total_shares` | Defines the total number of shares for user. Initially if the hashed cloud factor is set, it would be 2. | + + + + +```swift +public struct MpcKeyDetails : Codable { + public let tssPubKey : String + public let metadataPubKey: String + public let requiredFactors: Int32 + public let threshold: UInt32 + public let shareDescriptions : String + public let total_shares: UInt32 +} +``` + + + +## Log In with JWT (BYOA) + +If you are looking to pass a JWT-based IdToken to the SDK from your application, you can use the +`loginWithJWT()` function. + +### Usage + +```swift +let result = try await mpcCoreKit.loginWithJwt( + verifier: "Your verifier name from Web3Auth Dashboard", + verifierId: "Your verifierd Id value", + idToken: "Your JWT id Token" +) +``` + +### Arguements + +| Argument | Description | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------- | +| `verifier` | Your verifier name from Web3Auth dashboard. | +| `verifierId` | Your verifier id value, i.e. email, sub or custom. Make sure you have selected correct verifier id while creating the custom verifier. | +| `idToken` | Your JWT id token for verification. | + +### Result + +The `loginWithJWT`returns `MpcKeyDetails` upon success, which has infomration regarding thresholds, +required factors, and etc. + + + + + +| Parameter | Description | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tssPubKey` | It holds the value for the TSS PubKey in compressed form. The type of `tssPubKey` is `String`. | +| `metadataPubKey` | It holds the value for metadata PubKey which is used for interacting with metadata layer. | +| `requiredFactors` | It defines the total factors still required for SDK to be in write mode. If required factors are greater than 0, the SDK will be in read mode. You can use `inputFactor` function to input factor and refresh the instance. | +| `threshold` | Defines the threshold set by the SDK. Ideally it would be 2. | +| `total_shares` | Defines the total number of shares for user. Initially if the hashed cloud factor is set, it would be 2. | + + + + +```swift +public struct MpcKeyDetails : Codable { + public let tssPubKey : String + public let metadataPubKey: String + public let requiredFactors: Int32 + public let threshold: UInt32 + public let shareDescriptions : String + public let total_shares: UInt32 +} +``` + + + +## Logging out the User + +To disconnect user's connected wallet/ provider and log them out of the Web3Auth MPC Core Kit SDK +you can use `logout` function. + +### Usage + +```swift +try await mpcCoreKit.logout(); +``` diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx new file mode 100644 index 000000000..e6d171d9b --- /dev/null +++ b/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx @@ -0,0 +1,105 @@ +--- +title: "Initializing MPC Core Kit iOS SDK" +sidebar_label: "Initialize" +displayed_sidebar: sdk +description: "Web3Auth MPC Core Kit iOS SDK - Initialize | Documentation - Web3Auth" +--- + +import ChainConfig from "@site/src/common/sdk/pnp/web/_chain-config.mdx"; +import Web3AuthOptions from "@site/src/common/sdk/pnp/web/_web3authcore-options.mdx"; +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +After Installation, the next step to use Web3Auth MPC Core Kit iOS is to initialize the SDK. + +## Instantiating MpcCoreKit + +### Creating a class to conform ILocalStorage + +MpcCoreKit takes `ILocalStorage` as an input parameter. The package uses it to store and retrieve +the device factor. `ILocalStorage` being a `protocol` gives us the freedom to choose the local +storage of our choice. + +Here we are using `UserDefaults`, but you can choose the storage of your choice. + +```swift +import Foundation +import mpc_core_kit_swift + +class UserStorage : ILocalStorage { + func get(key: String) async throws -> Data { + guard let data = UserDefaults().value(forKey: key) as? Data else { + return Data() + } + return data + } + + func set(key: String, payload: Data) async throws { + UserDefaults().setValue(payload, forKey: key) + } +} + +let storage = UserStorage() +``` + +### Creating MpcCoreKit instance + +Once, we have created a class to conform `ILocalStorage` we are good to create an instance of +`MpcCoreKit`. If you want to disable the hashed cloud factor, you can set `disableHashFactor` to +true during the initialization. + +```swift + let mpcCoreKit = MpcCoreKit( + web3AuthClientId: "Your Web3Auth Client ID" // Get it from Web3Auth Dashboard, + web3AuthNetwork: .SAPPHIRE_MAINNET, + localStorage: UserStorage() +) +``` + +#### Arguments + + + + + +| Parameter | Description | +| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `web3AuthClientId` | Your Web3Auth Client Id from [Web3Auth Dashboard](https://dashboard.web3auth.io/). | +| `web3AuthNetwork` | The Web3auth network to be used for MPC Wallet Management. Supported values are `Web3AuthNetwork.SAPPHIRE_MAINNET`, `Web3AuthNetwork.SAPPHIRE_DEVNET`, `Web3AuthNetwork.MAINNET`, `Web3AuthNetwork.TESTNET`, `Web3AuthNetwork.CYAN`, `Web3AuthNetwork.AQUA` | +| `disableHashFactor` | Defines whether to use hashed cloud factor or not. Default value is `false`. | +| `localStorage` | A class which conforms to `ILocalStorage`. Used by the SDK internally to store and retrieve device share. | + + + + + +```swift +public struct MpcCoreKit { + public init(web3AuthClientId : String , web3AuthNetwork: Web3AuthNetwork, disableHashFactor : Bool = false, localStorage: ILocalStorage ) { + self.option = .init(disableHashFactor: disableHashFactor , Web3AuthClientId: web3AuthClientId, network: web3AuthNetwork) + self.appState = CoreKitAppState.init() + + self.network = web3AuthNetwork + + self.torusUtils = TorusUtils( + enableOneKey: true, + network: self.network.toTorusNetwork(), + clientId: web3AuthClientId + ) + + self.nodeDetailsManager = NodeDetailManager(network: self.network.toTorusNetwork()) + + self.coreKitStorage = .init(storeKey: self.storeKey, storage: localStorage) + + } +} +``` + + + diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx new file mode 100644 index 000000000..0a6e94981 --- /dev/null +++ b/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx @@ -0,0 +1,47 @@ +--- +title: "Installing MPC Core Kit iOS SDK" +sidebar_label: "Install" +displayed_sidebar: sdk +description: "Web3Auth MPC Core Kit iOS SDK - Install | Documentation - Web3Auth" +--- + +## MPC Core Kit iOS + +This package helps you implement the Web3Auth MPC Features while giving you the flexibility to +customize the UI and UX of the authentication process. + +#### Swift Package Manager + +1. In Xcode, with your app project open, navigate to **File > Add Packages**. + +2. When prompted, add the tKey iOS SDK repository: + + ```sh + https://github.com/Web3Auth/mpc-core-kit-swift + ``` + + From the `Dependency Rule` dropdown, select `Exact Version` and enter `1.0.0` as the version. + +3. When finished, Xcode will automatically begin resolving and downloading your dependencies in the + background. + +## Web3 Swift MPC Provider + +This package gives access to tss signing capabilities to be used with mpc-core-kit-swift. This comes +in handy by providing you with a standard way of retriving user's address and interacting with +blockchain. As of now, it only supports Ethereum. + +#### Swift Package Manager + +1. In Xcode, with your app project open, navigate to **File > Add Packages**. + +2. When prompted, add the tKey iOS SDK repository: + + ```sh + https://github.com/tkey/web3-swift-mpc-provider + ``` + + From the `Dependency Rule` dropdown, select `Exact Version` and enter `1.0.0` as the version. + +3. When finished, Xcode will automatically begin resolving and downloading your dependencies in the + background. diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx new file mode 100644 index 000000000..1f061cb75 --- /dev/null +++ b/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx @@ -0,0 +1,159 @@ +--- +title: "Web3Auth MPC Core Kit iOS SDK" +displayed_sidebar: sdk +sidebar_label: Overview +description: "Web3Auth MPC Core Kit iOS SDK | Documentation - Web3Auth" +--- + +import Image1 from "@site/static/images/tkey-mpc-flow.png"; + +Web3Auth's [mpc-core-kit-swift](https://github.com/Web3Auth/mpc-core-kit) SDK is simple and +easy-to-use SDK, which helps you implement the Web3Auth MPC Features while giving you the +flexibility to customize the UI and UX of the authentication process. + +## This Documentation is based on [`1.0.0`](https://github.com/Web3Auth/mpc-core-kit-swift/releases) SDK Version. + +## Requirements + +- iOS 14+ +- Xcode 11.4+ / 12.x +- Swift 4.x / 5.x + +:::note + +The minimum [pricing plan](https://web3auth.io/pricing.html) to use this SDK in a production +environment is the **Enterprise Plan**. However, you can use this SDK with all features enabled in +the development environment for free. + +::: + +## Web3Auth MPC Infrastructure Components + +With the Web3Auth infrastructure, your key is divided into multiple parts and stored across your +devices and our Auth Network. This ensures that your key is always available and never stored in a +single place. While in the traditional Web3Auth SDK, your key was dynamically reconstructed in the +frontend using threshold signatures, with the new Web3Auth MPC (Multi Party Computation) +architecture, it is **never reconstructed**. Instead, these partial keys are stored across different +locations, and your device is used to make partial signatures for your message/ transaction. These +are finally returned to the frontend where using TSS (Threshold Signature Scheme), these signatures +are combined to make a final signature. You can use this finally signed message/transaction to make +a transaction on the blockchain. + +The Threshold Signature Scheme (TSS) is a cryptographic primitive for distributed key generation and +signing. The use of TSS in Web3Auth's Auth network is a new paradigm that can provide numerous +benefits, especially in terms of security. + +Web3Auth Wallet Management + +As you can notice in this diagram above, the final output, i.e., the User's TSS Account, is +generated in multiple stages within the infrastructure. Since this is a TSS- MPC based +infrastructure, you don't get back a private key, but signatures that can be used to make +transactions on the blockchain. Let's understand each of these stages in detail. + +### Factors + +#### Social Login Factor + +This is the primary way for a user to access their account. This step involves authentication using +a user's preferred social login provider. The idToken received from the social login provider here +is passed to the Web3Auth Auth Network to generate the TSS Shares in the Nodes. By default, these +nodes have a threshold of 3/5 that can be customized according to requirements. When a user logs in, +the Auth Network generates signatures corresponding to the TSS Shares in the nodes and returns them +to the user's end. These signatures are then used alongside other shares to generate the final TSS +Account signatures. + +#### Device Factor (`index:2`) + +This is the second factor used to access the user's account. This step involves the generation of a +TSS Share on the user's device and using that to generate a final signature for the TSS Account +alongside the social login factor. This ensures the user logs in using their trusted device and +maintains a proper non-custodial setup. + +#### Backup Factor (`index:3`) + +A user has a choice to generate as many backup factors as needed to access their account. This step +involves the generation of a TSS Share on the user's end and storing them in whichever location they +prefer. This share can be used similarly to the device share to generate a final signature for the +TSS Account alongside the social login and/or device factors. + +### Threshold + +The threshold is the minimum number of shares required to generate a final signature for the TSS +Account. This threshold, by default, is set to 3/5 on the Auth Network and 2/3 for the user's device +front. This ensures high availability and ease of access on both ends alongside optimum security. +Both these thresholds can be customized according to the requirements. + +### Components of a Factor + +#### TSS Shares + +The TSS Shares are the main component needed for the generation of the final working signature of +the user. These shares are generated using distributed key generation and are stored in the Auth +Network and the user's device. Since these shares are generated using MPC, they are **never +reconstructed** and always stay decentralized and secure. + +#### Metadata Key & Shares + +The Metadata Key closely mimics the storage of the TSS Shares. The only difference is that the +metadata key is always reconstructed and used for its encryption/decryption capabilities. It +utilizes basic Shamir's Secret Sharing and is initially generated on a user's front end. The +metadata key is utilized for the encryption/decryption of the user metadata stored in the Web3Auth +Metadata Server. + +One metadata share gives you the **read** access to the metadata server, while two or more (as the +threshold is reached) give you the **write** access. + +#### Factor Keys + +To enable refresh, deletion, and rotational capabilities on the `tssKey`, we also introduce +**factorKeys**. Factor Keys are randomly generated keys unique to each factor-generated user's +device and backups, like users' phones, chrome extensions, on their cloud, assisting third parties, +etc. + +As share to the TSS Key and/or Metadata Key may rotate, Factor Keys allow a consistent secret to be +saved in these different locations. + +## Understanding the MPC Core Kit SDK Flow + +By default, for a new user, the MPC Core Kit SDK starts in a 2/2 flow. This means that the user will +have to generate a social login factor and a hashed cloud factor. This hashed cloud factor is +derived on the SDK front end and stored in the encrypted metadata server. This enables the user to +start the login process from any device without creating an MFA factor. + +This is done to make sure the user can access their account from any device without having to +generate a new factor. However, this makes the initial onboarding, semi-custodial. To make the +onboarding completely non-custodial, the user can use the `enableMfa` feature to generate a device +and backup factor and delete the hashed cloud factor. This makes the user's account completely +non-custodial in 2/3 setup and enables them to access their account from any device using the backup +share. Device share is saved on a trusted device and can be used to access the account from that +device seamlessly without having to generate a new factor. + +## Resources + +- [Quick Start](https://github.com/Web3Auth/web3auth-core-kit-examples/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): + Get Started with an easy to follow integration of Web3Auth + +- [Example Applications](https://github.com/Web3Auth/web3auth-core-kit-examples/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): + Explore our example applications and try the SDK yourself. + +- [Troubleshooting](/troubleshooting): Find quick solutions to common issues faced by developers. + +- [Source Code](https://github.com/web3auth/mpc-core-kit-swift): Web3Auth is open sourced. You can + find the source code on our GitHub repository. + +- [Community Support Portal](https://web3auth.io/community): Join our community to get support from + our team and other developers. + +## Helper SDKs + +### Web3 Provider + +#### [web3-swift-mpc-provider](https://github.com/tkey/web3-swift-mpc-provider) + +This package gives access to tss signing capabilities to be used with mpc-core-kit-swift. This comes +in handy by providing you with a standard way of retriving user's address and interacting with +blockchain. As of now, it only supports Ethereum. diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx new file mode 100644 index 000000000..1a10daf2d --- /dev/null +++ b/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx @@ -0,0 +1,263 @@ +--- +title: "Usage of MPC Core Kit iOS SDK" +sidebar_label: "Usage" +displayed_sidebar: sdk +description: "Web3Auth MPC Core Kit iOS SDK - Usage | Documentation - Web3Auth" +--- + +Once you've installed and successfully initialized `MpcCoreKit`, you can use it to authenticate your +users. Further, you can use the Web3 Swift provider given by Web3Auth to sign transactions and +interact with the blockchain. + +## Authentication Functions + +--- + +### [loginWithOAuth()](./authentication#log-in-with-oauth) + +If you are looking for an Authentication Flow in your application (like Auth0 SPA Flow), you can use +the `loginWithOAuth()` function. + +#### Usage + +```swift +let result = try await mpcCoreKit.loginWithOAuth( + loginProvider: .google, + clientId: "Your Google Client id", + verifier: "Your Custom Verifier name" +); +``` + +### [loginWithJWT()](./authentication#log-in-with-jwt-byoa) + +If you are looking to pass a JWT-based IdToken to the SDK from your application, you can use the +`loginWithJWT()` function. + +#### Usage + +```swift +let result = try await mpcCoreKit.loginWithJwt( + verifier: "Your verifier name from Web3Auth Dashboard", + verifierId: "Your verifierd Id value", + idToken: "Your JWT id Token" +) +``` + +### inputFactorKey() + +Inputs the Factor Key into the SDK. This function is used to recover the User's account using the +Factor Key. If the factor key is correct, the SDK initializes the User's account and logs them in. + +If you want to change the current active factor key in the current state of the SDK, you can use +this function. + +#### Usage + +```swift +try await mpcCoreKit.inputFactor( + factorKey: factorKey +) +``` + +### [logout()](./authentication#logging-out-the-user) + +Logs out the User. + +#### Usage + +```swift +try await mpcCoreKit.logout(); +``` + +## Factor Handling Functions + +--- + +### enableMFA() + +Enables MFA for the user. It creates a device factor and stores it in the local storage. It also +creates a backup factor and returns it to the user. You can also pass a factor key that can be used +for the backup factor. If you don't pass a factor key, a new factor key will be generated. To pass +the factor key you can use `enableMFA` arguement. + +Most importantly, this function deletes the Hashed Factor Key enabling a non-custodial flow. + +#### Usage + +```swift +let factor = try await mpcCoreKit.enableMFA(); +``` + +#### Arguments + +| Argument | Description | +| ---------------- | ------------------------------------------------------------------------------------------------------------------- | +| `enableMFA` | If you wish to set a custom factor key, you can use `enableMFA` argument. By default, SDK will handle this for you. | +| `recoveryFactor` | Defines whether to create recovery factor along with device factor. Default value is `true`. | + +#### `enableMFARecoveryFactor` struct + +```swift +public struct enableMFARecoveryFactor { + public var factorKey: String? + public var factorTypeDescription: FactorDescriptionTypeModule + public var additionalMetadata: [String:Any] + + public init(factorKey: String? = nil, factorTypeDescription: FactorDescriptionTypeModule = .Other, additionalMetadata: [String : Any] = [:]) { + self.factorKey = factorKey + self.factorTypeDescription = factorTypeDescription + self.additionalMetadata = additionalMetadata + } +} + +public enum FactorDescriptionTypeModule { + case HashedShare + case SecurityQuestions + case DeviceShare + case SeedPhrase + case PasswordShare + case SocialShare + case Other + + public func toString () -> String { + switch self { + + case .HashedShare: return "hashedShare" + case .SecurityQuestions: return "tssSecurityQuestions" + case .DeviceShare: return "deviceShare" + case .SeedPhrase: return "seedPhrase" + case .PasswordShare: return "passwordShare" + case .SocialShare: return "socialShare" + case .Other: return "Other" + } + } +} +``` + +### createFactor() + +A low-level function, helps you to create a backup factor key based on the type of TSS Share you +want to create. You can pass your own factor key or let the SDK generate one for you. + +#### Usage + +```swift +let factor = try await mpcCoreKit.createFactor( + tssShareIndex: .DEVICE, + factorKey: nil, + factorDescription: .DeviceShare +) +``` + +#### Arguments + +| Argument | Description | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tssShareIndex` | Defines the index of share. It can be either 2, or 3. You can use `TssShareType` to set the share index. | +| `factorKey?` | If you wish to pass the custom factor key for creation of factor, you can use `factorKey`. If value is nil, and SDK will internally create a new factory key for you. | +| `factorDescription` | Defines which type of share you are using as a factor. Checkout `FactorDescriptionTypeModule` for available options. | +| `additionalMetadata` | If you wish to store any additional meta data on metadata layer, you can pass it using `additionalMetadata`. It takes `[String: Any]` as a value. The default value is `[:]`. | + +#### Interfaces + +```swift + +public enum TssShareType { + case DEVICE + case RECOVERY + + public func toInt32 () -> Int32 { + switch self { + + case .DEVICE: return 2 + case .RECOVERY: return 3 + } + } + public func toString () -> String { + switch self { + + case .DEVICE: return "2" + case .RECOVERY: return "3" + } + } +} + +public enum FactorDescriptionTypeModule { + case HashedShare + case SecurityQuestions + case DeviceShare + case SeedPhrase + case PasswordShare + case SocialShare + case Other + + public func toString () -> String { + switch self { + + case .HashedShare: return "hashedShare" + case .SecurityQuestions: return "tssSecurityQuestions" + case .DeviceShare: return "deviceShare" + case .SeedPhrase: return "seedPhrase" + case .PasswordShare: return "passwordShare" + case .SocialShare: return "socialShare" + case .Other: return "Other" + } + } +} +``` + +### deleteFactor() + +Deletes the Factor, respective to the factorPub provided for the User's account. You can get the +factor Pubs by using the `getAllFactorPubs()` function. + +It will throw an error if you try to delete the factor that is currently active within the state of +the SDK. Use the `inputFactorKey()` function to change the factor key in the current state of the +SDK to be able to delete that factor. + +#### Usage + +```swift +try await mpcCoreKit.deleteFactor(deleteFactorPub: "Factor's PubKey") +``` + +#### Arguments + +| Argument | Description | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `deleteFactorPub` | The PubKey for the factor key you want to delete. The SDK internally will retrieve the corresponding factory key and delete it. | +| `factorKey?` | The factorKey you want to delete. The default value is `nil`. | + +### getCurrentFactorKey() + +Returns the current factor key in usage within the state of the SDK. + +#### Usage + +```swift +let factorKey = try mpcCoreKit.getCurrentFactorKey(); +``` + +## Mnemonic Conversations + +--- + +### mnemonicToKey() + +Converts a Mnemonic to a hex representation of Big Number used for factor key. + +#### Usage + +```swift +let factorKeyHex = mpcCoreKit.mnemonicToKey(shareMnemonic: "Mnemonics", format: "mnemonic"); +``` + +### keyToMnemonic() + +Converts a factor key hex string to a Mnemonic. + +#### Usage + +```swift +let factorKeyMnemonics = mpcCoreKit.mnemonicToKey(factorKey: "Factor key in hex", format: "mnemonic"); +``` diff --git a/sidebars.ts b/sidebars.ts index 3c71d18bf..5a1530ad8 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -1880,6 +1880,27 @@ const sidebars: SidebarsConfig = { }, ], }, + { + type: "category", + label: "MPC Core Kit iOS SDK", + items: [ + "sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios", + "sdk/core-kit/mpc-core-kit-ios/install", + "sdk/core-kit/mpc-core-kit-ios/initialize", + "sdk/core-kit/mpc-core-kit-ios/authentication", + "sdk/core-kit/mpc-core-kit-ios/usage", + { + type: "link", + label: "Support Forum", + href: "https://github.com/Web3Auth/mpc-core-kit-swift/releases", + }, + { + type: "link", + label: "Release Notes", + href: "https://github.com/Web3Auth/mpc-core-kit-swift/releases", + }, + ], + }, { type: "category", label: "tKey iOS SDK", From 9afd937e9e82ab19acffc3219f68cdf29999d520 Mon Sep 17 00:00:00 2001 From: AyushBherwani1998 Date: Tue, 23 Apr 2024 12:26:10 +0800 Subject: [PATCH 2/6] resolve review comments --- docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx index 1f061cb75..87eec1c38 100644 --- a/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx +++ b/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx @@ -7,7 +7,7 @@ description: "Web3Auth MPC Core Kit iOS SDK | Documentation - Web3Auth" import Image1 from "@site/static/images/tkey-mpc-flow.png"; -Web3Auth's [mpc-core-kit-swift](https://github.com/Web3Auth/mpc-core-kit) SDK is simple and +Web3Auth's [mpc-core-kit-swift](https://github.com/Web3Auth/mpc-core-kit-swift) SDK is simple and easy-to-use SDK, which helps you implement the Web3Auth MPC Features while giving you the flexibility to customize the UI and UX of the authentication process. @@ -134,10 +134,10 @@ device seamlessly without having to generate a new factor. ## Resources -- [Quick Start](https://github.com/Web3Auth/web3auth-core-kit-examples/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): +- [Quick Start](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): Get Started with an easy to follow integration of Web3Auth -- [Example Applications](https://github.com/Web3Auth/web3auth-core-kit-examples/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): +- [Example Applications](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/mpc-core-kit-ios): Explore our example applications and try the SDK yourself. - [Troubleshooting](/troubleshooting): Find quick solutions to common issues faced by developers. From 5ae23ab3eb20594ee97a99e90907902c3fcaf097 Mon Sep 17 00:00:00 2001 From: AyushBherwani1998 Date: Tue, 23 Apr 2024 12:48:11 +0800 Subject: [PATCH 3/6] add sdk references --- src/components/SDKReferenceCards/index.tsx | 48 ++++++++++++++++++++++ src/components/navDropdown/sdk.html | 15 +++++++ 2 files changed, 63 insertions(+) diff --git a/src/components/SDKReferenceCards/index.tsx b/src/components/SDKReferenceCards/index.tsx index eb2299497..4493669b7 100644 --- a/src/components/SDKReferenceCards/index.tsx +++ b/src/components/SDKReferenceCards/index.tsx @@ -862,6 +862,54 @@ export const mpccorekitreactnative = ( ); +export const mpccorekitios = ( +
+
+

MPC Core Kit Swift SDK

+

+ Get the Web3Auth full TSS-MPC Infrastructure deeply integrated within your native iOS + application. +

+ {mobileIconsWithoutFlutter} +
+ +
+); + export const infrasdks = (
diff --git a/src/components/navDropdown/sdk.html b/src/components/navDropdown/sdk.html index 53267e72a..2101ef1c6 100644 --- a/src/components/navDropdown/sdk.html +++ b/src/components/navDropdown/sdk.html @@ -325,6 +325,21 @@

MPC Core Kit React Native SDK

+
  • + + + + + + +
    +

    MPC Core Kit Swift SDK

    +

    Implement Web3Auth MPC in your iOS App

    +
    +
    +
  • From 327d80c84fc719106df1659b0ec665289d0bf612 Mon Sep 17 00:00:00 2001 From: AyushBherwani1998 Date: Fri, 24 May 2024 11:14:31 +0530 Subject: [PATCH 4/6] update the core-kit docs --- docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx index 1a10daf2d..23710e9a5 100644 --- a/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx +++ b/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx @@ -238,6 +238,44 @@ Returns the current factor key in usage within the state of the SDK. let factorKey = try mpcCoreKit.getCurrentFactorKey(); ``` +## User & Wallet Account Functions + +--- + +### getUserInfo() + +The function returns the `NSDictonary` containing the user information. The information can be +different depending on the login provider and method used. + +#### Usage + +```swift +let userInfo: [String: Any] = try mpcCoreKit.getUserInfo() +``` + +### getKeyDetails() + +The function return `MpcKeyDetails` containing the information regarding threshold, public key, and +user's shares. For more details, please check the table below. + +#### MpcKeyDetails Class + +| Name | Description | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `tssPubKey` | TSS Public Key for the user's account. | +| `metadataPubKey` | Metadata Public Key for the user's account. | +| `requiredFactors` | `requiredFactors` denotes the factors required for the SDK to be in write state. If the value is greater than 0, the SDK will be in read state. The variable can be used to check the required factors after using the login methods to verify if user has enough factors to access the account. | +| `threshold` | `threshold` defines the total number factors required for write state. | +| `shareDescriptions` | Returns the description for the shares. | +| `totalShares` | Returns the total number shares for the account. | +| `totalFactors` | Returns the total number of factors for the account. | + +#### Usage + +```swift +let keyDetails: MpcKeyDetails = try await mpcCoreKit.getKeyDetails() +``` + ## Mnemonic Conversations --- From c9e76998af07c0fbd13f3e5f6395172e7bad1d32 Mon Sep 17 00:00:00 2001 From: AyushBherwani1998 Date: Thu, 6 Feb 2025 06:20:17 +0530 Subject: [PATCH 5/6] add provider docs --- .../mpc-core-kit-ios/providers/evm.mdx | 152 ++++++++++++++++++ sidebars.ts | 6 + 2 files changed, 158 insertions(+) create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx new file mode 100644 index 000000000..87551ec15 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx @@ -0,0 +1,152 @@ +--- +title: Ethereum Signing Provider + +description: "Ethereum Signing Provider for EVM Compatible Chains | Documentation - Web3Auth" +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +import SPMProvider from "@site/src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx"; +import CocoapodsProvider from "@site/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation-provider.mdx"; + +The [MpcProviderSwift](https://github.com/tkey/MpcProviderSwift) package provides an Ethereum +compatible signing provider with TSS Signing capabilities. This comes in handy by providing you with +a standard way of retriving user's address and interacting with blockchain. + +Please note, this package only supports Ethereum. + +## Installation + + + + + + + + + + + + + +## Set up the Extension + +The `MPCEthereumProvider` constructor accepts an `EVMSigner` object. The `EVMSigner` includes a +`sign` method for signing raw messages and a `publicKey` property to retrieve the uncompressed +public key. + +We will create an extension for `MPCCoreKit` that conforms to the `EVMSigner` protocol. Once the +extension is implemented, an `MPCCoreKit` instance can be used to construct the +`MPCEthereumProvider` instance. + +### Example + +```swift +import Foundation +import mpc_core_kit_swift +import tkey +import MpcProviderSwift +import web3 + +extension MpcCoreKit : EvmSigner { + public func sign(message: Data) throws -> Data { + // Sign the message using MPC TSS + let data = try self.tssSignSync(message: message) + return data + } + + public var publicKey: Data { + // Get the uncompressed public key + let fullAddress = try! KeyPoint( + address: self.getTssPubKey().hexString + ).getPublicKey(format: .FullAddress) + + + return Data(hex: fullAddress)?.suffix(64) ?? Data() + } + +} +``` + +## Initialisation + +Once the extension is implemented, we can initialize the `MPCEthereumProvider` by passing an +instance of `MPCCoreKit` to the constructor. + +```swift +import MpcProviderSwift + +// Use the existing MPC Core Kit instance to initialize the Ethereum Provider +let mpcEthereumProvider = MPCEthereumProvider(evmSigner: mpcCoreKit) +``` + +## Get Account + +To retrieve the user's address, you can use the `address` property of the `MPCEthereumProvider` +instance. + +### Example + +```swift +import web3 + +// Use the existing MPCEthereumProvider instance +let address: EthereumAddress = mpcEthereumProvider.address +``` + +## Sign Personal Message + +To sign a personl message, you can use the `signMessage` method. The method takes message to be +signed in `Data` format as an argument. Please note, that you don't need to add the prefix to the +message. The method will add the prefix internally. + +### Example + +```swift +do { + let signature = try mpcEthereumProvider.signMessage( + message: "Web3Auth is awesome!".data(using: .utf8)! + ) +} catch { + // Handle the error +} +``` + +## Sign Transaction + +To sign a Ethereum transaction, you can use the `signTransaction` method. The methods takes +`EthereumTransaction` object as an argument. + +### Example + +```swift +do { + let address: EthereumAddress = mpcEthereumProvider.address + + // Self Transfer 0.000001 ETH on Ethereum Mainnet + let transaction = EthereumTransaction( + from: address, + to: address, + // 0.000001 ETH in Wei format + value: 1000000000000, + data: Data.init(hex: "0x00")!, + nonce: "ADDRESS_NONCE", + gasPrice: gasPrice.multiplied(by: .init(stringLiteral: "2")), + gasLimit: gasLimit, + // Chain ID for Ethereum Mainnet + chainId: 1 + ) + + // Sign the transaction + let signedTransaction = try mpcEthereumProvider.signTransaction( + transaction: transaction + ) +} catch { + // Handle the error +} +``` diff --git a/sidebars.ts b/sidebars.ts index 5a1530ad8..f8274e2b5 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -1808,6 +1808,12 @@ const sidebars: SidebarsConfig = { "sdk/mpc-core-kit/mpc-core-kit-react-native/providers/evm", ], }, + { + type: "category", + label: "Providers", + items: ["sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm"], + }, + // "sdk/mpc-core-kit/mpc-core-kit-ios/usage", { type: "link", label: "Support Forum", From c78eb6ddc1e6122f10f85d83a200ff6e57779bd5 Mon Sep 17 00:00:00 2001 From: Yashovardhan Agrawal Date: Tue, 11 Feb 2025 14:05:26 +0530 Subject: [PATCH 6/6] Fix according to new structure --- .../core-kit/mpc-core-kit-ios/initialize.mdx | 105 ----- .../sdk/core-kit/mpc-core-kit-ios/install.mdx | 47 -- .../mpc-core-kit-ios/mpc-core-kit-ios.mdx | 159 ------- docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx | 301 ------------- .../authentication/authentication.mdx | 54 +++ .../authentication/login-jwt.mdx | 115 +++++ .../authentication/login-oauth.mdx} | 150 +------ .../mpc-core-kit-swift/initialize.mdx | 135 ++++++ .../mpc-core-kit-swift/install.mdx | 67 +++ .../mpc-core-kit-swift/mpc-core-kit-swift.mdx | 186 ++++++++ .../providers/evm.mdx | 1 - .../providers/providers.mdx | 10 + .../mpc-core-kit/mpc-core-kit-swift/usage.mdx | 404 ++++++++++++++++++ sidebars.ts | 71 +-- src/common/SDKOptions.ts | 1 + .../_cocoapods-installation-provider.mdx | 0 .../swift/_cocoapods-installation.mdx | 7 + .../swift/_spm-installation-provider.mdx | 7 + .../mpc-core-kit/swift/_spm-installation.mdx | 7 + src/common/versions.ts | 6 +- src/components/SDKReferenceCards/index.tsx | 40 +- src/components/navDropdown/sdk.html | 2 +- 22 files changed, 1072 insertions(+), 803 deletions(-) delete mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx delete mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/install.mdx delete mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx delete mode 100644 docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/authentication.mdx create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-jwt.mdx rename docs/sdk/{core-kit/mpc-core-kit-ios/authentication.mdx => mpc-core-kit/mpc-core-kit-swift/authentication/login-oauth.mdx} (51%) create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/initialize.mdx create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/install.mdx create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/mpc-core-kit-swift.mdx rename docs/sdk/mpc-core-kit/{mpc-core-kit-ios => mpc-core-kit-swift}/providers/evm.mdx (99%) create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/providers.mdx create mode 100644 docs/sdk/mpc-core-kit/mpc-core-kit-swift/usage.mdx create mode 100644 src/common/sdk/mpc-core-kit/swift/_cocoapods-installation-provider.mdx create mode 100644 src/common/sdk/mpc-core-kit/swift/_cocoapods-installation.mdx create mode 100644 src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx create mode 100644 src/common/sdk/mpc-core-kit/swift/_spm-installation.mdx diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx deleted file mode 100644 index e6d171d9b..000000000 --- a/docs/sdk/core-kit/mpc-core-kit-ios/initialize.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: "Initializing MPC Core Kit iOS SDK" -sidebar_label: "Initialize" -displayed_sidebar: sdk -description: "Web3Auth MPC Core Kit iOS SDK - Initialize | Documentation - Web3Auth" ---- - -import ChainConfig from "@site/src/common/sdk/pnp/web/_chain-config.mdx"; -import Web3AuthOptions from "@site/src/common/sdk/pnp/web/_web3authcore-options.mdx"; -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; - -After Installation, the next step to use Web3Auth MPC Core Kit iOS is to initialize the SDK. - -## Instantiating MpcCoreKit - -### Creating a class to conform ILocalStorage - -MpcCoreKit takes `ILocalStorage` as an input parameter. The package uses it to store and retrieve -the device factor. `ILocalStorage` being a `protocol` gives us the freedom to choose the local -storage of our choice. - -Here we are using `UserDefaults`, but you can choose the storage of your choice. - -```swift -import Foundation -import mpc_core_kit_swift - -class UserStorage : ILocalStorage { - func get(key: String) async throws -> Data { - guard let data = UserDefaults().value(forKey: key) as? Data else { - return Data() - } - return data - } - - func set(key: String, payload: Data) async throws { - UserDefaults().setValue(payload, forKey: key) - } -} - -let storage = UserStorage() -``` - -### Creating MpcCoreKit instance - -Once, we have created a class to conform `ILocalStorage` we are good to create an instance of -`MpcCoreKit`. If you want to disable the hashed cloud factor, you can set `disableHashFactor` to -true during the initialization. - -```swift - let mpcCoreKit = MpcCoreKit( - web3AuthClientId: "Your Web3Auth Client ID" // Get it from Web3Auth Dashboard, - web3AuthNetwork: .SAPPHIRE_MAINNET, - localStorage: UserStorage() -) -``` - -#### Arguments - - - - - -| Parameter | Description | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `web3AuthClientId` | Your Web3Auth Client Id from [Web3Auth Dashboard](https://dashboard.web3auth.io/). | -| `web3AuthNetwork` | The Web3auth network to be used for MPC Wallet Management. Supported values are `Web3AuthNetwork.SAPPHIRE_MAINNET`, `Web3AuthNetwork.SAPPHIRE_DEVNET`, `Web3AuthNetwork.MAINNET`, `Web3AuthNetwork.TESTNET`, `Web3AuthNetwork.CYAN`, `Web3AuthNetwork.AQUA` | -| `disableHashFactor` | Defines whether to use hashed cloud factor or not. Default value is `false`. | -| `localStorage` | A class which conforms to `ILocalStorage`. Used by the SDK internally to store and retrieve device share. | - - - - - -```swift -public struct MpcCoreKit { - public init(web3AuthClientId : String , web3AuthNetwork: Web3AuthNetwork, disableHashFactor : Bool = false, localStorage: ILocalStorage ) { - self.option = .init(disableHashFactor: disableHashFactor , Web3AuthClientId: web3AuthClientId, network: web3AuthNetwork) - self.appState = CoreKitAppState.init() - - self.network = web3AuthNetwork - - self.torusUtils = TorusUtils( - enableOneKey: true, - network: self.network.toTorusNetwork(), - clientId: web3AuthClientId - ) - - self.nodeDetailsManager = NodeDetailManager(network: self.network.toTorusNetwork()) - - self.coreKitStorage = .init(storeKey: self.storeKey, storage: localStorage) - - } -} -``` - - - diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx deleted file mode 100644 index 0a6e94981..000000000 --- a/docs/sdk/core-kit/mpc-core-kit-ios/install.mdx +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: "Installing MPC Core Kit iOS SDK" -sidebar_label: "Install" -displayed_sidebar: sdk -description: "Web3Auth MPC Core Kit iOS SDK - Install | Documentation - Web3Auth" ---- - -## MPC Core Kit iOS - -This package helps you implement the Web3Auth MPC Features while giving you the flexibility to -customize the UI and UX of the authentication process. - -#### Swift Package Manager - -1. In Xcode, with your app project open, navigate to **File > Add Packages**. - -2. When prompted, add the tKey iOS SDK repository: - - ```sh - https://github.com/Web3Auth/mpc-core-kit-swift - ``` - - From the `Dependency Rule` dropdown, select `Exact Version` and enter `1.0.0` as the version. - -3. When finished, Xcode will automatically begin resolving and downloading your dependencies in the - background. - -## Web3 Swift MPC Provider - -This package gives access to tss signing capabilities to be used with mpc-core-kit-swift. This comes -in handy by providing you with a standard way of retriving user's address and interacting with -blockchain. As of now, it only supports Ethereum. - -#### Swift Package Manager - -1. In Xcode, with your app project open, navigate to **File > Add Packages**. - -2. When prompted, add the tKey iOS SDK repository: - - ```sh - https://github.com/tkey/web3-swift-mpc-provider - ``` - - From the `Dependency Rule` dropdown, select `Exact Version` and enter `1.0.0` as the version. - -3. When finished, Xcode will automatically begin resolving and downloading your dependencies in the - background. diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx deleted file mode 100644 index 87eec1c38..000000000 --- a/docs/sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios.mdx +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: "Web3Auth MPC Core Kit iOS SDK" -displayed_sidebar: sdk -sidebar_label: Overview -description: "Web3Auth MPC Core Kit iOS SDK | Documentation - Web3Auth" ---- - -import Image1 from "@site/static/images/tkey-mpc-flow.png"; - -Web3Auth's [mpc-core-kit-swift](https://github.com/Web3Auth/mpc-core-kit-swift) SDK is simple and -easy-to-use SDK, which helps you implement the Web3Auth MPC Features while giving you the -flexibility to customize the UI and UX of the authentication process. - -## This Documentation is based on [`1.0.0`](https://github.com/Web3Auth/mpc-core-kit-swift/releases) SDK Version. - -## Requirements - -- iOS 14+ -- Xcode 11.4+ / 12.x -- Swift 4.x / 5.x - -:::note - -The minimum [pricing plan](https://web3auth.io/pricing.html) to use this SDK in a production -environment is the **Enterprise Plan**. However, you can use this SDK with all features enabled in -the development environment for free. - -::: - -## Web3Auth MPC Infrastructure Components - -With the Web3Auth infrastructure, your key is divided into multiple parts and stored across your -devices and our Auth Network. This ensures that your key is always available and never stored in a -single place. While in the traditional Web3Auth SDK, your key was dynamically reconstructed in the -frontend using threshold signatures, with the new Web3Auth MPC (Multi Party Computation) -architecture, it is **never reconstructed**. Instead, these partial keys are stored across different -locations, and your device is used to make partial signatures for your message/ transaction. These -are finally returned to the frontend where using TSS (Threshold Signature Scheme), these signatures -are combined to make a final signature. You can use this finally signed message/transaction to make -a transaction on the blockchain. - -The Threshold Signature Scheme (TSS) is a cryptographic primitive for distributed key generation and -signing. The use of TSS in Web3Auth's Auth network is a new paradigm that can provide numerous -benefits, especially in terms of security. - -Web3Auth Wallet Management - -As you can notice in this diagram above, the final output, i.e., the User's TSS Account, is -generated in multiple stages within the infrastructure. Since this is a TSS- MPC based -infrastructure, you don't get back a private key, but signatures that can be used to make -transactions on the blockchain. Let's understand each of these stages in detail. - -### Factors - -#### Social Login Factor - -This is the primary way for a user to access their account. This step involves authentication using -a user's preferred social login provider. The idToken received from the social login provider here -is passed to the Web3Auth Auth Network to generate the TSS Shares in the Nodes. By default, these -nodes have a threshold of 3/5 that can be customized according to requirements. When a user logs in, -the Auth Network generates signatures corresponding to the TSS Shares in the nodes and returns them -to the user's end. These signatures are then used alongside other shares to generate the final TSS -Account signatures. - -#### Device Factor (`index:2`) - -This is the second factor used to access the user's account. This step involves the generation of a -TSS Share on the user's device and using that to generate a final signature for the TSS Account -alongside the social login factor. This ensures the user logs in using their trusted device and -maintains a proper non-custodial setup. - -#### Backup Factor (`index:3`) - -A user has a choice to generate as many backup factors as needed to access their account. This step -involves the generation of a TSS Share on the user's end and storing them in whichever location they -prefer. This share can be used similarly to the device share to generate a final signature for the -TSS Account alongside the social login and/or device factors. - -### Threshold - -The threshold is the minimum number of shares required to generate a final signature for the TSS -Account. This threshold, by default, is set to 3/5 on the Auth Network and 2/3 for the user's device -front. This ensures high availability and ease of access on both ends alongside optimum security. -Both these thresholds can be customized according to the requirements. - -### Components of a Factor - -#### TSS Shares - -The TSS Shares are the main component needed for the generation of the final working signature of -the user. These shares are generated using distributed key generation and are stored in the Auth -Network and the user's device. Since these shares are generated using MPC, they are **never -reconstructed** and always stay decentralized and secure. - -#### Metadata Key & Shares - -The Metadata Key closely mimics the storage of the TSS Shares. The only difference is that the -metadata key is always reconstructed and used for its encryption/decryption capabilities. It -utilizes basic Shamir's Secret Sharing and is initially generated on a user's front end. The -metadata key is utilized for the encryption/decryption of the user metadata stored in the Web3Auth -Metadata Server. - -One metadata share gives you the **read** access to the metadata server, while two or more (as the -threshold is reached) give you the **write** access. - -#### Factor Keys - -To enable refresh, deletion, and rotational capabilities on the `tssKey`, we also introduce -**factorKeys**. Factor Keys are randomly generated keys unique to each factor-generated user's -device and backups, like users' phones, chrome extensions, on their cloud, assisting third parties, -etc. - -As share to the TSS Key and/or Metadata Key may rotate, Factor Keys allow a consistent secret to be -saved in these different locations. - -## Understanding the MPC Core Kit SDK Flow - -By default, for a new user, the MPC Core Kit SDK starts in a 2/2 flow. This means that the user will -have to generate a social login factor and a hashed cloud factor. This hashed cloud factor is -derived on the SDK front end and stored in the encrypted metadata server. This enables the user to -start the login process from any device without creating an MFA factor. - -This is done to make sure the user can access their account from any device without having to -generate a new factor. However, this makes the initial onboarding, semi-custodial. To make the -onboarding completely non-custodial, the user can use the `enableMfa` feature to generate a device -and backup factor and delete the hashed cloud factor. This makes the user's account completely -non-custodial in 2/3 setup and enables them to access their account from any device using the backup -share. Device share is saved on a trusted device and can be used to access the account from that -device seamlessly without having to generate a new factor. - -## Resources - -- [Quick Start](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/mpc-core-kit-ios/mpc-core-kit-ios-quick-start): - Get Started with an easy to follow integration of Web3Auth - -- [Example Applications](https://github.com/Web3Auth/web3auth-core-kit-examples/tree/main/mpc-core-kit-ios): - Explore our example applications and try the SDK yourself. - -- [Troubleshooting](/troubleshooting): Find quick solutions to common issues faced by developers. - -- [Source Code](https://github.com/web3auth/mpc-core-kit-swift): Web3Auth is open sourced. You can - find the source code on our GitHub repository. - -- [Community Support Portal](https://web3auth.io/community): Join our community to get support from - our team and other developers. - -## Helper SDKs - -### Web3 Provider - -#### [web3-swift-mpc-provider](https://github.com/tkey/web3-swift-mpc-provider) - -This package gives access to tss signing capabilities to be used with mpc-core-kit-swift. This comes -in handy by providing you with a standard way of retriving user's address and interacting with -blockchain. As of now, it only supports Ethereum. diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx b/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx deleted file mode 100644 index 23710e9a5..000000000 --- a/docs/sdk/core-kit/mpc-core-kit-ios/usage.mdx +++ /dev/null @@ -1,301 +0,0 @@ ---- -title: "Usage of MPC Core Kit iOS SDK" -sidebar_label: "Usage" -displayed_sidebar: sdk -description: "Web3Auth MPC Core Kit iOS SDK - Usage | Documentation - Web3Auth" ---- - -Once you've installed and successfully initialized `MpcCoreKit`, you can use it to authenticate your -users. Further, you can use the Web3 Swift provider given by Web3Auth to sign transactions and -interact with the blockchain. - -## Authentication Functions - ---- - -### [loginWithOAuth()](./authentication#log-in-with-oauth) - -If you are looking for an Authentication Flow in your application (like Auth0 SPA Flow), you can use -the `loginWithOAuth()` function. - -#### Usage - -```swift -let result = try await mpcCoreKit.loginWithOAuth( - loginProvider: .google, - clientId: "Your Google Client id", - verifier: "Your Custom Verifier name" -); -``` - -### [loginWithJWT()](./authentication#log-in-with-jwt-byoa) - -If you are looking to pass a JWT-based IdToken to the SDK from your application, you can use the -`loginWithJWT()` function. - -#### Usage - -```swift -let result = try await mpcCoreKit.loginWithJwt( - verifier: "Your verifier name from Web3Auth Dashboard", - verifierId: "Your verifierd Id value", - idToken: "Your JWT id Token" -) -``` - -### inputFactorKey() - -Inputs the Factor Key into the SDK. This function is used to recover the User's account using the -Factor Key. If the factor key is correct, the SDK initializes the User's account and logs them in. - -If you want to change the current active factor key in the current state of the SDK, you can use -this function. - -#### Usage - -```swift -try await mpcCoreKit.inputFactor( - factorKey: factorKey -) -``` - -### [logout()](./authentication#logging-out-the-user) - -Logs out the User. - -#### Usage - -```swift -try await mpcCoreKit.logout(); -``` - -## Factor Handling Functions - ---- - -### enableMFA() - -Enables MFA for the user. It creates a device factor and stores it in the local storage. It also -creates a backup factor and returns it to the user. You can also pass a factor key that can be used -for the backup factor. If you don't pass a factor key, a new factor key will be generated. To pass -the factor key you can use `enableMFA` arguement. - -Most importantly, this function deletes the Hashed Factor Key enabling a non-custodial flow. - -#### Usage - -```swift -let factor = try await mpcCoreKit.enableMFA(); -``` - -#### Arguments - -| Argument | Description | -| ---------------- | ------------------------------------------------------------------------------------------------------------------- | -| `enableMFA` | If you wish to set a custom factor key, you can use `enableMFA` argument. By default, SDK will handle this for you. | -| `recoveryFactor` | Defines whether to create recovery factor along with device factor. Default value is `true`. | - -#### `enableMFARecoveryFactor` struct - -```swift -public struct enableMFARecoveryFactor { - public var factorKey: String? - public var factorTypeDescription: FactorDescriptionTypeModule - public var additionalMetadata: [String:Any] - - public init(factorKey: String? = nil, factorTypeDescription: FactorDescriptionTypeModule = .Other, additionalMetadata: [String : Any] = [:]) { - self.factorKey = factorKey - self.factorTypeDescription = factorTypeDescription - self.additionalMetadata = additionalMetadata - } -} - -public enum FactorDescriptionTypeModule { - case HashedShare - case SecurityQuestions - case DeviceShare - case SeedPhrase - case PasswordShare - case SocialShare - case Other - - public func toString () -> String { - switch self { - - case .HashedShare: return "hashedShare" - case .SecurityQuestions: return "tssSecurityQuestions" - case .DeviceShare: return "deviceShare" - case .SeedPhrase: return "seedPhrase" - case .PasswordShare: return "passwordShare" - case .SocialShare: return "socialShare" - case .Other: return "Other" - } - } -} -``` - -### createFactor() - -A low-level function, helps you to create a backup factor key based on the type of TSS Share you -want to create. You can pass your own factor key or let the SDK generate one for you. - -#### Usage - -```swift -let factor = try await mpcCoreKit.createFactor( - tssShareIndex: .DEVICE, - factorKey: nil, - factorDescription: .DeviceShare -) -``` - -#### Arguments - -| Argument | Description | -| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tssShareIndex` | Defines the index of share. It can be either 2, or 3. You can use `TssShareType` to set the share index. | -| `factorKey?` | If you wish to pass the custom factor key for creation of factor, you can use `factorKey`. If value is nil, and SDK will internally create a new factory key for you. | -| `factorDescription` | Defines which type of share you are using as a factor. Checkout `FactorDescriptionTypeModule` for available options. | -| `additionalMetadata` | If you wish to store any additional meta data on metadata layer, you can pass it using `additionalMetadata`. It takes `[String: Any]` as a value. The default value is `[:]`. | - -#### Interfaces - -```swift - -public enum TssShareType { - case DEVICE - case RECOVERY - - public func toInt32 () -> Int32 { - switch self { - - case .DEVICE: return 2 - case .RECOVERY: return 3 - } - } - public func toString () -> String { - switch self { - - case .DEVICE: return "2" - case .RECOVERY: return "3" - } - } -} - -public enum FactorDescriptionTypeModule { - case HashedShare - case SecurityQuestions - case DeviceShare - case SeedPhrase - case PasswordShare - case SocialShare - case Other - - public func toString () -> String { - switch self { - - case .HashedShare: return "hashedShare" - case .SecurityQuestions: return "tssSecurityQuestions" - case .DeviceShare: return "deviceShare" - case .SeedPhrase: return "seedPhrase" - case .PasswordShare: return "passwordShare" - case .SocialShare: return "socialShare" - case .Other: return "Other" - } - } -} -``` - -### deleteFactor() - -Deletes the Factor, respective to the factorPub provided for the User's account. You can get the -factor Pubs by using the `getAllFactorPubs()` function. - -It will throw an error if you try to delete the factor that is currently active within the state of -the SDK. Use the `inputFactorKey()` function to change the factor key in the current state of the -SDK to be able to delete that factor. - -#### Usage - -```swift -try await mpcCoreKit.deleteFactor(deleteFactorPub: "Factor's PubKey") -``` - -#### Arguments - -| Argument | Description | -| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `deleteFactorPub` | The PubKey for the factor key you want to delete. The SDK internally will retrieve the corresponding factory key and delete it. | -| `factorKey?` | The factorKey you want to delete. The default value is `nil`. | - -### getCurrentFactorKey() - -Returns the current factor key in usage within the state of the SDK. - -#### Usage - -```swift -let factorKey = try mpcCoreKit.getCurrentFactorKey(); -``` - -## User & Wallet Account Functions - ---- - -### getUserInfo() - -The function returns the `NSDictonary` containing the user information. The information can be -different depending on the login provider and method used. - -#### Usage - -```swift -let userInfo: [String: Any] = try mpcCoreKit.getUserInfo() -``` - -### getKeyDetails() - -The function return `MpcKeyDetails` containing the information regarding threshold, public key, and -user's shares. For more details, please check the table below. - -#### MpcKeyDetails Class - -| Name | Description | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `tssPubKey` | TSS Public Key for the user's account. | -| `metadataPubKey` | Metadata Public Key for the user's account. | -| `requiredFactors` | `requiredFactors` denotes the factors required for the SDK to be in write state. If the value is greater than 0, the SDK will be in read state. The variable can be used to check the required factors after using the login methods to verify if user has enough factors to access the account. | -| `threshold` | `threshold` defines the total number factors required for write state. | -| `shareDescriptions` | Returns the description for the shares. | -| `totalShares` | Returns the total number shares for the account. | -| `totalFactors` | Returns the total number of factors for the account. | - -#### Usage - -```swift -let keyDetails: MpcKeyDetails = try await mpcCoreKit.getKeyDetails() -``` - -## Mnemonic Conversations - ---- - -### mnemonicToKey() - -Converts a Mnemonic to a hex representation of Big Number used for factor key. - -#### Usage - -```swift -let factorKeyHex = mpcCoreKit.mnemonicToKey(shareMnemonic: "Mnemonics", format: "mnemonic"); -``` - -### keyToMnemonic() - -Converts a factor key hex string to a Mnemonic. - -#### Usage - -```swift -let factorKeyMnemonics = mpcCoreKit.mnemonicToKey(factorKey: "Factor key in hex", format: "mnemonic"); -``` diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/authentication.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/authentication.mdx new file mode 100644 index 000000000..af5b84635 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/authentication.mdx @@ -0,0 +1,54 @@ +--- +title: "Authentication Overview in MPC Core Kit iOS SDK" +sidebar_label: "Overview" +description: "Web3Auth MPC Core Kit iOS SDK - Authentication Overview | Documentation - Web3Auth" +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +There are two ways to login your users, depending on the type of authentication method you've +chosen. If you are looking for an Authentication Flow in your application like +[Single Page Application(SPA)](https://www.oauth.com/oauth2-servers/single-page-apps/) flow, you can +use the `loginWithOAuth` method. + +If you are looking to pass a JWT-based IdToken to the SDK from your application, like +[Regular Web Application(RWA)](https://www.oauth.com/oauth2-servers/server-side-apps/) Flow or even +using your own JWT provider, you can use the `loginWithJWT` method. + +As a prerequisite, before triggering the login function, you need to create a verifier for your +login method on the [Web3Auth Dashboard](https://dashboard.web3auth.io). + +## Creating a Verifier + +Since this is a Core Kit SDK, it gives you flexibility to use your own authentication service. You +need to create a custom verifier, which allows you to plug in your own authentication service to +authenticate users. + +For example, while authenticating with Google, you have to use your own Google Client ID setup to +authenticate users directly or use auth provider services like Auth0, Firebase, AWS Cognito etc. +Additionally, you can make your own JWT token authentication system and pass over the ID Token to +Web3Auth. + +[Learn how to create a verifier](/auth-provider-setup/verifiers). + +![Create a Verifier](/images/dashboard/create-verifier.gif) + +## Login Methods + +As discussed earlier, there are two login methods available in the SDK tailored to your use case. + +- [Login with OAuth](/sdk/mpc-core-kit/mpc-core-kit-js/authentication/login-oauth): You can use this + method the implicit login flow, where you don't need to manually handle the authentication and get + the JWT token. + +- [Login with JWT](/sdk/mpc-core-kit/mpc-core-kit-js/authentication/login-jwt): You can use this + method to manually handle the authentication, and send the JWT token to Web3Auth. This method + allows you to bring your own authentication flow. + +:::tip Recommended + +For faster login speeds, we recommend using the +[Login with JWT](/sdk/mpc-core-kit/mpc-core-kit-js/authentication/login-jwt) method. + +::: diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-jwt.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-jwt.mdx new file mode 100644 index 000000000..5c2633735 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-jwt.mdx @@ -0,0 +1,115 @@ +--- +title: "Log in with OAuth" +sidebar_label: "Log in with OAuth" +description: "Web3Auth MPC Core Kit Swift SDK - Log in with OAuth | Documentation - Web3Auth" +--- + +import ServiceWorkerCode from "@site/src/common/sdk/infra/tkey/_sw-js.mdx"; + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +To authenticate users using Single Page Application(SPA) flow, you can use the `loginWithOAuth` +method. The SDK uses method overloading to support both single verifier and aggregate verifier. + +Unlike the `loginWithJWT` method, this approach doesn't require you to manage the authentication +process manually. The method automatically manages the authentication flow and handles the response +from redirection internally. + +:::info Recommended + +The [loginWithJWT](/docs/sdk/mpc-core-kit/mpc-core-kit-ios/authentication/login-jwt) method is +recommended for faster login experience. + +::: + +## Single Verifier + +A single verifier flow operates independently of the other verifiers you've created on the Web3Auth +dashboard. For example, if you've set up custom verifiers for Google and Apple on the dashboard, +each verifier will generate a different wallet for the same user. + +To login with a single verifier, you will require to create a custom verifier in the Web3Auth +dashboard. If you haven't already created one, +[learn how to create a verifier](/docs/auth-provider-setup/byo-jwt-provider/#set-up-custom-jwt-verifier). + +The method takes `SingleLoginParams` as a parameter. + +### Parameters + +| Name | Description | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `typeOfLogin` | Defines the type of social/ OAuth login you want to use. Available values are `.google`, `.facebook`, `.discord`, `.reddit`, `.twitch`, `.apple`, `.github`, `.linkedin`, `.twitter`, `.weibo`, `.line`, `.email_password`, `.email_passwordless`, `.sms_passwordless`, and `.jwt` | +| `verifier` | Your custom verifier name. | +| `clientId` | Your OAuth provider client id. For instance, if you are using `LoginType.google` it'll take the google login id. | +| `redirectURL` | Defines the redirect URL, the default value is `https://scripts.toruswallet.io/redirect.html`. | +| `jwtParams?` | Auth0 login parameters. See [Auth0ClientOptions](https://github.com/torusresearch/customauth-swift-sdk/blob/master/Sources/CustomAuth/Common/LoginParams/Auth0ClientOptions.swift). Explicitly required for login types: `.jwt`, `.email_passwordless`, `.sms_passwordless`. | +| `hash?` | This is the urlfragment part of the url, only use if needed. | + +### Usage + +```swift +import CustomAuth + +let singleLoginParams = SingleLoginParams( + typeOfLogin: .google, + verifier: "YOUR_GOOGLE_VERIFIER_NAME", + clientId: "YOUR_GOOGLE_CLIENT_ID" +) + +do { + // Use an existing MPCCoreKit instance + let result = try await mpcCoreKit.loginWithOAuth( + singleLoginParams: singleLoginParams + ) +} catch { + // Handle error +} +``` + +## Aggregate Verifier + +An aggregate verifier enables you to combine multiple verifiers/ login methods, ensuring that users +can retrieve the same wallet address regardless of the method they choose to log in. +[Learn more about aggregate verifiers](/docs/auth-provider-setup/aggregate-verifier). + +To login with an aggregate verifier, you will require to create an aggregate verifier in the +Web3Auth dashboard. If you haven't already created one, +[learn how to create an aggregate verifier](/docs/auth-provider-setup/aggregate-verifier#setting-up-an-aggregate-verifier). + +The method takes `AggregateLoginParams` as a parameter. + +### Parameters + +| Name | Description | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `aggregateVerifierType` | Defines the aggregate verifier type. Supported value is `AggregateVerifierType.single_id_verifier`. This means the aggregate verifier would consider only one verification field to aggregate the different verifiers. | +| `verifierIdentifier` | Pass your top level aggregate verifier name. | +| `subVerifierDetailsArray` | Takes in a list of sub verifiers for the aggregate login, this is a list of [SingleLoginParams](#parameters). | + +### Usage + +```swift +import CustomAuth + +let aggregateLoginParams = AggregateLoginParams( + aggregateVerifierType: AggregateVerifierType.single_id_verifier, + verifierIdentifier: "YOUR_AGGREGATE_VERIFIER_NAME", + subVerifierDetailsArray: [ + SingleLoginParams( + typeOfLogin: .google, + verifier: "YOUR_GOOGLE_SUB_VERIFIER_NAME", + clientId: "YOUR_GOOGLE_CLIENT_ID" + ) + ] +) + +do { + // Use an existing MPCCoreKit instance + let result = try await mpcCoreKit.loginWithOAuth( + aggregateLoginParams: aggregateLoginParams + ) +} catch { + // Handle error +} +``` diff --git a/docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-oauth.mdx similarity index 51% rename from docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx rename to docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-oauth.mdx index ce94e5249..182422364 100644 --- a/docs/sdk/core-kit/mpc-core-kit-ios/authentication.mdx +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-oauth.mdx @@ -1,67 +1,22 @@ --- -title: "Authentication in MPC Core Kit iOS SDK" -sidebar_label: "Authentication" -displayed_sidebar: sdk -description: "Web3Auth MPC Core Kit iOS SDK - Authentication | Documentation - Web3Auth" ---- - -import ServiceWorkerCode from "@site/src/common/sdk/core-kit/tkey/_sw-js.mdx"; -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; - -There are two ways to login your users, depending on the type of authentication method you've -chosen. If you are looking for an Authentication Flow in your application (like Auth0 SPA Flow), you -can use the `loginWithOAuth()` function. If you are looking to pass a JWT-based IdToken to the SDK -from your application (like Auth0 RWA Flow or even BYOA JWT provider), you can use the -`loginWithJWT()` function. - -As a prerequisite, before triggering the login function, you need to create a verifier for your -login method on the [Web3Auth Dashboard](https://dashboard.web3auth.io). - -## Creating a Verifier - -Since this is a Core Kit SDK, it does not provide any default authentication methods. You need to -create a custom verifier to use this SDK. This means that you need to authenticate users with your -own custom authentication service. For example, while authenticating with Google, you have to use -your own Google Client ID and Dashboard to authenticate users directly or use aggregate services -like Auth0, Firebase, AWS Cognito etc. Additionally, you can make your own JWT token authentication -system and pass over the ID Token to Web3Auth to generate a private key for them. - -For enabling this, you need [Create a Verifier](/auth-provider-setup/verifiers) from the **Custom -Auth** section of the [Web3Auth Developer Dashboard](https://dashboard.web3auth.io) with your -desired configuration. - -:::tip +title: "Log in with OAuth" -If you want to know more about setting up a verifier and how to use it, please refer to the -[Custom Authentication Documentation](/features/custom-authentication). - -::: - -:::warning - -Core Kit SDK only supports Sapphire Mainnet and Devnet networks. The other networks don't support -MPC functionalities. - -::: - -## Log In with OAuth +sidebar_label: "Log in with OAuth" +description: "Web3Auth MPC Core Kit JS SDK - Log in with OAuth | Documentation - Web3Auth" +--- -If you wish to have SPA flow, similar to Auth0, you can use `loginWithOAuth` function. +import ServiceWorkerCode from "@site/src/common/sdk/infra/tkey/_sw-js.mdx"; -### Usage +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; -```swift -let result = try await mpcCoreKit.loginWithOAuth( - loginProvider: .google, - clientId: "Your Google Client id", - verifier: "Your Custom Verifier name" -); -``` +To authenticate users using Single Page Application(SPA) flow, you can use the `loginWithOAuth` +method. This methods takes the `OAuthLoginParams` as a parameter, which is an object that contains +the details of the verifier, and additional authentication parameters. -### Arguements +## Parameters -| Variable | Description | +| Parameters | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `loginProvider` | Defines the login provider to be used. Supported values are `LoginProviders.google`, `LoginProviders.facebook`, `LoginProviders.twitch`, `LoginProviders.reddit`, `LoginProviders.discord`, `LoginProviders.apple`, `LoginProviders.github`, `LoginProviders.linkedin`, `LoginProviders.kakao`, `LoginProviders.twitter`, `LoginProviders.weibo`, `LoginProviders.line`, `LoginProviders.wechat`, `LoginProviders.email_password`, `LoginProviders.jwt` | | `clientId` | Client id for respective `loginProvider`. For instance google client id, auth0 client id, and etc. | @@ -70,72 +25,20 @@ let result = try await mpcCoreKit.loginWithOAuth( | `redirectURL` | | | `browserRedirectURL` | | -### Result - -The `loginWith0Auth`returns `MpcKeyDetails` upon success, which has infomration regarding -thresholds, required factors, and etc. - - - - - -| Parameter | Description | -| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `tssPubKey` | It holds the value for the TSS PubKey in compressed form. The type of `tssPubKey` is `String`. | -| `metadataPubKey` | It holds the value for metadata PubKey which is used for interacting with metadata layer. | -| `requiredFactors` | It defines the total factors still required for SDK to be in write mode. If required factors are greater than 0, the SDK will be in read mode. You can use `inputFactor` function to input factor and refresh the instance. | -| `threshold` | Defines the threshold set by the SDK. Ideally it would be 2. | -| `total_shares` | Defines the total number of shares for user. Initially if the hashed cloud factor is set, it would be 2. | - - - - -```swift -public struct MpcKeyDetails : Codable { - public let tssPubKey : String - public let metadataPubKey: String - public let requiredFactors: Int32 - public let threshold: UInt32 - public let shareDescriptions : String - public let total_shares: UInt32 -} -``` - - - -## Log In with JWT (BYOA) - -If you are looking to pass a JWT-based IdToken to the SDK from your application, you can use the -`loginWithJWT()` function. - -### Usage +## Usage ```swift -let result = try await mpcCoreKit.loginWithJwt( - verifier: "Your verifier name from Web3Auth Dashboard", - verifierId: "Your verifierd Id value", - idToken: "Your JWT id Token" -) +let result = try await mpcCoreKit.loginWithOAuth( + loginProvider: .google, + clientId: "Your Google Client id", + verifier: "Your Custom Verifier name" +); ``` -### Arguements +## Result -| Argument | Description | -| ------------ | -------------------------------------------------------------------------------------------------------------------------------------- | -| `verifier` | Your verifier name from Web3Auth dashboard. | -| `verifierId` | Your verifier id value, i.e. email, sub or custom. Make sure you have selected correct verifier id while creating the custom verifier. | -| `idToken` | Your JWT id token for verification. | - -### Result - -The `loginWithJWT`returns `MpcKeyDetails` upon success, which has infomration regarding thresholds, -required factors, and etc. +The `loginWith0Auth`returns `MpcKeyDetails` upon success, which has infomration regarding +thresholds, required factors, and etc. - -## Logging out the User - -To disconnect user's connected wallet/ provider and log them out of the Web3Auth MPC Core Kit SDK -you can use `logout` function. - -### Usage - -```swift -try await mpcCoreKit.logout(); -``` diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/initialize.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/initialize.mdx new file mode 100644 index 000000000..8fe5f4621 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/initialize.mdx @@ -0,0 +1,135 @@ +--- +title: "Initializing MPC Core Kit Swift SDK" +sidebar_label: "Initialize" +description: "Web3Auth MPC Core Kit Swift SDK - Initialize | Documentation - Web3Auth" +--- + +import ChainConfig from "@site/src/common/sdk/pnp/web/_chain-config.mdx"; +import Web3AuthOptions from "@site/src/common/sdk/pnp/web/_web3authcore-options.mdx"; +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +After installation, the next step to use Web3Auth MPC Core Kit is to configure the storage & MPC +Core Kit instance. + +1. [Configure Storage](#configure-storage) +2. [Configure MpcCoreKit instance](#configure-instance) + +## Configure Storage + +MPC Core Kit uses `IStorage` to store the TSS Factor. `IStorage` being a `protocol` gives you the +freedom to choose the storage of your choice. Here we are using `UserDefaults`, but you can choose +the storage layer of your choice. + +The storage layer is generally used to store the Device Factor. + +### Methods + +The `IStorage` protocol has the following methods which you need to implement in your storage layer +implementation. + +| Name | Description | +| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `set` | This method will be used to store the factor in the storage layer. This method doesn't return anything on success. | +| `get` | This method will be used to try and retrieve the factor based on the given key from the storage layer. The method should return `Data` upon success. | + +### Example + +```swift +import Foundation +import mpc_core_kit_swift + +class UserStorage : IStorage { + func get(key: String) async throws -> Data { + print(key) + guard let data = UserDefaults().value(forKey: key) as? Data else { + return Data() + } + return data + } + + func set(key: String, payload: Data) async throws { + UserDefaults().setValue(payload, forKey: key) + } +} +``` + +## Configure MpcCoreKit instance + +Once, we have configured the storage layer, we can now configure the `MpcCoreKit` instance. Please +note that this is the most critical steps where you need to pass different parameters according to +the preference of your project. + +### Parameters + + + + + +| Parameter | Description | +| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `web3AuthClientId` | The Web3Auth Client ID for your application. Find one at [https://dashboard.web3auth.io](https://dashboard.web3auth.io/) | +| `manualSync` | Enables you to manually sync with the Web3Auth Metadata Server, helping you manage the API calls to the server. Default value is false. | +| `web3AuthNetwork` | Web3Auth Network used for MPC Wallet Management. | +| `disableHashedFactorKey` | Disables the Hashed Key, making the sure user logs in always in a non-custodial mode. Recommended only if you have proper MFA flow setup for the user while creating the account. Default value is false. | +| `hashedFactorNonce?` | Nonce for the hashed factor. Default value is Web3Auth Client id. [Learn more about hashed factor](https://web3auth.io/docs/sdk/mpc-core-kit/mpc-core-kit-js/#hashed-cloud-factor). | +| `storage` | Defines the storage for MPC Core Kit's state. You'll have to define your own storage layer by implementing the `IStorage` protocol. | +| `storageKey?` | Defines the custom storage key to be used to store and retrieve the MPC Core Kit state from the storage layer. | + + + + + +```swift +public class CoreKitWeb3AuthOptions { + public let web3AuthClientId: String + public let manualSync: Bool + public let web3AuthNetwork: Web3AuthNetwork + public let storageKey: String? + public let sessionTime: Int? + public let disableHashedFactorKey: Bool + public let storage: IStorage + // It is used to define the URL for the Metadata to be used in the SDK. + // This is for internal testing only, and shouldn't be used. + public let overwriteMetadataUrl: String? + public let hashedFactorNonce: String + + public init(web3AuthClientId: String, manualSync: Bool = false, web3AuthNetwork: Web3AuthNetwork = .SAPPHIRE_MAINNET, storage: IStorage, storageKey: String? = "local", sessionTime: Int? = 86000, disableHashedFactorKey: Bool = false, overwriteMetadataUrl: String? = nil, hashedFactorNonce: String? = nil) { + self.web3AuthClientId = web3AuthClientId + self.manualSync = manualSync + self.web3AuthNetwork = web3AuthNetwork + self.storageKey = storageKey + self.sessionTime = sessionTime + self.storage = storage + self.disableHashedFactorKey = disableHashedFactorKey + self.overwriteMetadataUrl = overwriteMetadataUrl + self.hashedFactorNonce = hashedFactorNonce ?? web3AuthClientId + } +} +``` + + + + +### Example + +```swift +do { + let mpcCoreKit = MpcCoreKit( + options: .init( + web3AuthClientId: "YOUR_WEB3AUTH_CLIENT_ID", // Get it from Web3Auth Dashboard, + web3AuthNetwork: .SAPPHIRE_MAINNET, + // Please check the storage configuration above + storage: UserStorage() + ) + ) +} catch let error { + // Handle error +} +``` diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/install.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/install.mdx new file mode 100644 index 000000000..5eb1c4b93 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/install.mdx @@ -0,0 +1,67 @@ +--- +title: "Installing MPC Core Kit Swift SDK" +sidebar_label: "Install" +description: "Web3Auth MPC Core Kit Swift SDK - Install | Documentation - Web3Auth" +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +import SPM from "@site/src/common/sdk/mpc-core-kit/swift/_spm-installation.mdx"; +import Cocoapods from "@site/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation.mdx"; +import SPMProvider from "@site/src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx"; +import CocoapodsProvider from "@site/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation-provider.mdx"; + +The MPC Core Kit Swift SDK requires a couple of packages for integrating the MPC TSS features and an +additional package for generating MPC TSS signatures. + +## Requirements + +- iOS 14+ +- Xcode 11.4+ / 12.x +- Swift 4.x / 5.x + +## MPC Core Kit Package + +This is the main package that helps you implement Web3Auth's MPC TSS features while giving you the +flexibility to customize the UI and UX of the authentication process. + + + + + + + + + + + + + +## Web3Auth MPC Provider + +This package gives Ethereum compatible signing provider with TSS Signing capabilities. This comes in +handy by providing you with a standard way of retriving user's address and interacting with +blockchain. + +Please note, this package only supports Ethereum. + + + + + + + + + + + + diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/mpc-core-kit-swift.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/mpc-core-kit-swift.mdx new file mode 100644 index 000000000..6fd461680 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/mpc-core-kit-swift.mdx @@ -0,0 +1,186 @@ +--- +title: "Web3Auth MPC Core Kit Swift SDK" +sidebar_label: Overview +description: "Web3Auth MPC Core Kit Swift SDK | Documentation - Web3Auth" +--- + +import TkeyMpcFlowDark from "@site/static/images/tkey-mpc-flow-dark.png"; +import TkeyMpcFlowLight from "@site/static/images/tkey-mpc-flow-light.png"; + +Web3Auth's [mpc-core-kit-swift](https://github.com/Web3Auth/mpc-core-kit-swift) SDK is simple and +easy-to-use SDK, which helps you implement the Web3Auth MPC Features while giving you the +flexibility to customize the UI and UX of the authentication process. + +Compared to other Web3Auth SDKs, such as Plug and Play (PnP) and Single Factor Auth (SFA) SDKs, +where the private key is securely reconstructed on the user's device and used to sign transactions, +the MPC TSS architecture ensures that the private key is never reconstructed for signing. However, +the SDK provides options to export the private key if the user wants to use their account in other +wallets. This approach eliminates vendor lock-in, unlike other MPC solutions. + +Instead, the partial key shares are stored at different locations which are used to generate the +partial signatures. The final signature is generated combining the partial signatures using the TSS. +Since the private key is never reconstructed, it's more secure approach. + +:::info + +The SDK is only available for the [Enterprise Plan](https://web3auth.io/pricing.html). However, you +can test the SDK with all features enabled in the `sapphire_devnet`. + +::: + +## Web3Auth MPC Infrastructure + +The Web3Auth infrastructure is designed to ensure the security of user keys. Instead of being stored +in a single location, the key is divided into multiple parts and distributed across the user's +devices and our Auth Network. This means that the key is always available and never in danger of +being compromised. + +The traditional Web3Auth SDK uses Shamir Secret Sharing (SSS) to dynamically reconstruct the key in +the frontend. However, with the new Web3Auth MPC (Multi Party Computation) architecture, this is no +longer necessary. Instead, partial keys are stored in different locations, and the user's device is +used to make partial signatures for messages and transactions. + +These partial signatures are then combined using the TSS (Threshold Signature Scheme) to create a +final signature, which can be used to make a transaction on the blockchain. The result is a more +secure and user-friendly authentication process that helps to protect against key theft and other +types of security breaches. + +The Threshold Signature Scheme (TSS) is a cryptographic primitive for distributed key generation and +signing. The use of TSS in Web3Auth's Auth Network is a new paradigm that can provide numerous +benefits, especially in terms of security. + + + + + This diagram describes the relationship between the Web3Auth SDK and integrating application + + +As you can notice in this diagram above, the final output, i.e., the User's TSS Account, is +generated in multiple stages within the infrastructure. Since this is a TSS- MPC based +infrastructure, you don't get back a private key, but signatures that can be used to make +transactions on the blockchain. Let's understand each of these stages in detail. + +## Types of Factors + +### Social Login Factor + +This is the primary way for a user to access their account. This step involves authentication of +user using a preferred social login provider. The `idToken` received from the social login provider +here is passed to the Web3Auth Auth Network to generate the TSS Shares in the Nodes. + +By default, these nodes have a threshold of 3/5 that can be customized according to requirements. +When a user logs in, the Auth Network generates signatures corresponding to the TSS Shares in the +nodes and returns them to the user's end. These signatures are then used alongside other shares to +generate the final TSS Account signatures. + +### Hashed Cloud Factor + +The MPC Core Kit SDK starts in a 2/2 flow by default. This means when user's logs in, a social login +factor is generated and at the same time SDK will generate a hashed cloud factor. This hashed cloud +factor is derived on the front end and stored in the encrypted metadata server. Please refer to the +above architecture to understand more about factors. + +This is done to make sure the user can access their account from any device without having to +generate a new factor. The hashed cloud factor is deleted when the user enables the MFA. + +### Device Factor (Factor Index: 2) + +This is the second factor used to access the user's account. This step involves the generation of a +TSS Share on the user's device and using that to generate a final signature for the TSS Account +alongside the social login factor. This ensures the user logs in using their trusted device and +maintains a proper non-custodial setup. + +### Backup Factor (Factor Index: 3) + +A user has a choice to generate as many backup factors as needed to access their account. This step +involves the generation of a TSS Share on the user's end and storing them in whichever location they +prefer. This share can be used similarly to the device share to generate a final signature for the +TSS Account alongside the social login and/or device factors. + +When user changes their device, their device factor will not be present on the new device. In that +case, the user can use the backup factor to access their account. You can choose to define the +backup factor of your choice like social recovery, Email OTP, SMS OTP, Authenticator app, etc. + +## Threshold + +The threshold is the minimum number of shares required to generate a final signature for the TSS +Account. By default, the Auth Network requires 3 out of 5 shares (3/5) to generate a signature. This +means that out of the 5 shares distributed across different nodes, any 3 shares can be combined to +create the final signature. This setup ensures high availability and security, as it allows for some +shares to be unavailable or compromised without affecting the overall system. + +On the user's device front, the default threshold is set to 2 out of 3 shares (2/3). This means that +out of the 3 shares available on the user's device, any 2 shares can be used to generate the final +signature. This setup provides a balance between security and ease of access, ensuring that the user +can still access their account even if one share is unavailable. + +Only the user level threshold can can be customized according to the requirements. The Auth Network +threshold is fixed at 3/5. + +Please note that when a user logs in for the first time, the threshold is set to 2 out of 2 shares +(2/2). This means that both shares are required to generate the final signature. After the user +enables the MFA flow, the threshold is set to 2 out of 3 shares (2/3), providing an additional layer +of security. + +## Components of a Factor + +### TSS Shares + +The TSS Shares are the main component needed for the generation of the final working signature of +the user. These shares are generated using distributed key generation(DKG) and are stored in the +Auth Network and the user's device. Since these shares are generated using MPC, they are **never +reconstructed** and always stay decentralized and secure. + +We've included a function in the SDK that lets you reconstruct the TSS Key from the shares. Just a +heads-up, this function is marked as unsafe, so it's best to use it with extra layers of security. +For example, only make this function available when MFA is enabled and ask the user to input their +MFA share while exporting. + +### Metadata Key & Shares + +The Metadata Key closely mimics the storage of the TSS Shares. The only difference is that the +metadata key is always reconstructed and used for its encryption/decryption capabilities. It +utilizes basic Shamir's Secret Sharing and is initially generated on a user's front end. The +metadata key is utilized for the encryption/decryption of the user metadata stored in the Web3Auth +Metadata Server. + +One metadata share gives you the **read** access to the metadata server, while two or more (as the +threshold is reached) give you the **write** access. + +### Factor Keys + +To enable refresh, deletion, and rotational capabilities on the TSS Key, we also introduce factor +keys. Factor Keys are randomly generated keys unique to each factor-generated user's device and +backups, like users' phones, chrome extensions, on their cloud, assisting third parties, etc. + +As share to the TSS Key and/or Metadata Key may rotate, Factor Keys allow a consistent secret to be +saved in these different locations. + +## Understanding the SDK Flow + +By default, for a new user, the MPC Core Kit SDK starts in a 2/2 flow. This means that the user will +have to generate a social login factor and a hashed cloud factor. This hashed cloud factor is +derived on the SDK front end and stored in the encrypted metadata server. This enables the user to +start the login process from any device without creating an MFA factor. + +This is done to make sure the user can access their account from any device without having to +generate a new factor. However, this makes the initial onboarding, semi-custodial. To make the +account completely non-custodial, the user can use the enable MFA feature to generate a device and +backup factor and delete the hashed cloud factor. This makes the user's account completely +non-custodial in 2/3 setup and enables them to access their account from any device using the backup +share. Device share is saved on a trusted device and can be used to access the account from that +device seamlessly without having to generate a new factor. + +## Resources + +- [Troubleshooting](/troubleshooting): Find quick solutions to common issues faced by developers. + +- [Source Code](https://github.com/web3auth/mpc-core-kit-swift): Web3Auth is open sourced. You can + find the source code on our GitHub repository. + +- [Community Support Portal](https://web3auth.io/community): Join our community to get support from + our team and other developers. diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/evm.mdx similarity index 99% rename from docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx rename to docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/evm.mdx index 87551ec15..67f2e6f9f 100644 --- a/docs/sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm.mdx +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/evm.mdx @@ -1,6 +1,5 @@ --- title: Ethereum Signing Provider - description: "Ethereum Signing Provider for EVM Compatible Chains | Documentation - Web3Auth" --- diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/providers.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/providers.mdx new file mode 100644 index 000000000..b9babfcb6 --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/providers/providers.mdx @@ -0,0 +1,10 @@ +--- +title: Providers for MPC Core Kit + +sidebar_label: Overview +description: "Web3Auth Providers | Documentation - Web3Auth" +--- + +import Content from "@site/src/common/sdk/providers/_providers-mpc.mdx"; + + diff --git a/docs/sdk/mpc-core-kit/mpc-core-kit-swift/usage.mdx b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/usage.mdx new file mode 100644 index 000000000..307025d6e --- /dev/null +++ b/docs/sdk/mpc-core-kit/mpc-core-kit-swift/usage.mdx @@ -0,0 +1,404 @@ +--- +title: "Usage of MPC Core Kit Swift SDK" +sidebar_label: "Usage" +description: "Web3Auth MPC Core Kit Swift SDK - Usage | Documentation - Web3Auth" +--- + +Once you've installed and successfully initialized `MpcCoreKit`, you can use it to authenticate your +users, add factors to their account, generate TSS signatures for transactions and interact with the +blockchain. + +## Functionality Overview + +| Method Name | Description | +| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| [loginWithJWT](#log-in-with-jwt) | Logs in the user with a JWT-based ID Token. We recommend using this method to authenticate users for better performance. | +| [loginWithOAuth](#log-in-with-oauth) | Logs in the user using OAuth Flow, this function underneaths uses the CustomAuth flow to authenticate the user. | +| [inputFactorKey](#log-in-with-existing-factor) | This method can be used to login with the exisitng factor key, for instance when threshold is not satisfied. | +| [logout](#logout) | This methods logs out the user and invalidates the session. | + +:::info Get help with Authentication + +Check out the [**Authentication**](/sdk/mpc-core-kit/mpc-core-kit-ios/authentication) section of the +SDK Reference to learn more about these functions. + +::: + +### Manual Sync Method + +This method enables you to have a fined grained control over the API calls made to the metadata +server from the SDK. + +| Method Name | Description | +| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [commitChanges](#commit-changes) | Commits the changes made to the user's account while in manual sync mode. To use this function, you'll need to enable the manual sync while [configuring the instance](./initialize#configure-instance). | + +### Factor Handling Methods + +| Method Name | Description | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [enableMFA](#enable-mfa) | By default, the SDK starts with 2/2 flow unless the `disableHashedFactorKey` is set to true during initialisation. To make the flow completely non-custodial, and have 2/3 flow, you can use the enableMFA function. | +| [createFactor](#create-factor) | Creates a new TSS Factor for the user's account to increase. You can configure the type of factor, it can either be a device factor, or backup factor. | +| [deleteFactor](#delete-factor) | This method allows you to deletes a TSS factor for the user. Please make sure user has enough factors to recover the account. | +| [getCurrentFactorKey](#get-current-factor-key) | This methods returns the current factor key used along with social factor to log in. | +| [getDeviceFactor](#get-device-factor) | This methods returns the device factor if available. | +| [setDeviceFactor](#set-device-factor) | This methods allows you to set the device factor for the user. | +| [getAllFactorPubs](#get-all-factor-pubs) | This methods returns the list of all factor pub keys for the user's account. | + +### User & Wallet Account Methods + +| Method Name | Description | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| [getPubKey](#get-secp256k1-public-key) | Returns the TSS PubKey in SEC1 format which can be used for the secp256k1 curve to derive the EOA address. | +| [getUserInfo](#get-user-info) | Returns the user information such as name, verifier, email, and other details. | +| [getKeyDetails](#get-key-details) | Returns the key details for the user account, these key details has information like total factors, and threshold. | + +### Additional Helper Methods + +| Method Name | Description | +| --------------------------------- | --------------------------------------------------------------------------------------------- | +| [mnemonicToKey](#mnemonic-to-key) | This method helps you to convert 24 word mnemonic(seed phrase) into corresponding factor key. | +| [keyToMnemonic](#key-to-mnemonic) | This method helps you to convert the factor key to corresponding 24 mnemonic. | + +## Authentication Methods + +### Log in with OAuth + +This method helps to log in the user using Single Page Application (SPA) flow. You can choose your +preferred social auth providers with 0Auth login flow. Please refer to the +[authentication section](/sdk/mpc-core-kit/mpc-core-kit-ios/authentication/login-oauth) section for +more details. + +### Log in with JWT + +Logs in the user with a JWT-based ID Token. We recommend using this method to authenticate users for +better performance. For this method, you'll have to manage the authentication yourself, and Web3Auth +will only verify the idToken passed. Please refer to the +[authentication section](/sdk/mpc-core-kit/mpc-core-kit-ios/authentication/login-jwt) for more +details. + +### Log in with Existing Factor + +This method can be used to input the factor key, for instance when threshold is not satisfied. For +example, if user's device factor is not present, this method can be used to input the back up factor +key, and recover the account. If the factor key is correct, the SDK initializes the user's account +and logs them in. + +If you want to change the factor key in the current state of the SDK, you can use this method. +Please make sure to convert your factor key to BN before passing it to this method. + +The function takes the factor key in HEX format as an argument. + +```swift +do { + // Use the existing MPCCoreKit instance + try await mpcCoreKit.inputFactor( + factorKey: "FACTOR_KEY_IN_HEX" + ) +} catch { + // Handle error +} +``` + +### Logout + +This method logs out the user, and invalidates the session. + +```swift +do { + // Use the existing MPCCoreKit instance + try await mpcCoreKit.logout(); +} catch { + // Handle error +} +``` + +## Manual Sync Method + +### Commit Changes + +This method helps you syncs the local metadata with the Web3Auth's Metadata server. This function is +only to be used while in manual sync mode. This enables you to have a fined grained control over the +API calls made to the metadata server from the SDK. + +It is especially useful when you want to handle the factors and keys of the user's account in a more +controlled manner, enabling a much faster and safer experience for the User. + +Please note that if you don't commit the local changes, the user's account will not sync with the +metadata server, and any changes will be lost when the app is closed. + +```swift +do { + // Use the existing MPCCoreKit instance + try await mpcCoreKit.commitChanges(); +} catch { + // Handle error +} +``` + +## Factor Handling Methods + +### Enable MFA + +By default, the SDK starts with semi-custodial 2/2 flow unless the `disableHashedFactorKey` is set +to true during initialisation. To make the flow completely non-custodial, and have 2/3 flow, you can +use the enableMFA method. + +It creates a device factor and stores it in the local storage. Along with that, it also creates a +backup factor and returns it to the user. The default backup factor is 24 words mnemonic. You can +configure the backup factor to be social recovery, password recovery, authenticator app, or back up +of your choice. + +Most importantly, this method also deletes the Hashed Factor Key enabling a non-custodial flow. The +method takes in `MFARecoveryFactor` which allows you to configure the backup factor of your choice. + +#### MFARecoveryFactor Parameters + +| Name | Description | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `factorKey?` | A new hex string to be used for the back up factor. You can pass the hex generated from social recovery, or any other back up factor like authenticator app. By default, a random BN is generated and converted to hex format. | +| `factorTypeDescription` | The share description to be stored in Metadata. Default value is `.Other`. Available values are `.HashedShare`,`.SecurityQuestions`, `.DeviceShare`, `.SeedPhrase`, `.PasswordShare`, `.SocialShare`, and `.Other` | +| `additionalMetadata` | You can use this parameter if you wish to store additional metadata for the factor. | + +#### Usage + +```swift +do { + // Use the existing MPCCoreKit instance + let backupFactor = try await mpcCoreKit.enableMFA() +} catch { + // Handle error +} +``` + +### Create Factor + +To create a factor, you can use the `createFactor` method. This is a low-level function to help you +to create a backup factor key based on the type of TSS Share you want to create. You can pass your +own factor key or let the SDK generate one for you. + +This method helps you add additional factor to the user's account such as device factor, social +recovery, SMS OTP, authenticator, and more. + +:::danger Note + +You shouldn't create too many factors, we recommend a **maximum of 7 factors**. + +::: + +#### Parameters + +| Name | Description | +| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tssShareIndex` | Takes in TSS Share type to define the type of share to be created. Available values are `.device`, and `.recovery`. | +| `factorKey?` | A hex string to be used for creating the factor factor. You can pass the hex generated from social recovery, or any other back up factor like authenticator app. By default, a random BN is generated and converted to hex string. | +| `factorDescription` | The share description to be stored in Metadata. Available values are `.HashedShare`,`.SecurityQuestions`, `.DeviceShare`, `.SeedPhrase`, `.PasswordShare`, `.SocialShare`, `.Other`. Default value is `.Other`. | +| `additionalMetadata` | You can use this parameter if you wish to store additional metadata for the factor. | + +#### Usage + +```swift +do { + // Use the existing MPCCoreKit instance + let factor = try await mpcCoreKit.createFactor( + tssShareIndex: .DEVICE, + factorKey: nil, + factorDescription: .DeviceShare + ) +} catch { + // Handle error +} +``` + +### Delete Factor + +To delete a factor you can use the `deleteFactor` method. This method helps you delete the factor, +respective to the factor pub provided for the user's account. + +You can get the factor pubs by using the [getAllFactorPubs](#get-all-factor-pubs) method. It will +throw an error if you try to delete the factor that is currently active within the state of the SDK. + +Use the [inputFactorKey](#log-in-with-existing-factor) method to change the factor key in the +current state of the SDK before deleting the current active factor. + +#### Parameters + +| Name | Description | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `deleteFactorPub` | The PubKey for the factor you want to delete. The SDK internally will retrieve the corresponding factory key and delete it. | +| `factorKey?` | The factorKey of the factor you want to delete. | + +#### Usage + +```swift +do { + // Use the existing MPCCoreKit instance + try await mpcCoreKit.deleteFactor( + deleteFactorPub: "FACTOR_PUB_KEY_IN_HEX" + ) +} catch { + // Handle error +} +``` + +### Get Current Factor Key + +To retrieve the currently active factor within the state of the SDK you can use the +`getCurrentFactorKey` method. + +```swift +do { + // Use the existing MPCCoreKit instance + let currentFactorKey = try await mpcCoreKit.getCurrentFactorKey(); +} catch { + // Handle error +} +``` + +### Get Device Factor + +To retrieve the device factor key hex string, you can use the `getDeviceFactor` method. The method +will throw an error if the device factor is not available. + +To set the device factor, you can use the [setDeviceFactor](#set-device-factor) method. + +```swift +do { + // Use the existing MPCCoreKit instance + let deviceFactor = try await mpcCoreKit.getDeviceFactor(); +} catch { + // Handle error +} +``` + +### Set Device Factor + +To set the device factor, you can use the `setDeviceFactor` method. The method only stores the +factor key in the storage layer, and does not create a factor. To create a new device factor, you +can use the [createFactor](#create-factor) method. Once the factor is created successfully, you can +store the factor key in the storage layer using this method. + +```swift +do { + let deviceFactor = try await mpcCoreKit.createFactor( + tssShareIndex: .DEVICE, + factorKey: nil, + factorDescription: .DeviceShare + ) + + // Use the existing MPCCoreKit instance + try await mpcCoreKit.setDeviceFactor( + deviceFactor: deviceFactor + ) +} catch { + // Handle error +} +``` + +### Get All Factor Pubs + +This method helps you to retrieve the list of all factors PubKey for the account. This method is +useful when you want to delete a factor, or check if the factor is present in the account. + +Please note, this method only returns list of factors PubKey, and doesn't contain the share +description and additional metadata. Please use the [getKeyDetails](#get-key-details) method to +retrieve the share description and additional metadata. + +```swift +do { + // Use the existing MPCCoreKit instance + let factorPubs = try await mpcCoreKit.getAllFactorPubs(); +} catch { + // Handle error +} +``` + +## User & Wallet Account Methods + +### Get Secp256k1 Public Key + +To retrieve the Secp256k1 public key, you can use the `getPubKey` method. You can use this public +key to derive the EOA address. + +```swift +do { + // Use the existing MPCCoreKit instance + let pubKey = try await mpcCoreKit.getPubKey(); +} catch { + // Handle error +} +``` + +### Get User Info + +To retrive the user's information you can use the `getUserInfo` method. The methods returns the +user's information based on the idToken, and Web3Auth metadata like verifier, verifier Id. + +```swift +// Use the existing MPCCoreKit instance +let userInfo: UserInfo? = mpcCoreKit.getUserInfo() +``` + +### Get Key Details + +To retieve the MPCKeyDetails for the user account you can use the `getKeyDetails` methods. These key +details has information like total factors, required factors, and threshold. Learn more about the +[MpcKeyDetails](#mpckeydetails). + +#### Usage + +```swift +do { + // Use the existing MPCCoreKit instance + let keyDetails: MpcKeyDetails = try await mpcCoreKit.getKeyDetails() +} catch { + // Handle error +} +``` + +#### MpcKeyDetails + +| Name | Description | +| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tssPubKey` | The TSS PubKey, you can also get the TSS PubKey using the [getPubKey](#get-secp256k1-public-key) method. The PubKey is in SEC1 format. | +| `metadataPubKey` | Holds the information for the metadataPubKey. | +| `requiredFactors` | Defines the number of factors required to access the account after authentication flow. User won't be able to access the account, unless the requiredFactors is 0 | +| `threshold` | Defines the number of threshold set by the user, for instance is it 2/2. or 2/n. By default, the SDK starts with 2/2 flow. | +| `shareDescriptions` | Holds a json encoded string of the share descriptions. | +| `totalShares` | Returns the total number shares for the account. | +| `totalFactors?` | Defines the total factors created by the user. | + +## Mnemonic Conversion Methods + +### Mnemonic to Key + +To convert 24 word mnemonic(seed phrase) into corresponding factor key, you can use the +`mnemonicToKey` method. This is helpful when you want to convert the 24 words mnemonic backup factor +to factor key. + +```swift +do { + // Use the existing MPCCoreKit instance + let factorKeyHex = try mpcCoreKit.mnemonicToKey( + shareMnemonic: "YOUR_24_WORD_MNEMONIC" + ); +} catch { + // Handle error +} +``` + +### Key to Mnemonic + +To convert the factor key hex string to a 24 words mnemonic, you can use the `keyToMnemonic` method. + +```swift +do { + let deviceFactorKey = try await mpcCoreKit.getDeviceFactor(); + // Use the existing MPCCoreKit instance + let deviceFactorInMnemonics = try mpcCoreKit.keyToMnemonic( + factorKey: deviceFactorKey + ); +} catch { + // Handle error +} +``` diff --git a/sidebars.ts b/sidebars.ts index f8274e2b5..fc2dcdae2 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -9,6 +9,7 @@ import { unity, unreal, js, + swift, } from "./src/common/SDKOptions"; import { getPnPVersion, getSFAVersion, getMPCCoreKitVersion } from "./src/common/versions"; @@ -107,6 +108,7 @@ function mpcckTopNavButton(selectedSDK: string): string { var mpcCoreKitSDKs = { [js]: `${baseUrl}sdk/mpc-core-kit/mpc-core-kit-js`, [reactnative]: `${baseUrl}sdk/mpc-core-kit/mpc-core-kit-react-native`, + [swift]: `${baseUrl}sdk/mpc-core-kit/mpc-core-kit-swift`, }; if (mpcCoreKitSDKs.hasOwnProperty(selectedSDK)) { delete mpcCoreKitSDKs[selectedSDK]; @@ -131,6 +133,7 @@ function mpcckTopNavButton(selectedSDK: string): string { v${sdkVersion}
    @@ -1787,6 +1790,47 @@ const sidebars: SidebarsConfig = { }, ...sdkQuickLinks, ], + sdk_core_kit_mpc_swift: [ + { + type: "html", + value: mpcckTopNavButton(swift), + defaultStyle: true, + }, + "sdk/mpc-core-kit/mpc-core-kit-swift/mpc-core-kit-swift", + "sdk/mpc-core-kit/mpc-core-kit-swift/install", + "sdk/mpc-core-kit/mpc-core-kit-swift/initialize", + { + type: "category", + label: "Authentication", + items: [ + "sdk/mpc-core-kit/mpc-core-kit-swift/authentication/authentication", + "sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-jwt", + "sdk/mpc-core-kit/mpc-core-kit-swift/authentication/login-oauth", + ], + }, + // "sdk/mpc-core-kit/mpc-core-kit-swift/signing", + "sdk/mpc-core-kit/mpc-core-kit-swift/usage", + // "sdk/mpc-core-kit/mpc-core-kit-swift/examples", + { + type: "category", + label: "Providers", + items: [ + "sdk/mpc-core-kit/mpc-core-kit-swift/providers/providers", + "sdk/mpc-core-kit/mpc-core-kit-swift/providers/evm", + ], + }, + { + type: "link", + label: "Support Forum", + href: "https://web3auth.io/community/c/help-core-kit/mpc-core-kit/33", + }, + { + type: "link", + label: "Release Notes", + href: "https://github.com/Web3Auth/mpc-core-kit-swift/releases", + }, + ...sdkQuickLinks, + ], sdk_core_kit_mpc_react_native: [ { type: "html", @@ -1808,12 +1852,6 @@ const sidebars: SidebarsConfig = { "sdk/mpc-core-kit/mpc-core-kit-react-native/providers/evm", ], }, - { - type: "category", - label: "Providers", - items: ["sdk/mpc-core-kit/mpc-core-kit-ios/providers/evm"], - }, - // "sdk/mpc-core-kit/mpc-core-kit-ios/usage", { type: "link", label: "Support Forum", @@ -1886,27 +1924,6 @@ const sidebars: SidebarsConfig = { }, ], }, - { - type: "category", - label: "MPC Core Kit iOS SDK", - items: [ - "sdk/core-kit/mpc-core-kit-ios/mpc-core-kit-ios", - "sdk/core-kit/mpc-core-kit-ios/install", - "sdk/core-kit/mpc-core-kit-ios/initialize", - "sdk/core-kit/mpc-core-kit-ios/authentication", - "sdk/core-kit/mpc-core-kit-ios/usage", - { - type: "link", - label: "Support Forum", - href: "https://github.com/Web3Auth/mpc-core-kit-swift/releases", - }, - { - type: "link", - label: "Release Notes", - href: "https://github.com/Web3Auth/mpc-core-kit-swift/releases", - }, - ], - }, { type: "category", label: "tKey iOS SDK", diff --git a/src/common/SDKOptions.ts b/src/common/SDKOptions.ts index 6d4b9bcf4..39b3730a6 100644 --- a/src/common/SDKOptions.ts +++ b/src/common/SDKOptions.ts @@ -6,6 +6,7 @@ export const web = "Web"; export const android = "Android"; export const ios = "iOS"; export const js = "Javascript"; +export const swift = "Swift"; export const macOS = "macOS"; export const reactnative = "React Native"; export const rnbare = "React Native Bare"; diff --git a/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation-provider.mdx b/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation-provider.mdx new file mode 100644 index 000000000..e69de29bb diff --git a/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation.mdx b/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation.mdx new file mode 100644 index 000000000..79abc1394 --- /dev/null +++ b/src/common/sdk/mpc-core-kit/swift/_cocoapods-installation.mdx @@ -0,0 +1,7 @@ +1. Open the Podfile, and add the MPC Provider Swift pod: + +```sh +pod 'MPCProviderSwift', '~> 1.0.0' +``` + +2. Once added, use `pod install` command to install the MPC Provider Swift pod. diff --git a/src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx b/src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx new file mode 100644 index 000000000..511464ec4 --- /dev/null +++ b/src/common/sdk/mpc-core-kit/swift/_spm-installation-provider.mdx @@ -0,0 +1,7 @@ +1. Open your project in Xcode. +2. Navigate to File -> Add Package Dependencies +3. When prompted, paste the Web3Auth MPC Provider Swift SDK repository: + + ```sh + https://github.com/tkey/MPCProviderSwift + ``` diff --git a/src/common/sdk/mpc-core-kit/swift/_spm-installation.mdx b/src/common/sdk/mpc-core-kit/swift/_spm-installation.mdx new file mode 100644 index 000000000..729648a19 --- /dev/null +++ b/src/common/sdk/mpc-core-kit/swift/_spm-installation.mdx @@ -0,0 +1,7 @@ +1. Open your project in Xcode. +2. Navigate to File -> Add Package Dependencies +3. When prompted, paste the Web3Auth MPC Core Kit Swift SDK repository: + + ```sh + https://github.com/Web3Auth/mpc-core-kit-swift + ``` diff --git a/src/common/versions.ts b/src/common/versions.ts index 46d133bff..a332ec47c 100644 --- a/src/common/versions.ts +++ b/src/common/versions.ts @@ -17,8 +17,9 @@ export const tkeyAndroidVersion = `0.0.5`; export const tkeyIOSVersion = `0.0.4`; export const mpcCoreKitJSVersion = `3.4.x`; export const mpcCoreKitReactNativeVersion = `1.0.0`; +export const mpcCoreKitSwiftVersion = `1.0.0`; -import { web, android, ios, js, reactnative, flutter, unity, unreal } from "./SDKOptions"; +import { web, android, ios, js, reactnative, flutter, unity, unreal, swift } from "./SDKOptions"; export function getPnPVersion(platform: string) { if (platform === web) { @@ -66,4 +67,7 @@ export function getMPCCoreKitVersion(platform: string) { if (platform === reactnative) { return mpcCoreKitReactNativeVersion; } + if (platform === swift) { + return mpcCoreKitSwiftVersion; + } } diff --git a/src/components/SDKReferenceCards/index.tsx b/src/components/SDKReferenceCards/index.tsx index 4493669b7..cc95f5e5a 100644 --- a/src/components/SDKReferenceCards/index.tsx +++ b/src/components/SDKReferenceCards/index.tsx @@ -790,9 +790,6 @@ export const mpccorekitjs = (

    MPC Core Kit JS SDK

    -

    - Get the Web3Auth full TSS-MPC Infrastructure deeply integrated within your application. -

    ); -export const mpccorekitreactnative = ( +export const mpccorekitmobile = (
    -

    MPC Core Kit React Native SDK

    +

    MPC Core Kit Mobile SDKs

    Designed for projects that require a tailored approach to authentication, providing the tools and flexibility necessary to build advanced, secure, and integrated authentication systems.

    - Works for React Native & Expo environments. + Get the Web3Auth full TSS-MPC Infrastructure deeply integrated within your application.

    {mobileIconsWithoutFlutter}
    @@ -840,9 +837,6 @@ export const mpccorekitreactnative = (
    - -
    -); - -export const mpccorekitios = ( -
    -
    -

    MPC Core Kit Swift SDK

    -

    - Get the Web3Auth full TSS-MPC Infrastructure deeply integrated within your native iOS - application. -

    - {mobileIconsWithoutFlutter} -
    -