Javascript SDK

Javascript SDK

#Version

This document is for magic-sdk version 13.2.0 and above. ⁠You can view the open-source repository for this SDK on Github and all versioned releases on NPM.

Note: If you are looking for documentation for a version of magic-sdk below 13.2.0 that utilizes the magic.connect namespace, please refer to the older documentation for the SDK here.

#Configuration & Setup

In order to use the Magic Javascript SDK, you must get a valid publishable API key from the Magic Dashboard. In the examples below, replace the value of YOUR_API_KEY with the value you get from the dashboard. See the quickstart section for more details and installation instructions.

#Constructor

#Magic()

Configure and construct your Magic SDK instance.

#Arguments

  1. apiKey: String : Your publishable API Key retrieved from the Magic Dashboard
  2. options?: String | Object : A representation of the connected Ethereum network (one of: mainnet, goerli) or a custom object with your custom EVM node configurations.
    • Default: 'mainnet' : Will connect to Ethereum's mainnet network.
    • options.network: Object
      • options.network.rpcUrl: String : A URL pointing to your custom EVM Node.
      • options.network.chainId?: Number : If your node infrastructure requires you to pass an explicit chain ID, you can use this parameter to do so.
      • options.thirdPartyWalletOptions?: Object : An object with the Coinbase Wallet and or Wallet Connect sdk initialization parameters (required if either of these two wallets are enabled). This option is available as of magic-sdk@14.0.0.

#Example

Use presets for Ethereum

Javascript
01import { Magic } from "magic-sdk"
02
03const magic = new Magic('YOUR_API_KEY', { 
04  network: 'goerli', // connect to Ethereum Testnet!
05});

Use Polygon, Optimism or custom RPC URLs

Javascript
01import { Magic } from "magic-sdk"
02
03const customNodeOptions = {
04  rpcUrl: 'https://polygon-rpc.com', // your ethereum, polygon, or optimism mainnet/testnet rpc URL
05  chainId: 137 // corresponding chainId for your rpc url
06}
07
08const magic = new Magic('YOUR_API_KEY', { 
09  network: customNodeOptions, // connected to Polygon Mainnet!
10});

#Wallet Module Methods

All methods below are namespaced to the magic.wallet module.

#getProvider()

This method is introduced in magic-sdk@14.0.0 and must be used to get the current provider if third party wallets are enabled. Otherwise, we suggest using magic.rpcProvider.

#Returns

  1. Object : The rpc provider of the wallet a user is currently logged in with (MetaMask, Coinbase Wallet, Wallet Connect, or Magic).

Important: To ensure rpc requests are routed to the correct wallet, developers must re-fetch the provider object using getProvider() and re-initialize the web3.js or ethers.js instance any time a user logs in, logs out, or disconnects their wallet.

#Web3.js Example

Javascript
01import { Magic } from "magic-sdk"
02import Web3 from 'web3';
03
04const magic = new Magic('YOUR_API_KEY', { 
05  network: "goerli",
06  thirdPartyWalletOptions: {
07    coinbaseWallet: {
08      sdk: {
09        appName: 'Magic Demo',
10      },
11      provider: {
12        jsonRpcUrl: 'https://rpc.ankr.com/eth_goerli',
13        chainId: 5,
14      },
15    },
16    walletConnect: {
17      rpc: {
18        5: 'https://rpc.ankr.com/eth_goerli',
19      },
20    },
21  }
22});
23
24const provider = await magic.wallet.getProvider();
25
26const web3 = new Web3(provider);
27
28// Listen for events
29web3.currentProvider.on('accountsChanged', handleAccountsChanged);
30web3.currentProvider.on('chainChanged', handleChainChanged);
31web3.currentProvider.on('disconnect', handleDisconnect);
32
33const accounts = await magic.wallet.connectWithUI();

#Ethers.js Example

Javascript
01import { Magic } from "magic-sdk"
02import { ethers } from 'ethers';
03
04const magic = new Magic('YOUR_API_KEY', { 
05  network: "goerli",
06});
07
08const provider = await magic.wallet.getProvider();
09
10const web3Provider = new ethers.providers.Web3Provider(provider);
11
12// Listen for events
13web3Provider.on('accountsChanged', handleAccountsChanged);
14web3Provider.on('chainChanged', handleChainChanged);
15web3Provider.on('disconnect', handleDisconnect);
16
17const accounts = await magic.wallet.connectWithUI();

#getInfo()

Get information about the wallet the use is currently logged in with. User must be signed in for this method to return or else it will throw an error.

#Returns

  1. Object : Information about the wallet the user is currently signed in with.
    • walletType: 'magic'|'metamask'|'coinbase_wallet'|'wallet_connect'

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03// after user has already logged in
04const walletInfo = await magic.wallet.getInfo();
05console.log(walletInfo); // { walletType: "magic" | "metamask" | "coinbase_wallet" | "wallet_connect" }

#connectWithUI()

Request the user to connect their wallet to the dapp.

#Returns

  1. String[] : An array of user accounts that are connected, with the first element being the current public address of the user.

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03const accounts = await magic.wallet.connectWithUI();

#showUI()

Displays the wallet widget. This is only supported for users who login with email or Google and not third party wallets such as metamask. User must be signed in for this method to return or else it will throw an error.

#Returns

  1. Promise which resolves when the user closes the wallet widget window.
  2. Optionally, add a .on() handler to catch the disconnect event emitted when the user logs out from the wallet widget.

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03// after user has already logged in
04const { walletType } = await magic.wallet.getInfo();
05
06if (walletType === "magic") {
07  magic.wallet.showUI().on('disconnect', () => console.log('user disconnected');
08};

#requestUserInfoWithUI()

Displays the wallet widget within an iframe that prompts the user to consent to sharing information with the requesting dApp with OpenID profile scopes. Currently, the only profile scope that can be requested is a verified email. Collecting a verified email address from third-party wallet users (MetaMask, Coinbase Wallet, etc.) is a premium feature but included in the free trial period (see pricing). User must be signed in for this method to return or else it will throw an error.

#Arguments

  1. scope?: Object : The object containing requested OpenID profile scopes.
    • email?: String : If the user should be prompted to provide them email as a required or optional field.

#Returns

  1. A promise which returns an Object : Contains result of the requested scopes.
    • email?: String: The email of the user if they consented to providing it in the UI.

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03// after user has already logged in
04const userInfo = await magic.wallet.requestUserInfoWithUI({ scope: { email: "required" }})
05console.log(userInfo.email); // the user's email if they consented.

#disconnect()

Disconnects the user from the dApp. This is similar to logging a user out in that it will clear the authenticated state for the current user, the iframe, and any third party wallet the user may have signed in with. User must be signed in for this method to return or else it will throw an error.

#Returns

  1. A promise that return a boolean: If the user's session was succesfully cleared or not.

#Example

Javascript
01import { Magic } from "magic-sdk"
02
03await magic.wallet.disconnect() // clears user session

#EVM RPC Methods

Magic supports the following EVM RPC Methods that can be called through a web3 provider library such as web3.js or ethers.js.

Note: as of magic-sdk@14.0.0, eth_accounts will return an empty array if a user is not logged in. It will no longer prompt the login form. To do that, use magic.wallet.connectWithUI.

  • eth_accounts
  • get_balance
  • eth_estimateGas
  • eth_gasPrice
  • eth_sendTransaction
  • personal_sign
  • eth_signTypedData_v3
  • eth_signTypedData_v4

Did you find what you were looking for?