Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update react templates #16

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions templates/react/next-ethers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ This is a [zkSync](https://zksync.io) + [ethers v6](https://docs.ethers.org/v6/)

# Getting Started

## Requirements
- A wallet extension like MetaMask installed in your browser.
- Node.js and npm installed.
- To use the `dockerized local node` or `in memory local node` setups, you will need to run the respective services in Docker. For detailed instructions on setting up and running these nodes, refer to the [Documentation](https://docs.zksync.io/build/test-and-debug).

## Installation
Install dependencies with `npm install`.

Run `npm run dev` in your terminal, and then open [localhost:3000](http://localhost:3000) in your browser.

Once the webpage has loaded, changes made to files inside the `src/` directory (e.g. `src/pages/index.tsx`) will automatically update the webpage.
Expand Down
22 changes: 11 additions & 11 deletions templates/react/next-ethers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
"lint": "next lint"
},
"dependencies": {
"ethers": "^6.9.2",
"next": "^13.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"zksync-ethers": "^6.0.0"
"ethers": "^6.13.2",
"next": "^14.2.5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"zksync-ethers": "^6.11.1"
},
"devDependencies": {
"@types/node": "^17.0.31",
"@types/react": "^18.0.9",
"@types/react-dom": "^18.0.3",
"eslint": "^8.15.0",
"eslint-config-next": "^12.1.6",
"typescript": "^5.0.4"
"@types/node": "^22.1.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"eslint": "^8.57.0",
"eslint-config-next": "^14.2.5",
"typescript": "^5.5.4"
}
}
32 changes: 18 additions & 14 deletions templates/react/next-ethers/src/components/Balance.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
'use client'
'use client';

import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { ethers } from 'ethers';

import { useAsync } from '../hooks/useAsync';
import { useEthereum } from './Context';

Expand All @@ -17,25 +16,30 @@ export function Balance() {
<FindBalance />
</div>
</>
)
);
}

export function AccountBalance() {
const { getProvider, account } = useEthereum();
const { result: balance, execute: fetchBalance, error } = useAsync(address => getProvider()!.getBalance(address));

const fetchBalance = useCallback((address: string) => {
return getProvider()!.getBalance(address);
}, [getProvider]);

const { result: balance, execute, error } = useAsync(fetchBalance);

useEffect(() => {
if (account?.address) {
fetchBalance(account.address);
execute(account.address);
}
}, [account]);
}, [account, execute]);

return (
<div>
<div>
Connected wallet balance:
{balance ? ethers.formatEther(balance) : ""}
<button onClick={() => fetchBalance(account?.address)}>refetch</button>
{balance ? ethers.formatEther(balance) : "0"}
<button onClick={() => account?.address && execute(account?.address)}>refetch</button>
</div>
{error && <div>Error: {error.message}</div>}
</div>
Expand All @@ -46,13 +50,13 @@ export function FindBalance() {
const [address, setAddress] = useState('');
const { getProvider } = useEthereum();

const fetchBalanceFunc = async (address: string) => {
const fetchBalanceFunc = useCallback(async (address: string) => {
const provider = getProvider();
if (!provider) throw new Error("Provider not found");
return provider.getBalance(address);
};
}, [getProvider]);

const { result: balance, execute: fetchBalance, inProgress, error } = useAsync(fetchBalanceFunc);
const { result: balance, execute, inProgress, error } = useAsync(fetchBalanceFunc);

return (
<div>
Expand All @@ -64,11 +68,11 @@ export function FindBalance() {
type="text"
placeholder="wallet address"
/>
<button onClick={() => fetchBalance(address)}>
<button onClick={() => execute(address)} disabled={!address}>
{inProgress ? 'fetching...' : 'fetch'}
</button>
</div>
<div>{balance ? ethers.formatEther(balance) : ""}</div>
<div>{balance ? ethers.formatEther(balance) : "0"}</div>
{error && <div>Error: {error.message}</div>}
</div>
);
Expand Down
52 changes: 37 additions & 15 deletions templates/react/next-ethers/src/components/BlockNumber.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,54 @@
'use client'

import { useState, useEffect } from 'react';

import { useState, useEffect, useCallback } from 'react';
import { useEthereum } from './Context';

export function BlockNumber() {
const { getProvider } = useEthereum();
const [blockNumber, setBlockNumber] = useState<bigint | null>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const fetchAndSubscribeToBlockUpdates = useCallback(async () => {
setError(null);
const provider = getProvider();
if (!provider) {
setError("Provider not available");
return () => {};
}

try {
const currentBlockNumber = await provider.getBlockNumber();
setBlockNumber(BigInt(currentBlockNumber));

const onBlockHandler = (blockNumber: number) => {
setBlockNumber(BigInt(blockNumber));
};

provider.on("block", onBlockHandler);

return () => {
provider.off("block", onBlockHandler);
};
} catch (err) {
setError(`Error: ${err instanceof Error ? err.message : String(err)}`);
return () => {};
}
}, [getProvider]);

if (!provider) return;

const onBlockHandler = (block: bigint) => {
setBlockNumber(block);
};

provider.on("block", onBlockHandler);
useEffect(() => {
const unsubscribe = fetchAndSubscribeToBlockUpdates();

return () => {
provider.off("block", onBlockHandler);
};
}, [getProvider]);
}, [fetchAndSubscribeToBlockUpdates]);

return (
<div>
{blockNumber?.toString()}
{error ? (
<div>Error: {error}</div>
) : blockNumber === null ? (
<div>Loading block number...</div>
) : (
<div>{blockNumber.toString()}</div>
)}
</div>
);
}
44 changes: 17 additions & 27 deletions templates/react/next-ethers/src/components/Context.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { JsonRpcSigner } from 'ethers';
import React, { useState, useEffect, createContext, useContext } from 'react';
import { useState, createContext, useContext } from 'react';
import { BrowserProvider } from 'zksync-ethers';

type Chain = {
Expand All @@ -20,19 +20,12 @@ const zkSync: Chain = {
const zkSyncSepoliaTestnet: Chain = {
id: 300,
name: "zkSync Sepolia Testnet",
rpcUrl: "https://rpc.ankr.com/eth_sepolia",
rpcUrl: "https://sepolia.era.zksync.dev",
blockExplorerUrl: "https://sepolia.etherscan.io"
}
const zkSyncGoerliTestnet: Chain = {
id: 280,
name: "zkSync Goerli Testnet",
rpcUrl: "https://testnet.era.zksync.dev",
blockExplorerUrl: "https://goerli.explorer.zksync.io"
}
export const chains: Chain[] = [
zkSync,
zkSyncSepoliaTestnet,
zkSyncGoerliTestnet,
...(
process.env.NODE_ENV === "development" ?
[
Expand Down Expand Up @@ -70,6 +63,7 @@ const EthereumContext = createContext<EthereumContextValue | null>(null);
export const EthereumProvider = ({ children }: { children: React.ReactNode }) => {
const [account, setAccount] = useState<{ isConnected: true; address: string; } | { isConnected: false; address: null; }>({ isConnected: false, address: null });
const [network, setNetwork] = useState<Chain | null>(null);
const [error, setError] = useState<string | null>(null);

const getEthereumContext = () => (window as any).ethereum;

Expand All @@ -91,16 +85,19 @@ export const EthereumProvider = ({ children }: { children: React.ReactNode }) =>
}

const connect = async () => {
if (!getEthereumContext()) throw new Error("No injected wallets found");

web3Provider = new BrowserProvider((window as any).ethereum, "any");
const accounts = await web3Provider?.send("eth_requestAccounts", []);
if (accounts.length > 0) {
onAccountChange(accounts);
getEthereumContext()?.on("accountsChanged", onAccountChange);
web3Provider?.on("network", onNetworkChange);
} else {
try {
if (!getEthereumContext()) throw new Error("No injected wallets found");
web3Provider = new BrowserProvider((window as any).ethereum, "any");
const accounts = await web3Provider?.send("eth_requestAccounts", []);
if (accounts.length > 0) {
onAccountChange(accounts);
getEthereumContext()?.on("accountsChanged", onAccountChange);
web3Provider?.on("network", onNetworkChange);
} else {
throw new Error("No accounts found");
}
} catch (err: any) {
setError(err.message);
}
}

Expand All @@ -114,14 +111,6 @@ export const EthereumProvider = ({ children }: { children: React.ReactNode }) =>
web3Provider?.off("network", onNetworkChange);
}

useEffect(() => {
connect();

return () => { // Clean-up on component unmount
disconnect();
}
}, []);

const switchNetwork = async (chainId: number) => {
const chain = chains.find((chain: any) => chain.id === chainId);
if (!chain) throw new Error("Unsupported chain");
Expand Down Expand Up @@ -166,6 +155,7 @@ export const EthereumProvider = ({ children }: { children: React.ReactNode }) =>
getSigner
}}>
{children}
{error && <div>Error: {error}</div>}
</EthereumContext.Provider>
);
}
Expand All @@ -176,4 +166,4 @@ export const useEthereum = () => {
throw new Error("useEthereum must be used within an EthereumProvider");
}
return context;
}
}
Loading
Loading