guides
Guide

How to use Magic with Ethereum and Optimism

Magic Staff ยท August 1, 2021

#Resources

Note: this guide uses web3.js, but to see a demo with ethers.js click here.

#Introduction

#What is Optimism

Optimism (aka Optimistic Ethereum) is a Layer 2 scaling solution for Ethereum. It uses "optimistic rollups" technology where transactions are submitted directly to the L2, "rolled up" into a single proof, then sent to the layer one chain (Ethereum) to be verified. With smart contract computations being done on L2 rather than L1, it allows for significantly faster and cheaper transactions.

Optimism is also interoperable with Ethereum and the Ethereum Virtual Machine (EVM) so smart contracts can easily be deployed on Optimism without much/any refactoring.

With Magic, developers can connect to the Optimism network by simply specifying the network URL when initiating a Magic instance. This guide will show how you can create a web3-enabled app, allow users to switch between the Ethereum and Optimism networks, call smart contracts, and send transactions.

#Connecting to Optimism

In magic.js, simply initialize the Magic instance with the network pointed to your Optimism rpc url.

Javascript
01import { Magic } from "magic-sdk";
02
03const customNodeOptions = {
04  rpcUrl: "https://goerli.optimism.io",
05  chainId: 420
06};
07
08export const magic = new Magic("YOUR_API_KEY", {
09  network: customNodeOptions
10});

#Viewing User Balance

You can use the native getBalance function of the web3.js library to pull the user's balance for whichever network you iniated Magic with.

Javascript
01const fetchBalance = (address) => {
02  web3.eth.getBalance(address).then(bal => setBalance(web3.utils.fromWei(bal)))
03}
04
05return (
06  <h1>Balance</h1>
07  <div className="info">
08    {balance.toString().substring(0, 6)} ETH
09  </div>
10)

#Send Transaction

Sending a transaction is also very simple using web3.js. Be sure to pass in a gasPrice as Optimism does not accept EIP-1559 transactions, and if there is no gasPrice specified, Magic will manually calculate it using an EIP-1559 transaction type.

Javascript
01const sendTransaction = async () => {
02    const { transactionHash } = await web3.eth.sendTransaction({
03      from: publicAddress,
04      to: toAddress,
05      value: web3.utils.toWei(amount),
06      gasPrice: "1"
07    });
08}
09
10return (
11 <div className="container">
12  <h1>Send Transaction</h1>
13  <input 
14    type="text" 
15    value={toAddress} 
16    onChange={(e) => setToAddress(e.target.value)} 
17    placeholder="To Address" 
18  />
19  <input 
20    type="text" 
21    value={amount} 
22    onChange={(e) => setAmount(e.target.value)} 
23    placeholder="Amount" 
24  />
25  <button onClick={sendTransaction}>Send Transaction</button>
26</div>
27)

#Calling Smart Contracts

Javascript
01const contractAddress = "0x6fA26B7618881A5D528dff280d5A12c51CDD41b8";
02  const contract = new web3.eth.Contract(abi, contractAddress);
03  const [number, setNumber] = useState();
04  const [newNumber, setNewNumber] = useState("");
05
06  const fetchContractNumber = () => {
07    contract.methods.number().call().then(setNumber);
08  };
09
10  useEffect(() => {
11    fetchContractNumber();
12  }, []);
13
14  const updateContractNumber = async () => {
15    const { transactionHash } = await contract.methods.store(newNumber).send({
16      from: publicAddress,
17      gasPrice: "1"
18    });
19  };
20
21  return (
22    <div className="container">
23      <h1>Number stored in contract</h1>
24      <div className="info">{number}</div>
25
26      <h1>Update Number</h1>
27      <input
28        type="text"
29        disabled={disabled}
30        value={newNumber}
31        onChange={(e) => setNewNumber(e.target.value)}
32        className="full-width"
33        placeholder="New number"
34      />
35      <button disabled={disabled} onClick={updateContractNumber}>
36        Update
37      </button>
38    </div>
39  );

#Done

That's all there is to it! You've now got an app that allows users to create a wallet with just their email, and connect to the Optimism L2 and Ethereum networks within your app.

Let's make some magic!

Did you find what you were looking for?