-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.tsx
428 lines (405 loc) · 12.7 KB
/
index.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import { CeloTokenContract } from '@celo/contractkit/lib/base';
import { StableToken } from '@celo/contractkit/lib/celo-tokens';
import { StableTokenWrapper } from '@celo/contractkit/lib/wrappers/StableTokenWrapper';
import {
Alfajores,
CeloProvider,
Theme,
UseCelo,
useCelo,
} from '@celo/react-celo';
import { BigNumber } from 'bignumber.js';
import Head from 'next/head';
import { useCallback, useEffect, useState } from 'react';
import Web3 from 'web3';
import { PrimaryButton, SecondaryButton, toast } from '../components';
import CeloWordMark from '../components/celo-wordmark';
import { ThemeButton, themes } from '../components/theme-button';
import { feeTokenMap } from '../utils';
import { sendTestTransaction } from '../utils/send-test-transaction';
import { signTest } from '../utils/sign-test';
import { signTestTypedData } from '../utils/sign-test-typed-data';
interface Summary {
name: string;
address: string;
celo: BigNumber;
balances: { symbol: StableToken; value?: BigNumber; error?: string }[];
}
const defaultSummary: Summary = {
name: '',
address: '',
celo: new BigNumber(0),
balances: [],
};
function truncateAddress(address: string) {
return `${address.slice(0, 8)}...${address.slice(36)}`;
}
const html =
typeof document !== 'undefined' &&
(document.getElementsByTagName('html')[0] as HTMLElement);
function isDark() {
return html && html.classList.contains('tw-dark');
}
function HomePage(): React.ReactElement {
const {
kit,
address,
network,
connect,
supportsFeeCurrency,
disconnect,
performActions,
walletType,
feeCurrency,
updateFeeCurrency,
updateTheme,
} = useCelo();
const [_theme, selectTheme] = useState<Theme | null>(null);
const [summary, setSummary] = useState(defaultSummary);
const [sending, setSending] = useState(false);
const fetchSummary = useCallback(async () => {
if (!address) {
setSummary(defaultSummary);
return;
}
const [accounts, goldToken, stableTokens] = await Promise.all([
kit.contracts.getAccounts(),
kit.contracts.getGoldToken(),
Promise.all(
Object.values(StableToken).map(async (stable) => {
let contract;
try {
contract = await kit.contracts.getStableToken(stable);
} catch (e) {
contract = null;
console.error(e);
}
return {
symbol: stable,
contract: contract,
};
})
),
]);
const [accountSummary, celo, balances] = await Promise.all([
accounts.getAccountSummary(address).catch((e) => {
console.error(e);
return defaultSummary;
}),
goldToken.balanceOf(address),
getBalances(stableTokens, address),
]);
setSummary({
...accountSummary,
celo,
balances,
});
}, [address, kit]);
const wrapAction =
(
action: (performActions: UseCelo['performActions']) => Promise<void>,
actionName: string
) =>
async () => {
try {
setSending(true);
await action(performActions);
toast.success(`${actionName} succeeded`);
await fetchSummary();
} catch (e) {
toast.error((e as Error).message);
} finally {
setSending(false);
}
};
const testSendTransaction = wrapAction(
sendTestTransaction,
'sendTransaction'
);
const testSignTypedData = wrapAction(signTestTypedData, 'signTypedData');
const testSignPersonal = wrapAction(signTest, 'signPersonal');
const toggleDarkMode = useCallback(() => {
if (!html) {
return;
}
if (isDark()) {
html.classList.remove('tw-dark');
html.classList.remove('dark');
} else {
html.classList.add('tw-dark');
html.classList.add('dark');
}
}, []);
useEffect(() => {
void fetchSummary();
}, [fetchSummary]);
return (
<div className="w-full">
<Head>
<title>react-celo</title>
<link rel="icon" href="/favicon.ico?v=2" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=5"
/>
</Head>
<main className="w-full">
<section className="flex flex-col justify-center items-center w-full min-h-[285px] p-4 bg-sand dark:bg-wood dark:text-white mt-4 ">
<h1 className="text-dark-600 mt-6 pb-4 text-center">
A{' '}
<a
className="underline"
href="https://reactjs.org/docs/hooks-intro.html"
target="_blank"
rel="noreferrer"
>
React hook
</a>{' '}
to ease connecting to the{' '}
<a href="https://celo.org/" target="_blank" rel="noreferrer">
<CeloWordMark height={16} />
</a>{' '}
<SelectChain />
network.
</h1>
{address ? (
<PrimaryButton onClick={disconnect}>Disconnect</PrimaryButton>
) : (
<PrimaryButton
onClick={() =>
connect().catch((e) => toast.error((e as Error).message))
}
>
Use Celo Now
</PrimaryButton>
)}
<div className="text-slate-600 dark:text-slate-200 my-4 max-w-sm text-center">
Connect to your wallet of choice, then sign and send a test
transaction
</div>
<div
className={`flex flex-col items-center justify-center md:flex-row md:space-x-4 my-2 ${
address || 'hidden'
}`}
>
<SecondaryButton disabled={sending} onClick={testSendTransaction}>
Test sendTransaction
</SecondaryButton>
<SecondaryButton
disabled={sending}
onClick={testSignTypedData}
className="w-full md:w-max"
>
Test signTypedData
</SecondaryButton>
<SecondaryButton
disabled={sending}
onClick={testSignPersonal}
className="w-full md:w-max"
>
Test signPersonal
</SecondaryButton>
</div>
</section>
<UsedBy />
<div className="mt-6">
<div className="text-slate-600 mb-4 max-w-md">
<h2 className="mb-2 text-lg text-slate-900 dark:text-slate-200">
Styling
</h2>
<p className="text-slate-600 dark:text-slate-200 mb-4">
React Celo will go dark when tailwinds tw-dark class is on body or
you can provide a theme
</p>
<label className="toggle-dark dark:text-slate-200">
<span className="toggle-title">
Toggle modal's dark mode (tw-dark)
</span>
<div className="switch">
<input
type="checkbox"
onChange={toggleDarkMode}
defaultValue={isDark() ? 'checked' : 'unchecked'}
/>
<span className="slider round "></span>
</div>
</label>
<h3 className="mb-2 text-base dark:text-slate-200">
Try out some of the pre-made themes below
</h3>
<div className="grid grid-flow-col gap-4 my-4">
{themes.map((theme, i) => (
<ThemeButton
key={i}
theme={theme}
currentTheme={_theme}
onClick={(newTheme) => {
updateTheme(newTheme);
selectTheme(newTheme);
}}
/>
))}
</div>
</div>
<div className="flex flex-col">
{address && (
<div className="w-64 md:w-96 space-y-4 text-slate-700 bg-sand dark:bg-black dark:text-white rounded p-4">
<div className="mb-4">
<div className="text-lg font-bold mb-2 text-slate-900 dark:text-slate-200">
Account Summary on {network.name}
</div>
<div className="space-y-2">
<div>Wallet type: {walletType}</div>
<div>Name: {summary.name || 'Not set'}</div>
<div className="">Address: {truncateAddress(address)}</div>
</div>
</div>
<div>
<div className="text-lg font-bold mb-2 text-slate-900 dark:text-slate-100">
Balances
</div>
<div className="space-y-2">
<div>
CELO: {Web3.utils.fromWei(summary.celo.toFixed())}
</div>
{summary.balances.map((token) => (
<div key={token.symbol}>
{token.symbol}:{' '}
{token.value
? Web3.utils.fromWei(token.value.toFixed())
: token.error}
</div>
))}
</div>
</div>
<div>
<div className="text-lg font-bold mb-2 text-slate-900 dark:text-slate-100">
Fee Currency{' '}
{supportsFeeCurrency || `not supported on ${walletType}`}
</div>
<select
disabled={!supportsFeeCurrency}
value={feeCurrency}
onChange={(event) =>
updateFeeCurrency(event.target.value as CeloTokenContract)
}
className="border border-slate-300 rounded px-4 py-2"
>
{Object.keys(feeTokenMap).map((token) => (
<option key={token} value={token}>
{feeTokenMap[token as keyof typeof feeTokenMap]}
</option>
))}
</select>
</div>
</div>
)}
</div>
</div>
</main>
</div>
);
}
async function getBalances(
stableTokens: { symbol: StableToken; contract: StableTokenWrapper | null }[],
address: string
) {
return Promise.all(
stableTokens.map(async (stable) => {
let value, error;
if (stable.contract) {
value = await stable.contract.balanceOf(address);
} else {
error = 'not deployed in network';
}
return {
symbol: stable.symbol,
value: value,
error: error,
};
})
);
}
export const WC_PROJECT_ID = 'cbd4dfc72c388f372fc45f003becb013';
export default function Home(): React.ReactElement {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
}, []);
return (
<CeloProvider
dapp={{
name: 'react-celo demo',
description: 'A demo DApp to showcase functionality',
url: 'https://react-celo.vercel.app',
icon: 'https://react-celo.vercel.app/favicon.ico',
walletConnectProjectId: WC_PROJECT_ID,
}}
defaultNetwork={Alfajores.name}
connectModal={{
providersOptions: { searchable: true },
}}
>
{isMounted && <HomePage />}
</CeloProvider>
);
}
function UsedBy() {
return (
<div className="mt-6 flex flex-col items-center">
<h2 className="mb-2 text-lg dark:text-white">Used by</h2>
<ul className="flex gap-6">
{[
{
name: 'Celo Tracker ',
url: 'https://www.celotracker.com/',
},
{
name: 'Mobius Money',
url: 'https://mobius.money/',
},
{
name: 'Impact Market',
url: 'https://www.impactmarket.com/',
},
{
name: 'Add yours to the list...',
url: 'https://github.com/celo-org/react-celo/',
},
].map(({ name, url }) => (
<li key={name}>
<a
target="_blank"
className="text-rc-violet dark:text-rc-violet-light"
href={url}
rel="noreferrer"
>
{name}
</a>
</li>
))}
</ul>
</div>
);
}
function SelectChain() {
const { network, networks, updateNetwork } = useCelo();
return (
<select
className="border border-forest outline-forest text-slate-800 rounded px-1 py-1 mr-1"
value={network.name}
onChange={(e) => {
const newNetwork = networks.find((n) => n.name === e.target.value);
if (newNetwork) {
void updateNetwork(newNetwork).catch(console.error);
}
}}
>
{Object.values(networks).map((n) => (
<option key={n.name} value={n.name}>
{n.name}
</option>
))}
</select>
);
}