-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.tsx
More file actions
270 lines (242 loc) · 8.05 KB
/
Copy pathapp.tsx
File metadata and controls
270 lines (242 loc) · 8.05 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// import functionalities
import './App.css';
import {
Connection,
Keypair,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
clusterApiUrl,
sendAndConfirmTransaction,
} from "@solana/web3.js";
import { useEffect, useState } from "react";
import './App.css'
// import to fix polyfill issue with buffer with webpack
import * as buffer from "buffer";
window.Buffer = buffer.Buffer;
// create types
type DisplayEncoding = "utf8" | "hex";
type PhantomEvent = "disconnect" | "connect" | "accountChanged";
type PhantomRequestMethod =
| "connect"
| "disconnect"
| "signTransaction"
| "signAllTransactions"
| "signMessage";
interface ConnectOpts {
onlyIfTrusted: boolean;
}
// create a provider interface (hint: think of this as an object) to store the Phantom Provider
interface PhantomProvider {
publicKey: PublicKey | null;
isConnected: boolean | null;
signTransaction: (transaction: Transaction) => Promise<Transaction>;
signAllTransactions: (transactions: Transaction[]) => Promise<Transaction[]>;
signMessage: (
message: Uint8Array | string,
display?: DisplayEncoding
) => Promise<any>;
connect: (opts?: Partial<ConnectOpts>) => Promise<{ publicKey: PublicKey }>;
disconnect: () => Promise<void>;
on: (event: PhantomEvent, handler: (args: any) => void) => void;
request: (method: PhantomRequestMethod, params: any) => Promise<unknown>;
}
/**
* @description gets Phantom provider, if it exists
*/
const getProvider = (): PhantomProvider | undefined => {
if ("solana" in window) {
// @ts-ignore
const provider = window.solana as any;
if (provider.isPhantom) return provider as PhantomProvider;
}
};
export default function App() {
// create state variable for the provider
const [provider, setProvider] = useState<PhantomProvider | undefined>(
undefined
);
// create state variable for the phantom wallet key
const [receiverPublicKey, setReceiverPublicKey] = useState<PublicKey | undefined>(
undefined
);
// create state variable for the sender wallet key
const [senderKeypair, setSenderKeypair] = useState<Keypair | undefined>(
undefined
);
// create a state variable for our connection
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
// connection to use with local solana test validator
// const connection = new Connection("http://127.0.0.1:8899", "confirmed");
// this is the function that runs whenever the component updates (e.g. render, refresh)
useEffect(() => {
const provider = getProvider();
// if the phantom provider exists, set this as the provider
if (provider) setProvider(provider);
else setProvider(undefined);
}, []);
/**
* @description creates a new KeyPair and airdrops 2 SOL into it.
* This function is called when the Create a New Solana Account button is clicked
*/
const createSender = async () => {
// create a new Keypair
const newKeypair = Keypair.generate();
setSenderKeypair(newKeypair);
console.log('Sender account: ', newKeypair.publicKey.toString());
console.log('Airdropping 2 SOL to Sender Wallet');
// request airdrop into this new account
try {
const airdropSignature = await connection.requestAirdrop(
newKeypair.publicKey,
2 * LAMPORTS_PER_SOL // Airdrop 2 SOL
);
const latestBlockHash = await connection.getLatestBlockhash();
await connection.confirmTransaction({
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
signature: airdropSignature,
});
console.log('Wallet Balance: ' + (await connection.getBalance(newKeypair.publicKey)) / LAMPORTS_PER_SOL);
} catch (error) {
console.error('Airdrop failed:', error);
}
};
/**
* @description prompts user to connect wallet if it exists.
* This function is called when the Connect to Phantom Wallet button is clicked
*/
const connectWallet = async () => {
// @ts-ignore
const { solana } = window;
// checks if phantom wallet exists
if (solana) {
try {
// connect to phantom wallet and return response which includes the wallet public key
const response = await solana.connect({ onlyIfTrusted: false });
console.log('Connected to wallet:', response.publicKey.toString());
// save the public key of the phantom wallet to the state variable
setReceiverPublicKey(new PublicKey(response.publicKey));
} catch (err) {
console.error('Failed to connect wallet:', err);
}
}
};
/**
* @description disconnects wallet if it exists.
* This function is called when the disconnect wallet button is clicked
*/
const disconnectWallet = async () => {
// @ts-ignore
const { solana } = window;
// checks if phantom wallet exists
if (solana) {
try {
solana.disconnect();
setReceiverPublicKey(undefined);
console.log("wallet disconnected")
} catch (err) {
console.log(err);
}
}
};
/**
* @description transfer SOL from sender wallet to connected wallet.
* This function is called when the Transfer SOL to Phantom Wallet button is clicked
*/
const transferSol = async () => {
if (!senderKeypair || !receiverPublicKey) {
console.error('Sender or Receiver account is missing');
return;
}
try {
// create a new transaction for the transfer
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: senderKeypair.publicKey,
toPubkey: receiverPublicKey,
lamports: LAMPORTS_PER_SOL, // Transfer 1 SOL
})
);
// send and confirm the transaction
const signature = await sendAndConfirmTransaction(connection, transaction, [senderKeypair]);
console.log('Transaction signature:', signature);
console.log("Sender Balance: " + await connection.getBalance(senderKeypair.publicKey) / LAMPORTS_PER_SOL);
console.log("Receiver Balance: " + await connection.getBalance(receiverPublicKey) / LAMPORTS_PER_SOL);
} catch (error) {
console.error('Transfer failed:', error);
}
};
// HTML code for the app
return (
<div className="App">
<header className="App-header">
<h2>Module 2 Assessment</h2>
<span className="buttons">
<button
style={{
fontSize: "16px",
padding: "15px",
fontWeight: "bold",
borderRadius: "5px",
}}
onClick={createSender}
>
Create a New Solana Account
</button>
{provider && !receiverPublicKey && (
<button
style={{
fontSize: "16px",
padding: "15px",
fontWeight: "bold",
borderRadius: "5px",
}}
onClick={connectWallet}
>
Connect to Phantom Wallet
</button>
)}
{provider && receiverPublicKey && (
<div>
<button
style={{
fontSize: "16px",
padding: "15px",
fontWeight: "bold",
borderRadius: "5px",
position: "absolute",
top: "28px",
right: "28px"
}}
onClick={disconnectWallet}
>
Disconnect from Wallet
</button>
</div>
)}
{provider && receiverPublicKey && senderKeypair && (
<button
style={{
fontSize: "16px",
padding: "15px",
fontWeight: "bold",
borderRadius: "5px",
}}
onClick={transferSol}
>
Transfer SOL to Phantom Wallet
</button>
)}
</span>
{!provider && (
<p>
No provider found. Install{" "}
<a href="https://phantom.app/">Phantom Browser extension</a>
</p>
)}
</header>
</div>
);
}