Overview

Getting Started

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic publishable key.

Installation

Add magic_sdk to your pubspec.yaml:
YAML
dependencies:
  flutter:
    sdk: flutter
  magic_sdk: ^6.0.1
Run the following command to install dependencies:
Bash
dart pub get

Performance improvement (optional)

We use service workers for for better performance on web3 operations. They are enabled by default on Android, but if you’d like to take advantage of this performance boost on iOS as well, you’d have to enable app bound domains. To do that, add the following to your Info.plist and rebuild your app:
plist
<key>WKAppBoundDomains</key>
<array>
  <string>https://auth.magic.link</string>
</array>

Constructor

Magic() Magic(apiKey, {MagicLocale locale})
ParameterTypeDefinition
apiKeyStringYour publishable API Key retrieved from the Magic Dashboard.
locale?MagicLocaleCustomize the language of Magic’s modal, email and confirmation screen. See Localization for more.
Magic.eth(String apiKey, { required EthNetwork network, MagicLocale locale})
ParameterTypeDefinition
networkEthNetworkA representation of the connected Ethereum network (one of: mainnet or goerli).
Magic.custom(String apiKey, { required String rpcUrl, int? chainId, MagicLocale locale})
ParameterTypeDefinition
rpcUrlStringA URL pointing to your custom Ethereum Node.
chainId?intSome Node infrastructures require you to pass an explicit chain ID. If you are aware that your Node requires this configuration, pass it here as an integer.

Initialization

Dart
import "package:magic_sdk/magic_sdk.dart";

// Construct with an API key:
Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Construct with an API key and locale:
Magic.instance = Magic("PUBLISHABLE_API_KEY", locale: MagicLocale.en_US);

// Construct with an API key and network:
Magic.instance = Magic.eth("PUBLISHABLE_API_KEY", network: EthNetwork.goerli);

// Construct with an API key and custom node options:
Magic.instance = Magic.custom("PUBLISHABLE_API_KEY", rpcUrl: "https://your.custom.url/", chainId: 1);

Auth Module

The Auth Module and its members are accessible on the Magic SDK instance by the auth property.

loginWithSMS

Authenticate a user passwordlessly using a one-time code sent to the specified phone number. List of Currently Blocked Country Codes Public Methods Future<String> loginWithSMS({ required String email })
ParameterTypeDefinition
phoneNumberStringThe phone number to log in with.
Returns
  • Future<string> The future resolves upon authentication request success and throws with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.
Example
Dart
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// log in a user by using text input Controller
try {
  var magic = Magic.instance;
  await magic.auth.loginWithSMS(phoneNumber: textController.text);
} catch {
  // Handle errors if required!
}

loginWithEmailOTP

Authenticate a user passwordlessly using an email one-time code sent to the specified user’s email address. Public Methods Future<String> loginWithEmailOTP({ required String email })
ParameterTypeDefinition
emailStringThe user email to log in with.
Returns
  • Future<string> The future resolves upon authentication request success and throws with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// log in a user by using text input Controller
try {
  var magic = Magic.instance;
  await magic.auth.loginWithEmailOTP(email: textController.text);
} catch {
  // Handle errors if required!
}

User Module

The User Module and it’s members are accessible on the Magic SDK instance by the user property.

updateEmail

Initiates the update email flow that allows a user to change their email address. Arguments Future<bool> updateEmail({required String email, bool showUI = true})
ParameterTypeDefinition
emailStringThe new email to update to.
showUI?BooleanIf true, shows an out-of-the-box pending UI which includes instructions on which step of the confirmation process the user is on. Dismisses automatically when the process is complete.
Returns
  • Future<boolean>: The future resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Initiates the flow to update a user's current email to a new one.
try {
  var magic = Magic.instance;

  /* Assuming user is logged in */
  await magic.user.updateEmail(email: '[email protected]');
} catch {
  // Handle errors if required!
}

/**
 * Initiates the flow to update a user's current email to a new one,
 * without showing an out-of-the box UI.
 */
try {
  var magic = Magic.instance;

  /* Assuming user is logged in */
  await magic.user.updateEmail({ email: '[email protected]', showUI: false });
} catch {
  // Handle errors if required!
}

getIdToken

Generates a Decentralized Id Token which acts as a proof of authentication to resource servers. Arguments Future<String> getIdToken({int lifespan = 900})
ParameterTypeDefinition
lifespan?intWill set the lifespan of the generated token. Defaults to 900s (15 mins)
Returns
  • Future<string>: Base64-encoded string representation of a JSON tuple representing [proof, claim]
Example
Dart
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
var m = Magic.instance;
const idToken = await m.user.getIdToken();
} catch {
// Handle errors if required!
}

generateIdToken

Generates a Decentralized Id Token with optional serialized data. Arguments Future<String> generateIdToken({int lifespan = 900, String attachment = 'none'})
ParameterTypeDefinition
lifespan?intWill set the lifespan of the generated token. Defaults to 900s (15 mins)
attachment?StringWill set a signature of serialized data in the generated token. Defaults to "none"
Returns
  • Future<string>: Base64-encoded string representation of a JSON tuple representing [proof, claim]
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
  var m = Magic.instance;

  const idToken = await m.user.generateIdToken({ attachment: 'SERVER_SECRET' });
} catch {
  // Handle errors if required!
}

getInfo

Retrieves information for the authenticated user. Arguments
  • None
Returns
  • Future<UserInfo>: an object containing the issuer, email and cryptographic public address of the authenticated user
ValueTypeDefinition
issuerStringThe Decentralized ID of the user. In server-side use-cases, we recommend this value to be used as the user ID in your own tables.
emailStringEmail address of the authenticated user.
publicAddressStringThe authenticated user’s public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.
isMfaEnabledBooleanA boolean indicating if user has multi-factor authentication enabled.
recoveryFactors_ List<RecoveryFactor>
_ value
* type
Example
Dart
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
var m = Magic.instance
await m.user.getInfo();
} catch {
// Handle errors if required!
}

isLoggedIn

Checks if a user is currently logged in to the Magic SDK. Arguments
  • None
Returns
  • Future<Boolean>
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

try {
  const isLoggedIn = await m.user.isLoggedIn();
  debugPrint(isLoggedIn); // => `true` or `false`
} catch {
  // Handle errors if required!
}

logout

Logs out the currently authenticated Magic user Arguments
  • None
Returns
  • Future<Boolean>
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

try {
  await m.user.logout();
  debugPrint(await m.user.isLoggedIn()); // => `false`
} catch {
  // Handle errors if required!
}

OAuth Module

The OAuth Module and it’s members are accessible on the Magic SDK instance by the oauth property.

loginWithPopup

Starts the OAuth 2.0 login flow. Arguments
  • provider (String): The OAuth provider being used for login
  • redirectURI (String): A URL a user is sent to after they successfully log in
  • scope? (Array): Defines the specific permissions an application requests from a user
Returns
  • None
Valid Providers
NameArgument
Google'google'
Facebook'facebook'
Twitter'twitter'
Apple'apple'
Discord'discord'
GitHub'github'
LinkedIn'linkedin'
Bitbucket'bitbucket'
GitLab'gitlab'
Twitch'twitch'
Microsoft'microsoft'
Example
Dart
import 'package:magic_sdk/magic_sdk.dart';
import 'package:magic_ext_oauth/magic_ext_oauth.dart';

Magic.instance = Magic("YOUR_PUBLISHABLE_KEY");
Magic magic = Magic.instance;

var configuration = OAuthConfiguration(provider: OAuthProvider.GITHUB, redirectURI: 'YOUR_APP_SCHEME://');
var result = await magic.oauth.loginWithPopup(configuration);

Resources