-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello.js
More file actions
73 lines (65 loc) · 2.21 KB
/
Copy pathhello.js
File metadata and controls
73 lines (65 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import React, { useState, useEffect } from 'react';
import { ethers } from 'ethers';
import './App.css';
const contractAddress = "YOUR_DEPLOYED_CONTRACT_ADDRESS";
const contractABI = []; // Add your contract ABI here
function App() {
const [account, setAccount] = useState('');
const [contract, setContract] = useState(null);
const [betAmount, setBetAmount] = useState('');
const [result, setResult] = useState('');
useEffect(() => {
connectWallet();
}, []);
async function connectWallet() {
if (typeof window.ethereum !== 'undefined') {
try {
await window.ethereum.request({ method: 'eth_requestAccounts' });
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const address = await signer.getAddress();
setAccount(address);
const contractInstance = new ethers.Contract(contractAddress, contractABI, signer);
setContract(contractInstance);
} catch (error) {
console.error("Failed to connect wallet:", error);
}
} else {
console.log('Please install MetaMask!');
}
}
async function flipCoin() {
if (!contract) return;
try {
const tx = await contract.flip({ value: ethers.utils.parseEther(betAmount) });
await tx.wait();
const events = await contract.queryFilter('CoinFlipped', tx.blockNumber, tx.blockNumber);
const event = events[0];
setResult(event.args.won ? 'You won!' : 'You lost!');
} catch (error) {
console.error("Error flipping coin:", error);
setResult('Error: ' + error.message);
}
}
return (
<div className="App">
<h1>Coin Flip DApp</h1>
{!account ? (
<button onClick={connectWallet}>Connect Wallet</button>
) : (
<div>
<p>Connected Account: {account}</p>
<input
type="text"
value={betAmount}
onChange={(e) => setBetAmount(e.target.value)}
placeholder="Bet amount in ETH"
/>
<button onClick={flipCoin}>Flip Coin</button>
<p>{result}</p>
</div>
)}
</div>
);
}
export default App;