-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathContent.tsx
373 lines (321 loc) · 9.77 KB
/
Content.tsx
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import React, { Fragment, useCallback, useEffect, useState } from "react";
import { utils } from "near-api-js";
import type {
SignedMessage,
SignMessageParams,
Transaction,
} from "@near-wallet-selector/core";
import { verifyFullKeyBelongsToUser } from "@near-wallet-selector/core";
import { verifySignature } from "@near-wallet-selector/core";
import type { Account, Message } from "../interfaces";
import { CONTRACT_ID } from "../constants";
import SignIn from "./SignIn";
import Form from "./Form";
import Messages from "./Messages";
import { useWalletSelector } from "@near-wallet-selector/react-hook";
type Submitted = SubmitEvent & {
target: { elements: { [key: string]: HTMLInputElement } };
};
const SUGGESTED_DONATION = "0";
const BOATLOAD_OF_GAS = "30000000000000";
const Content: React.FC = () => {
const {
signedAccountId,
getBalance,
signOut,
signIn,
viewFunction,
callFunction,
signAndSendTransactions,
wallet,
getAccount: getAccountProvider,
signMessage,
accounts,
walletSelector,
} = useWalletSelector();
const [isEthereumWallet, setIsEthereumWallet] = useState(false);
const [account, setAccount] = useState<Account | null>(null);
const [messages, setMessages] = useState<Array<Message>>([]);
const [loading, setLoading] = useState<boolean>(false);
const getAccount = useCallback(async (): Promise<Account | null> => {
if (!signedAccountId) {
return null;
}
const hasBalance = !!(await getBalance(signedAccountId));
if (!hasBalance) {
window.alert(
`Account ID: ${signedAccountId} has not been founded. Please send some NEAR into this account.`
);
await signOut();
return null;
}
return getAccountProvider(signedAccountId).then(
(data) =>
({
...data,
account_id: signedAccountId,
} as Account)
);
}, [getAccountProvider, getBalance, signOut, signedAccountId]);
const getMessages = useCallback(async () => {
return (await viewFunction({
contractId: CONTRACT_ID,
method: "getMessages",
})) as Array<Message>;
}, [viewFunction]);
useEffect(() => {
// TODO: don't just fetch once; subscribe!
getMessages().then(setMessages);
const timeoutId = setTimeout(() => {
verifyMessageBrowserWallet();
}, 500);
return () => {
clearTimeout(timeoutId);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!signedAccountId) {
return setAccount(null);
}
setLoading(true);
getAccount().then((nextAccount) => {
setAccount(nextAccount);
setLoading(false);
});
}, [signedAccountId, getAccount]);
useEffect(() => {
if (!walletSelector) {
return;
}
const checkIfEthereumWallet = async () => {
const selector = await walletSelector;
if (!selector) {
throw new Error("No selector found");
}
setIsEthereumWallet(
selector.store.getState().selectedWalletId === "ethereum-wallets"
);
};
checkIfEthereumWallet();
}, [setIsEthereumWallet, walletSelector]);
const handleSwitchAccount = () => {
if (!accounts) {
throw new Error("No accounts found");
}
if (!walletSelector) {
throw new Error("No selector found");
}
const currentIndex = accounts.findIndex(
(x) => x.accountId === signedAccountId
);
const nextIndex = currentIndex < accounts.length - 1 ? currentIndex + 1 : 0;
const nextAccountId = accounts[nextIndex].accountId;
walletSelector.then((selector) => {
selector.setActiveAccount(nextAccountId);
});
alert("Switched account to " + nextAccountId);
};
const addMessages = useCallback(
async (message: string, donation: string, multiple: boolean) => {
if (!multiple) {
return callFunction({
contractId: CONTRACT_ID,
method: "addMessage",
args: { text: message },
deposit: utils.format.parseNearAmount(donation)!,
}).catch((err) => {
alert("Failed to add message " + err);
console.log("Failed to add message");
throw err;
});
}
const transactions: Array<Transaction> = [];
for (let i = 0; i < 2; i += 1) {
transactions.push({
signerId: signedAccountId!,
receiverId: CONTRACT_ID,
actions: [
{
type: "FunctionCall",
params: {
methodName: "addMessage",
args: {
text: `${message} (${i + 1}/2)`,
},
gas: BOATLOAD_OF_GAS,
deposit: utils.format.parseNearAmount(donation)!,
},
},
],
});
}
return signAndSendTransactions({ transactions }).catch((err) => {
alert("Failed to add messages exception " + err);
console.log("Failed to add messages");
throw err;
});
},
[signedAccountId, callFunction, signAndSendTransactions]
);
const verifyMessage = async (
message: SignMessageParams,
signedMessage: SignedMessage
) => {
const verifiedSignature = verifySignature({
message: message.message,
nonce: message.nonce,
recipient: message.recipient,
publicKey: signedMessage.publicKey,
signature: signedMessage.signature,
callbackUrl: message.callbackUrl,
});
const selector = await walletSelector;
if (!selector) {
throw new Error("No selector found");
}
const verifiedFullKeyBelongsToUser = await verifyFullKeyBelongsToUser({
publicKey: signedMessage.publicKey,
accountId: signedMessage.accountId,
network: selector.options.network,
});
const isMessageVerified = verifiedFullKeyBelongsToUser && verifiedSignature;
const alertMessage = isMessageVerified
? "Successfully verified"
: "Failed to verify";
alert(
`${alertMessage} signed message: '${
message.message
}': \n ${JSON.stringify(signedMessage)}`
);
};
const verifyMessageBrowserWallet = useCallback(async () => {
const urlParams = new URLSearchParams(
window.location.hash.substring(1) // skip the first char (#)
);
const accId = urlParams.get("accountId") as string;
const publicKey = urlParams.get("publicKey") as string;
const signature = urlParams.get("signature") as string;
if (!accId && !publicKey && !signature) {
return;
}
const message: SignMessageParams = JSON.parse(
localStorage.getItem("message")!
);
const signedMessage = {
accountId: accId,
publicKey,
signature,
};
await verifyMessage(message, signedMessage);
const url = new URL(location.href);
url.hash = "";
url.search = "";
window.history.replaceState({}, document.title, url);
localStorage.removeItem("message");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleSubmit = useCallback(
async (e: Submitted) => {
e.preventDefault();
const { fieldset, message, donation, multiple } = e.target.elements;
fieldset.disabled = true;
return addMessages(message.value, donation.value || "0", multiple.checked)
.then(() => {
return getMessages()
.then((nextMessages) => {
setMessages(nextMessages);
message.value = "";
donation.value = SUGGESTED_DONATION;
fieldset.disabled = false;
multiple.checked = false;
message.focus();
})
.catch((err) => {
alert("Failed to refresh messages");
console.log("Failed to refresh messages");
throw err;
});
})
.catch((err) => {
console.error(err);
fieldset.disabled = false;
});
},
[addMessages, getMessages]
);
const handleSignMessage = async () => {
if (!wallet) {
throw new Error("No wallet connected");
}
const message = "test message to sign";
const nonce = Buffer.from(crypto.getRandomValues(new Uint8Array(32)));
const recipient = "guest-book.testnet";
if (wallet.type === "browser") {
localStorage.setItem(
"message",
JSON.stringify({
message,
nonce: [...nonce],
recipient,
callbackUrl: location.href,
})
);
}
try {
const signedMessage = await signMessage({
message,
nonce,
recipient,
});
if (signedMessage) {
await verifyMessage({ message, nonce, recipient }, signedMessage);
}
} catch (err) {
const errMsg =
err instanceof Error ? err.message : "Something went wrong";
alert(errMsg);
}
};
if (loading) {
return null;
}
if (!account) {
return (
<Fragment>
<div>
<button onClick={signIn}>Log in</button>
</div>
<div style={{ marginTop: 30 }}>
{/* @ts-ignore */}
<appkit-button label="Log in with Ethereum" />
</div>
<SignIn />
</Fragment>
);
}
return (
<Fragment>
<div>
<button onClick={signOut}>Log out</button>
<button onClick={signIn}>Switch Wallet</button>
<button onClick={handleSignMessage}>Sign Message</button>
{accounts && accounts.length > 1 && (
<button onClick={handleSwitchAccount}>Switch Account</button>
)}
</div>
{isEthereumWallet && (
<div style={{ marginTop: 30 }}>
{/* @ts-ignore */}
<appkit-button label="Log in with Ethereum" />
</div>
)}
<Form
account={account}
onSubmit={(e) => handleSubmit(e as unknown as Submitted)}
/>
<Messages messages={messages} />
</Fragment>
);
};
export default Content;