Guides
Guide

How to Build a Decentralized App on Binance Smart Chain with Magic

How to Build a Decentralized App on Binance Smart Chain with Magic

4 Feb 2021
Download this example and get started in seconds:
npx make-magic --template binance-smart-chain
Banner for How to Build a Decentralized App on Binance Smart Chain with Magic

Hi 👋, in this end-to-end guide you'll be building a Binance Smart Chain based dApp (decentralized application) with the functionalities to send transactions, deploy & iteract with smart contracts, and sign messages, with keys secured by a familiar Web 2.0 style passwordless login!


Boostrap Project

CLI Quickstart Tool

To start, run the following CLI command in your terminal. The make-magic NPM package is the quickest way to bootstrap a Magic project from a list of pre-built templates - similar to create-react-app.

npx make-magic --template binance-smart-chain

Setup Project Name

After a few seconds, you will be prompted for a project name, this will also be the name of the folder that will be created for this project.

Prompt Project Name

Magic Publishable API Key

After putting in a project name, you will be prompted for your Magic Publishable API Key, which is used to enable user authentication with Magic.

Prompt Publishable API Key

To get your publishable API key, you'll need to sign up to Magic Dashboard. Once you've signed up, an app will be created upon your first login (you'll be able to create new apps later).

Magic Dashboard

You'll now be able to see your Test Publishable API Key - copy and paste the key into your CLI prompt.

Fill Publishable API Key

Select NPM Client

After hitting Enter, you'll be asked to select whether you’d like to use npm / yarn as the NPM client for your project.

Prompt NPM Client

Open Application

After selecting your NPM client, a lightweight server will automatically start and you'll be directed to your application running locally.

In this example app, you'll be prompted to sign up for a new account using an email address or login to an existing one. The authentication process is secured by Magic.

Sign Up Form

After clicking on your magic link email, you'll be successfully logged in, and a Binance Smart Chain wallet address will be automatically generated as well!

Signed Up

Get Test BNB

To interact with this example app, you'll first need to acquire some test BNB tokens. This is very straightforward with Binance Smart Chain with a couple few steps:

  1. Visit the BNB Testnet Faucet
  2. Copy and paste your public address from the example app into the text box of the faucet
  3. Click the Give me BNB dropdown button, and select how many test BNB tokens you'd like to get
  4. After a few seconds, the tokens will be available in your account!

Code Deep Dive

Now you can open your local project with a code editor of your choice, and we'll highlight several snippets of code where we'll teach you some basics on how to use Magic and Binance Smart Chain.

Install Magic and Web3 SDK

To begin using Magic and Binance Smart Chain, you'll first need to install the Magic and Web3 Javascript SDK with a script tag. You can also install them with yarn or npm.

You may already be familiar with the Web3 SDK, which is often used to build Ethereum-based decentralized applications. What's exciting about Binance Smart Chain is that it's EVM-compatible, which means you can continue to use the same Web3 SDK without having to learn a new SDK interface!

<script src="https://cdn.jsdelivr.net/npm/magic-sdk/dist/magic.js"></script> <script src="https://cdn.jsdelivr.net/npm/web3@1.3.4/dist/web3.min.js"></script>

Initialize Magic Instance

Before you initialize a Magic instance, you'll need to configure your Binance Smart Chain options.

For Testnet

const BSCOptions = { /* Smart Chain Testnet RPC URL */ rpcUrl: 'https://data-seed-prebsc-1-s1.binance.org:8545/', chainId: 97, // Smart Chain Testnet Chain ID };

For Mainnet

const BSCOptions = { /* Smart Chain Mainnet RPC URL */ rpcUrl: 'https://bsc-dataseed.binance.org/', chainId: 56, // Smart Chain Mainnet Chain ID };

Now you can initialize a Magic instance with your Publishable API Key and Binance Smart Chain options:

/* Initialize Magic instance */ const magic = new Magic('pk_test_api_key', { network: BSCOptions, }); /* Initialize Binance Smart Chain Web3 provider */ const web3 = new Web3(magic.rpcProvider);

Implement Login Handler

Implementing user login is very straightforward with Magic. Simply pass in the user email to a one-liner to initiate the login process:

await magic.auth.loginWithMagicLink({ email });

Full Implementation

const handleLogin = async e => { e.preventDefault(); const email = new FormData(e.target).get('email'); if (email) { /* One-liner login 🤯 */ await magic.auth.loginWithMagicLink({ email }); render(); } };

Implement Send Transaction

Every Magic user account comes with a Binance Smart Chain wallet key pair, and can be accessed via familiar and simple Web 2.0 style login, without needing to write down seedphrases or download browser extensions.

To get your current wallet address

const fromAddress = (await web3.eth.getAccounts())[0];

To send a transaction to the blockchain with Web3

const receipt = await web3.eth.sendTransaction({ from: fromAddress, to: destination, value: web3.utils.toWei(amount), });

Read official Web3 SDK documentation to learn more method usages. The Magic SDK documentation has more examples too.

Full Implementation

const handleSendTxn = async e => { e.preventDefault(); const destination = new FormData(e.target).get('destination'); const amount = new FormData(e.target).get('amount'); if (destination && amount) { const btnSendTxn = document.getElementById('btn-send-txn'); btnSendTxn.disabled = true; btnSendTxn.innerText = 'Sending...'; const fromAddress = (await web3.eth.getAccounts())[0]; // Submit transaction to the blockchain and wait for it to be mined const receipt = await web3.eth.sendTransaction({ from: fromAddress, to: destination, value: web3.utils.toWei(amount), }); console.log('Completed:', receipt); render(); } };

Implement Logout Handler

Implementing user logout is very simple.

Full Implementation

const handleLogout = async () => { await magic.user.logout(); render(); };

Use Fortmatic

Fortmatic is an alternative product developed by the Magic team to support Ethereum-specific dApps - it now also supports Binance Smart Chain! The main difference is that Fortmatic offers a Single-Sign-On user experience and has a default UI for sending transactions and sending messages (unlike Magic where you can customize the UI).

info

👉 Check out the following CodeSandBox for full example.

Learn More

Let's make some magic!