---
tags: Guides
---
# Learning Magic
Next Week, challenge: can I replace the login in this template with a Magic API login
Replace Magic
https://dashboard.magic.link/app/all_apps
https://github.com/ethereum-boilerplate/ethereum-boilerplate
Video Tutorial
https://www.youtube.com/watch?v=8csylggGSBQ
---
## Switching between chains ETH & Arbitrum
https://magic.link/posts/magic-arbitrum
Each JS file is for each file or screen (div)

Index.js - it's like a hello world
### Login page with Magic integration
Found in Components folder under 'login.js'
```javascript
import React, { useCallback, useState } from 'react';
import { useHistory } from 'react-router';
import { magicEthereum } from '../magic';
export default function Login() {
const [email, setEmail] = useState('');
const [isLoggingIn, setIsLoggingIn] = useState(false);
const history = useHistory();
/**
* Perform login action via Magic's passwordless flow. Upon successuful
* completion of the login flow, a user is redirected to the homepage.
*/
const login = useCallback(async () => {
setIsLoggingIn(true);
try {
await magicEthereum.auth.loginWithMagicLink({
email,
redirectURI: new URL('/callback', window.location.origin).href,
});
history.push('/');
} catch {
setIsLoggingIn(false);
}
}, [email]);
/**
* Saves the value of our email input into component state.
*/
const handleInputOnChange = useCallback(event => {
setEmail(event.target.value);
}, []);
return (
<div className='container'>
<h1>Please sign up or login</h1>
<input
type='email'
name='email'
required='required'
placeholder='Enter your email'
onChange={handleInputOnChange}
disabled={isLoggingIn}
/>
<button onClick={login} disabled={isLoggingIn}>Send</button>
</div>
);
}
```
### Switching between networks
1) requires Magic API Key
2) Arbitrum API key (Via Alchemy)

---
## Project 2: Replace Login
Installing Boilerplate example
Install NextJS
Run the application
``` npm run dev ```
``` grep -r "Naming to be searched```
Replacement
Looking for on-click event so that it can be changed and connect to Magic. Typically done with listeners
Create a connector object between Magic and this template
Source the line number that I'm looking for
```javascript=
const { connectAsync } = useConnect({ connector: new InjectedConnector() });
```
so replace "InjectedConnector" with Magic Connector
### Has a render function
```javascript=
/* 4. Implement Login Handler */
const handleLogin = async e => {
e.preventDefault();
const email = new FormData(e.target).get('email');
const redirectURI = `${window.location.origin}/callback`; // 👈 This will be our callback URI
if (email) {
/* One-liner login 🤯 */
await magic.auth.loginWithMagicLink({ email, redirectURI }); // 👈 Notice the additional parameter!
render();
}
};
```
How to hook the button with the render function
```javascript
await magic.auth.loginWithMagicLink({ email, redirectURI })
```
provide user data
```
const { account, chain } = await connectAsync();
```
## Replace
1. find the JS type of the current Moralis login so that I can replace
https://docs.moralis.io/docs/sign-in-with-magiclink
```javascript=
import { MagicConnector } from '@everipedia/wagmi-magic-connector'
import { signIn } from 'next-auth/react'
import { useAccount, useConnect, useSignMessage, useDisconnect } from 'wagmi'
import { useRouter } from 'next/router'
import axios from 'axios'
```
These imports are new and need to be included
```javascript=
const { connectAsync } = useConnect({
connector: new MagicConnector({
options: {
apiKey: 'YOUR_MAGIC_LINK_API_KEY', //required
},
}),
})
```
copy and paste over
```javascript=
const { push } = useRouter()
```
---
Currently using WAGMI for contract calls
better guides on better swapping out frameworks
rainbow kit better for side projets (https://www.rainbowkit.com/)
Ask Hunter
fastest way to sell connection between login and user adoption
---
line 9
```javascript=
const { connectAsync } = useConnect({ connector: new InjectedConnector() });
```
How WAGMI is dealing with the connected wallet
This is the WAGMI component
```javascript=
const MyApp = ({ Component, pageProps }: AppProps) => {
return (
<ChakraProvider resetCSS theme={theme}>
<WagmiConfig client={client}>
<SessionProvider session={pageProps.session} refetchInterval={0}>
<Component {...pageProps} />
</SessionProvider>
</WagmiConfig>
</ChakraProvider>
);
};
```
want to give context to user that you're login, your app.js page is top thing that you go to, where you see the design pattern that is stored here and checked if the person is logged in, and useful to say that the user is logged in
magic user and then go to main pages and show that you're logged in
- need examples of build end to end
pull cycles to make something, fix guides,
have existing, how to replace with Magic connect
1. guide on NextJS and creating a MC together
2. a flow on how to use Magic Connect, and make smart contract calls and reads

If we have a MetaMask, MM lives in the browser, and that's where the Key is stored, and if you want to access it you access your browser
If custodial - i save your private key in our database and do transaction
If non-custodial - our backend is not storing private keys in database, and storing in 3rd party
the browser is telling backend that you are starting hte practice, and now the email says i'm logged in and the back-end says it's verified, send credentials to browser, and inject iFrame into browser, and go to token and go to wallet and get the private key
The API is giving credentials to browser and going to security module to get credneitals, and Magic configures the wallet module. If Magic goes down the KMS module goes down, our backend systems gives credentials. We want to innovate on decentralize the storage of keys, and rn we are focused on security
Break up this KMS (Amazon Hardware Security model - we are whitelabeling) into multiple fractions and create partial signatures into. Our backend never touches the flow we are just interacting with it. Our backend can't see the private key
Amazon is literally using hardware - cold storage
To access, you need to get into the network itself
In technical version include:
https://magic.link/docs/home/security#delegated-key-management
https://magic.link/docs/home/security#client-to-aws-data-flow
Boilerplates would be Mushfy, where are his example demo/boilerplates
---
## Project 3: DemoLogin
Goal: Replace a traditional login with Magic Connect
Step 1: Find template
https://github.com/mdbootstrap/bootstrap-login-form
https://mdbootstrap.com/docs/standard/extended/login/#section-2
Step 2: have functioning JS file
https://magic.link/docs/connect/get-started#email-one-time-passcode
Step 3: API keys
https://docs.moralis.io/authentication-api/how-to-sign-in-with-magiclink
creating API.json file to create an offline file for storing keys so you don't publish a file with your private keys on Github
access JSON object in JS
create 3 variables
https://mkyong.com/javascript/how-to-access-json-object-in-javascript/
```javascript=
var APIObject = JSON.parse("API.json")
var APIKey = APIObject["Secret"]
const magic = new Magic(APIKey
```
we put the API keys as json variables and then referenced them in the js file
---
01/18/2023
Installed the SDKs
Created a header for us to incorporate JS in the html file
https://www.w3schools.com/tags/tag_head.asp
Next week
we want to ensure the Login Handler Submit button has function
https://magic.link/posts/hello-world
edit the code in the html file
Step 4: make an association between JS and button
Step 5: user clicking button
implement event handler for onclick
Handler needs to be listening to on-click
adding onclick handler
```
<button onclick="handleLogin()" class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="button">Log
in</button>
```
Step 6: created module for the index html script
```
type="module"
```
Step 7: install python
Step 8: install npm web3
https://github.com/web3/web3.js/issues/1439
1/25/23
next week is getting login to work and seeing if we need to edit out any doubles in the Web3.js or html file