-
Notifications
You must be signed in to change notification settings - Fork 337
/
App.tsx
795 lines (672 loc) · 19.1 KB
/
App.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import * as React from "react";
import styled from "styled-components";
import WalletConnect from "@walletconnect/browser";
import WalletConnectQRCodeModal from "@walletconnect/qrcode-modal";
import { convertUtf8ToHex } from "@walletconnect/utils";
import { IInternalEvent, IJsonRpcRequest } from "@walletconnect/types";
import Button from "./components/Button";
import Column from "./components/Column";
import Wrapper from "./components/Wrapper";
import Modal from "./components/Modal";
import Header from "./components/Header";
import Loader from "./components/Loader";
import { fonts } from "./styles";
import {
apiGetAccountAssets,
apiGetGasPrices,
apiGetAccountNonce
} from "./helpers/api";
// import {
// recoverTypedSignature
// } from "./helpers/ethSigUtil";
import {
sanitizeHex,
hashPersonalMessage,
recoverPublicKey,
recoverPersonalSignature
} from "./helpers/utilities";
import {
convertAmountToRawNumber,
convertStringToHex
} from "./helpers/bignumber";
import { IAssetData } from "./helpers/types";
import Banner from "./components/Banner";
import AccountAssets from "./components/AccountAssets";
const SLayout = styled.div`
position: relative;
width: 100%;
/* height: 100%; */
min-height: 100vh;
text-align: center;
`;
const SContent = styled(Wrapper)`
width: 100%;
height: 100%;
padding: 0 16px;
`;
const SLanding = styled(Column)`
height: 600px;
`;
const SButtonContainer = styled(Column)`
width: 250px;
margin: 50px 0;
`;
const SConnectButton = styled(Button)`
border-radius: 8px;
font-size: ${fonts.size.medium};
height: 44px;
width: 100%;
margin: 12px 0;
`;
const SContainer = styled.div`
height: 100%;
min-height: 200px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
word-break: break-word;
`;
const SModalContainer = styled.div`
width: 100%;
position: relative;
word-wrap: break-word;
`;
const SModalTitle = styled.div`
margin: 1em 0;
font-size: 20px;
font-weight: 700;
`;
const SModalParagraph = styled.p`
margin-top: 30px;
`;
const SBalances = styled(SLanding)`
height: 100%;
& h3 {
padding-top: 30px;
}
`;
const STable = styled(SContainer)`
flex-direction: column;
text-align: left;
`;
const SRow = styled.div`
width: 100%;
display: flex;
margin: 6px 0;
`;
const SKey = styled.div`
width: 30%;
font-weight: 700;
`;
const SValue = styled.div`
width: 70%;
font-family: monospace;
`;
const STestButtonContainer = styled.div`
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
`;
const STestButton = styled(Button)`
border-radius: 8px;
font-size: ${fonts.size.medium};
height: 44px;
width: 100%;
max-width: 175px;
margin: 12px;
`;
interface IAppState {
walletConnector: WalletConnect | null;
fetching: boolean;
connected: boolean;
chainId: number;
showModal: boolean;
pendingRequest: boolean;
uri: string;
accounts: string[];
address: string;
result: any | null;
assets: IAssetData[];
}
const INITIAL_STATE: IAppState = {
walletConnector: null,
fetching: false,
connected: false,
chainId: 1,
showModal: false,
pendingRequest: false,
uri: "",
accounts: [],
address: "",
result: null,
assets: []
};
class App extends React.Component<any, any> {
public state: IAppState = {
...INITIAL_STATE
};
public walletConnectInit = async () => {
// bridge url
const bridge = "https://bridge.walletconnect.org";
// create new walletConnector
const walletConnector = new WalletConnect({ bridge });
window.walletConnector = walletConnector;
await this.setState({ walletConnector });
// check if already connected
if (!walletConnector.connected) {
// create new session
await walletConnector.createSession();
// get uri for QR Code modal
const uri = walletConnector.uri;
// console log the uri for development
console.log(uri); // tslint:disable-line
// display QR Code modal
WalletConnectQRCodeModal.open(uri, () => {
console.log("QR Code Modal closed"); // tslint:disable-line
});
}
// subscribe to events
await this.subscribeToEvents();
};
public subscribeToEvents = () => {
const { walletConnector } = this.state;
if (!walletConnector) {
return;
}
walletConnector.on("session_update", async (error, payload) => {
console.log('walletConnector.on("session_update")'); // tslint:disable-line
if (error) {
throw error;
}
const { chainId, accounts } = payload.params[0];
this.onSessionUpdate(accounts, chainId);
});
walletConnector.on("connect", (error, payload) => {
console.log('walletConnector.on("connect")'); // tslint:disable-line
if (error) {
throw error;
}
this.onConnect(payload);
});
walletConnector.on("disconnect", (error, payload) => {
console.log('walletConnector.on("disconnect")'); // tslint:disable-line
if (error) {
throw error;
}
this.onDisconnect();
});
if (walletConnector.connected) {
const { chainId, accounts } = walletConnector;
const address = accounts[0];
this.setState({
connected: true,
chainId,
accounts,
address
});
}
this.setState({ walletConnector });
};
public killSession = async () => {
const { walletConnector } = this.state;
if (walletConnector) {
walletConnector.killSession();
}
this.resetApp();
};
public resetApp = async () => {
await this.setState({ ...INITIAL_STATE });
};
public onConnect = async (payload: IInternalEvent) => {
const { chainId, accounts } = payload.params[0];
const address = accounts[0];
await this.setState({
connected: true,
chainId,
accounts,
address
});
WalletConnectQRCodeModal.close();
this.getAccountAssets();
};
public onDisconnect = async () => {
WalletConnectQRCodeModal.close();
this.resetApp();
};
public onSessionUpdate = async (accounts: string[], chainId: number) => {
const address = accounts[0];
await this.setState({ chainId, accounts, address });
await this.getAccountAssets();
};
public getAccountAssets = async () => {
const { address, chainId } = this.state;
this.setState({ fetching: true });
try {
// get account balances
const assets = await apiGetAccountAssets(address, chainId);
await this.setState({ fetching: false, address, assets });
} catch (error) {
console.error(error); // tslint:disable-line
await this.setState({ fetching: false });
}
};
public toggleModal = () =>
this.setState({ showModal: !this.state.showModal });
public testSendTransaction = async () => {
const { walletConnector, address, chainId } = this.state;
if (!walletConnector) {
return;
}
// from
const from = address;
// to
const to = address;
// nonce
const _nonce = await apiGetAccountNonce(address, chainId);
const nonce = sanitizeHex(convertStringToHex(_nonce));
// gasPrice
const gasPrices = await apiGetGasPrices();
const _gasPrice = gasPrices.slow.price;
const gasPrice = sanitizeHex(
convertStringToHex(convertAmountToRawNumber(_gasPrice, 9))
);
// gasLimit
const _gasLimit = 21000;
const gasLimit = sanitizeHex(convertStringToHex(_gasLimit));
// value
const _value = 0;
const value = sanitizeHex(convertStringToHex(_value));
// data
const data = "0x";
// test transaction
const tx = {
from,
to,
nonce,
gasPrice,
gasLimit,
value,
data
};
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// send transaction
const result = await walletConnector.sendTransaction(tx);
// format displayed result
const formattedResult = {
method: "eth_sendTransaction",
txHash: result,
from: address,
to: address,
value: "0 ETH"
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public testSignTransaction = async () => {
const { walletConnector, address, chainId } = this.state;
if (!walletConnector) {
return;
}
// from
const from = address;
// to
const to = address;
// nonce
const _nonce = await apiGetAccountNonce(address, chainId);
const nonce = sanitizeHex(convertStringToHex(_nonce));
// gasPrice
const gasPrices = await apiGetGasPrices();
const _gasPrice = gasPrices.slow.price;
const gasPrice = sanitizeHex(
convertStringToHex(convertAmountToRawNumber(_gasPrice, 9))
);
// gasLimit
const _gasLimit = 21000;
const gasLimit = sanitizeHex(convertStringToHex(_gasLimit));
// value
const _value = 0;
const value = sanitizeHex(convertStringToHex(_value));
// data
const data = "0x";
// test transaction
const tx = {
from,
to,
nonce,
gasPrice,
gasLimit,
value,
data
};
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// send transaction
const result = await walletConnector.signTransaction(tx);
// format displayed result
const formattedResult = {
method: "eth_signTransaction",
result
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public testCustomRequest = async (customRequest: IJsonRpcRequest) => {
const { walletConnector } = this.state;
if (!walletConnector) {
return;
}
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// send message
const result = await walletConnector.sendCustomRequest(customRequest);
// format displayed result
const formattedResult = {
method: customRequest.method,
result
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public testSignMessage = async () => {
const { walletConnector, address } = this.state;
if (!walletConnector) {
return;
}
// test message
const message = "My email is john@doe.com - 1537836206101";
// hash message
const hash = hashPersonalMessage(message);
// eth_sign params
const msgParams = [address, hash];
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// send message
const result = await walletConnector.signMessage(msgParams);
// verify signature
const signer = recoverPublicKey(result, hash);
const verified = signer.toLowerCase() === address.toLowerCase();
// format displayed result
const formattedResult = {
method: "eth_sign",
address,
signer,
verified,
result
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public testSignPersonalMessage = async () => {
const { walletConnector, address } = this.state;
if (!walletConnector) {
return;
}
// test message
const message = "My email is john@doe.com - 1537836206101";
// encode message (hex)
const hexMsg = convertUtf8ToHex(message);
// personal_sign params
const msgParams = [hexMsg, address];
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// send message
const result = await walletConnector.signPersonalMessage(msgParams);
// verify signature
const signer = recoverPersonalSignature(result, message);
const verified = signer.toLowerCase() === address.toLowerCase();
// format displayed result
const formattedResult = {
method: "personal_sign",
address,
signer,
verified,
result
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public testSignTypedData = async () => {
const { walletConnector, address } = this.state;
if (!walletConnector) {
return;
}
// typed data
const typedData = {
types: {
EIP712Domain: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" }
],
Person: [
{ name: "name", type: "string" },
{ name: "account", type: "address" }
],
Mail: [
{ name: "from", type: "Person" },
{ name: "to", type: "Person" },
{ name: "contents", type: "string" }
]
},
primaryType: "Mail",
domain: {
name: "Example Dapp",
version: "0.7.0",
chainId: 1,
verifyingContract: "0x0000000000000000000000000000000000000000"
},
message: {
from: {
name: "Alice",
account: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
},
to: {
name: "Bob",
account: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
},
contents: "Hey, Bob!"
}
};
// eth_signTypedData params
const msgParams = [address, typedData];
try {
// open modal
this.toggleModal();
// toggle pending request indicator
this.setState({ pendingRequest: true });
// sign typed data
const result = await walletConnector.signTypedData(msgParams);
// // verify signature
// const signer = recoverPublicKey(result, typedData);
// const verified = signer.toLowerCase() === address.toLowerCase();
// format displayed result
const formattedResult = {
method: "eth_signTypedData",
address,
// signer,
// verified,
result
};
// display result
this.setState({
walletConnector,
pendingRequest: false,
result: formattedResult || null
});
} catch (error) {
console.error(error); // tslint:disable-line
this.setState({ walletConnector, pendingRequest: false, result: null });
}
};
public render = () => {
const {
assets,
address,
connected,
chainId,
fetching,
showModal,
pendingRequest,
result
} = this.state;
return (
<SLayout>
<Column maxWidth={1000} spanHeight>
<Header
connected={connected}
address={address}
chainId={chainId}
killSession={this.killSession}
/>
<SContent>
{!address && !assets.length ? (
<SLanding center>
<h3>
{`Try out WalletConnect`}
<br />
<span>{`v${process.env.REACT_APP_VERSION}`}</span>
</h3>
<SButtonContainer>
<SConnectButton
left
onClick={this.walletConnectInit}
fetching={fetching}
>
{"Connect to WalletConnect"}
</SConnectButton>
</SButtonContainer>
</SLanding>
) : (
<SBalances>
<Banner />
<h3>Actions</h3>
<Column center>
<STestButtonContainer>
<STestButton left onClick={this.testSendTransaction}>
{"eth_sendTransaction"}
</STestButton>
<STestButton left onClick={this.testSignTransaction}>
{"eth_signTransaction"}
</STestButton>
<STestButton disabled left onClick={this.testCustomRequest}>
{"Custom Request"}
</STestButton>
<STestButton left onClick={this.testSignMessage}>
{"eth_sign"}
</STestButton>
<STestButton left onClick={this.testSignPersonalMessage}>
{"personal_sign"}
</STestButton>
<STestButton disabled left onClick={this.testSignTypedData}>
{"eth_signTypedData"}
</STestButton>
</STestButtonContainer>
</Column>
<h3>Balances</h3>
{!fetching ? (
<AccountAssets chainId={chainId} assets={assets} />
) : (
<Column center>
<SContainer>
<Loader />
</SContainer>
</Column>
)}
</SBalances>
)}
</SContent>
</Column>
<Modal show={showModal} toggleModal={this.toggleModal}>
{pendingRequest ? (
<SModalContainer>
<SModalTitle>{"Pending Call Request"}</SModalTitle>
<SContainer>
<Loader />
<SModalParagraph>
{"Approve or reject request using your wallet"}
</SModalParagraph>
</SContainer>
</SModalContainer>
) : result ? (
<SModalContainer>
<SModalTitle>{"Call Request Approved"}</SModalTitle>
<STable>
{Object.keys(result).map(key => (
<SRow key={key}>
<SKey>{key}</SKey>
<SValue>{result[key].toString()}</SValue>
</SRow>
))}
</STable>
</SModalContainer>
) : (
<SModalContainer>
<SModalTitle>{"Call Request Rejected"}</SModalTitle>
</SModalContainer>
)}
</Modal>
</SLayout>
);
};
}
export default App;