Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: ui and functionality
  • Loading branch information
chakra-guy committed Feb 14, 2025
commit 369be5a7226cd06e800555ed9e090135d0a47c27
1 change: 1 addition & 0 deletions examples/multichain/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pnpm-debug.log*
lerna-debug.log*

node_modules
local_modules
dist
dist-ssr
*.local
Expand Down
2 changes: 1 addition & 1 deletion examples/multichain/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>Metamask Multichain Example</title>
</head>
<body>
<div id="root"></div>
Expand Down
9 changes: 8 additions & 1 deletion examples/multichain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@
"preview": "vite preview"
},
"dependencies": {
"@chakra-ui/react": "^3.8.0",
"@emotion/react": "^11.14.0",
"@metamask/providers": "^20.0.0",
"lucide-react": "^0.468.0",
"next-themes": "^0.4.4",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react-dom": "^19.0.0",
"react-icons": "^5.4.0",
"tslib": "^2.8.1"
},
"devDependencies": {
"@eslint/js": "^9.19.0",
Expand Down
39 changes: 39 additions & 0 deletions examples/multichain/public/metamask-logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/multichain/public/noise.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
275 changes: 248 additions & 27 deletions examples/multichain/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,256 @@
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
"use client";

import { useState } from "react";
import { useMultichain } from "./multichain/hooks.ts";
import {
Container,
Flex,
Box,
Image,
createListCollection,
Text,
Link,
} from "@chakra-ui/react";
import { Button } from "@chakra-ui/react";
import { toaster } from "./components/ui/toaster"
import { ExternalLink } from "lucide-react";
import { BackgroundNoise } from "./components/layout/background.tsx";
import { NativeSelectField, NativeSelectRoot } from "./components/ui/native-select.tsx";

const EXTENSION_ID = "eklmonnmoaepkgaomjcefmimkkfikokn";

const networks = createListCollection({
items: [
{ label: "Ethereum", value: "eip155:1" },
{ label: "Linea", value: "eip155:59144" },
],
});

function App() {
const [count, setCount] = useState(0)
const [isConnected, setIsConnected] = useState(false);
const [currentNetwork, setCurrentNetwork] = useState(["eip155:1"]);
const [userAddress, setUserAddress] = useState<string | null>(null);

const client = useMultichain();

const handleConnect = async () => {
try {
const connected = await client.connect({ extensionId: EXTENSION_ID });
if (connected) {
const session = await client.createSession({
requiredScopes: {
"eip155:1": {
methods: [],
notifications: ["accountsChanged", "chainChanged"],
},
"eip155:59144": {
methods: [],
notifications: ["accountsChanged", "chainChanged"],
},
},
});
console.log("session", session);
setIsConnected(true);
if (session.sessionScopes["eip155:1"]?.accounts?.[0]) {
const address = session.sessionScopes["eip155:1"].accounts[0].split(':')[2];
setUserAddress(address);
}
}
} catch (error) {
console.error("Failed to connect:", error);
setIsConnected(false);
}
};

const handleDisconnect = () => {
client.disconnect();
setIsConnected(false);
};

const signMessage = async () => {
try {
const result = await client.invokeMethod({
scope: "eip155:1",
request: {
method: "personal_sign",
params: [
"0x506c65617365207369676e2074686973206d65737361676520746f20636f6e6669726d20796f7572206964656e746974792e",
userAddress,
],
},
});
console.log("result", result);
toaster.create({
title: "Message Signed",
description: "Your message was successfully signed",
type: "success",
duration: 4000,
});
} catch (error) {
toaster.create({
title: "Signing Failed",
description: error instanceof Error ? error.message : "An error occurred",
type: "error",
duration: 4000,
});
}
};

const fetchBlockNumber = async () => {
try {
const result = await client.invokeMethod({
scope: currentNetwork[0],
request: {
method: "eth_blockNumber",
params: [],
},
});
const blockNum = Number.parseInt(result as string, 16).toLocaleString(); // Convert hex to decimal and format
toaster.create({
title: "Block Number Retrieved",
description: `Latest block number: ${blockNum}`,
type: "success",
duration: 4000,
});
} catch (error) {
console.error("Failed to fetch block number:", error);
toaster.create({
title: "Failed to Fetch Block Number",
description: error instanceof Error ? error.message : "An error occurred",
type: "error",
duration: 4000,
});
}
};

const handleNetworkChange = (details: { value: string[] }) => {
setCurrentNetwork(details.value);
};

return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
<BackgroundNoise />

<Container w="5xl" h="100vh">
<Flex align="center" justify="space-between" py={10}>
<Image src="/metamask-logo.svg" alt="Logo" height="40px" />
<Flex gap={4} align="center">
{isConnected && (
<NativeSelectRoot size="lg" width="150px">
<NativeSelectField
value={currentNetwork[0]}
onChange={(e) => handleNetworkChange({ value: [e.target.value] })}
bg="white"
color="black"
borderRadius="sm"
border="none"
fontWeight="medium"
>
{networks.items.map((network) => (
<option key={network.value} value={network.value}>
{network.label}
</option>
))}
</NativeSelectField>
</NativeSelectRoot>
)}
<Button
onClick={isConnected ? handleDisconnect : handleConnect}
type="button"
colorScheme="blue"
size="lg"
>
{isConnected ? "Disconnect" : "Connect Wallet"}
</Button>
</Flex>
</Flex>

<Box mt={4} mx="auto" maxW="5xl">
{isConnected ? (
<Flex direction="column" gap={8}>
<Box borderWidth="1px" borderRadius="lg" p={6} bg="rgba(20, 20, 21, 0.44)">
<Text fontSize="xl" mb={2} color="white" fontWeight="medium">
Wallet Actions
</Text>
<Text fontSize="md" color="gray.400" mb={4}>
Try out these wallet interactions using the MetaMask Multichain SDK
</Text>
<Flex gap={4} wrap="wrap">
<Button onClick={signMessage} colorScheme="gray" size="lg">
Sign Message
</Button>
<Button onClick={fetchBlockNumber} colorScheme="gray" size="lg">
Fetch Latest Block
</Button>
</Flex>
</Box>

<Box
borderWidth="1px"
borderRadius="lg"
p={6}
bg="rgba(20, 20, 21, 0.44)"
>
<Text fontSize="xl" mb={4} color="white" fontWeight="medium">
Learn More
</Text>
<Flex direction="column" gap={3}>
<Link
href="https://docs.metamask.io/sdk/"
target="_blank"
color="blue.400"
display="flex"
alignItems="center"
gap={2}
>
Documentation <ExternalLink size={16} />
</Link>
<Link
href="https://github.com/MetaMask/metamask-sdk"
target="_blank"
color="blue.400"
display="flex"
alignItems="center"
gap={2}
>
GitHub Repository <ExternalLink size={16} />
</Link>
<Link
href="https://docs.metamask.io/sdk/reference/"
target="_blank"
color="blue.400"
display="flex"
alignItems="center"
gap={2}
>
API Reference <ExternalLink size={16} />
</Link>
</Flex>
</Box>
</Flex>
) : (
<Flex
direction="column"
align="center"
justify="center"
minH="300px"
p={8}
>
<Box fontSize="4xl" mb={4}>
🔒
</Box>
<Text fontSize="xl" color="gray.200" fontWeight="medium">
Not connected
</Text>
<Text color="gray.400" mt={2}>
Connect your wallet to get started
</Text>
</Flex>
)}
</Box>
</Container>
</>
)
);
}

export default App
export default App;
Loading