Created
September 14, 2023 21:31
-
-
Save AsaoluElijah/7ffc6ed9d81ae3fc80f22208799f9366 to your computer and use it in GitHub Desktop.
This Gist provides a React code snippet that demonstrates how to connect to MetaMask using the ethers.js library. It includes a simple form styled with Tailwind CSS, allowing users to transfer ETH from their MetaMask account to another address. Upon successful transaction, a confirmation message is displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from "react"; | |
import { ethers } from "ethers"; | |
function App() { | |
const [provider, setProvider] = useState(null); | |
const [address, setAddress] = useState(""); | |
const [amount, setAmount] = useState(""); | |
const [message, setMessage] = useState(""); | |
useEffect(() => { | |
connectMetaMask(); | |
}, []); | |
const connectMetaMask = async () => { | |
if (window.ethereum) { | |
const newProvider = new ethers.providers.Web3Provider(window.ethereum); | |
try { | |
await window.ethereum.enable(); | |
setProvider(newProvider); | |
} catch (error) { | |
console.error("User denied account access"); | |
} | |
} else { | |
console.log( | |
"Non-Ethereum browser detected. Consider installing MetaMask." | |
); | |
} | |
}; | |
const sendEth = async () => { | |
if (provider && address && amount) { | |
const signer = provider.getSigner(); | |
const tx = await signer.sendTransaction({ | |
to: address, | |
value: ethers.utils.parseEther(amount), | |
}); | |
await tx.wait(); | |
// console.log(tx); | |
if (tx.hash) { | |
// navigate()? | |
setMessage( | |
`Transaction successful! Tx Hash: ${tx.hash}, Successfully ${amount} sent to ${tx.to}` | |
); | |
} | |
} | |
}; | |
return ( | |
<div className="App p-8"> | |
<button | |
onClick={connectMetaMask} | |
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" | |
> | |
Connect to MetaMask | |
</button> | |
{provider && ( | |
<div className="mt-4"> | |
<input | |
type="text" | |
placeholder="Recipient Address" | |
onChange={(e) => setAddress(e.target.value)} | |
className="p-2 border rounded" | |
/> | |
<input | |
type="text" | |
placeholder="Amount in ETH" | |
onChange={(e) => setAmount(e.target.value)} | |
className="ml-2 p-2 border rounded" | |
/> | |
<button | |
onClick={sendEth} | |
className="ml-2 bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" | |
> | |
Send ETH | |
</button> | |
</div> | |
)} | |
{message && <p className="mt-4 text-green-500">{message}</p>} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment