forked from gitcoinco/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.js
2324 lines (1977 loc) · 108 KB
/
cart.js
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @notice Vue component for managing cart and checkout process
* @dev If you need to interact with the Rinkeby Dai contract (e.g. to reset allowances for
* testing), use this one click dapp: https://oneclickdapp.com/drink-leopard/
*/
let BN;
needWalletConnection();
window.addEventListener('dataWalletReady', function(e) {
BN = web3.utils.BN;
}, false);
// Constants
const ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
const gitcoinAddress = '0x00De4B13153673BCAE2616b67bf822500d325Fc3'; // Gitcoin donation address for mainnet and rinkeby
// Contract parameters and constants
const bulkCheckoutAbi = [{ 'anonymous': false, 'inputs': [{ 'indexed': true, 'internalType': 'address', 'name': 'token', 'type': 'address' }, { 'indexed': true, 'internalType': 'uint256', 'name': 'amount', 'type': 'uint256' }, { 'indexed': false, 'internalType': 'address', 'name': 'dest', 'type': 'address' }, { 'indexed': true, 'internalType': 'address', 'name': 'donor', 'type': 'address' }], 'name': 'DonationSent', 'type': 'event' }, { 'anonymous': false, 'inputs': [{ 'indexed': true, 'internalType': 'address', 'name': 'previousOwner', 'type': 'address' }, { 'indexed': true, 'internalType': 'address', 'name': 'newOwner', 'type': 'address' }], 'name': 'OwnershipTransferred', 'type': 'event' }, { 'anonymous': false, 'inputs': [{ 'indexed': false, 'internalType': 'address', 'name': 'account', 'type': 'address' }], 'name': 'Paused', 'type': 'event' }, { 'anonymous': false, 'inputs': [{ 'indexed': true, 'internalType': 'address', 'name': 'token', 'type': 'address' }, { 'indexed': true, 'internalType': 'uint256', 'name': 'amount', 'type': 'uint256' }, { 'indexed': true, 'internalType': 'address', 'name': 'dest', 'type': 'address' }], 'name': 'TokenWithdrawn', 'type': 'event' }, { 'anonymous': false, 'inputs': [{ 'indexed': false, 'internalType': 'address', 'name': 'account', 'type': 'address' }], 'name': 'Unpaused', 'type': 'event' }, { 'inputs': [{ 'components': [{ 'internalType': 'address', 'name': 'token', 'type': 'address' }, { 'internalType': 'uint256', 'name': 'amount', 'type': 'uint256' }, { 'internalType': 'address payable', 'name': 'dest', 'type': 'address' }], 'internalType': 'struct BulkCheckout.Donation[]', 'name': '_donations', 'type': 'tuple[]' }], 'name': 'donate', 'outputs': [], 'stateMutability': 'payable', 'type': 'function' }, { 'inputs': [], 'name': 'owner', 'outputs': [{ 'internalType': 'address', 'name': '', 'type': 'address' }], 'stateMutability': 'view', 'type': 'function' }, { 'inputs': [], 'name': 'pause', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [], 'name': 'paused', 'outputs': [{ 'internalType': 'bool', 'name': '', 'type': 'bool' }], 'stateMutability': 'view', 'type': 'function' }, { 'inputs': [], 'name': 'renounceOwnership', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [{ 'internalType': 'address', 'name': 'newOwner', 'type': 'address' }], 'name': 'transferOwnership', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [], 'name': 'unpause', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [{ 'internalType': 'address payable', 'name': '_dest', 'type': 'address' }], 'name': 'withdrawEther', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [{ 'internalType': 'address', 'name': '_tokenAddress', 'type': 'address' }, { 'internalType': 'address', 'name': '_dest', 'type': 'address' }], 'name': 'withdrawToken', 'outputs': [], 'stateMutability': 'nonpayable', 'type': 'function' }];
const bulkCheckoutAddress = '0x7d655c57f71464B6f83811C55D84009Cd9f5221C';
const batchZkSyncDepositContractAddress = '0x9D37F793E5eD4EbD66d62D505684CD9f756504F6';
const batchZkSyncDepositContractAbi = '[{"inputs":[{"internalType":"address","name":"_zkSync","type":"address"},{"internalType":"contract IERC20[]","name":"_tokens","type":"address[]"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AllowanceSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20","name":"token","type":"address"},{"indexed":true,"internalType":"uint104","name":"amount","type":"uint104"},{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"DepositMade","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"ETH_TOKEN_PLACHOLDER","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"},{"components":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint104","name":"amount","type":"uint104"}],"internalType":"struct BatchZkSyncDeposit.Deposit[]","name":"_deposits","type":"tuple[]"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"setAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"zkSync","outputs":[{"internalType":"contract IZkSync","name":"","type":"address"}],"stateMutability":"view","type":"function"}]';
const zkSyncContractAbi = '[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"blockNumber","type":"uint32"}],"name":"BlockCommit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"blockNumber","type":"uint32"}],"name":"BlockVerification","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"totalBlocksVerified","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"totalBlocksCommitted","type":"uint32"}],"name":"BlocksRevert","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"zkSyncBlockId","type":"uint32"},{"indexed":true,"internalType":"uint32","name":"accountId","type":"uint32"},{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint16","name":"tokenId","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"DepositCommit","type":"event"},{"anonymous":false,"inputs":[],"name":"ExodusMode","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint32","name":"nonce","type":"uint32"},{"indexed":false,"internalType":"bytes","name":"fact","type":"bytes"}],"name":"FactAuth","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"zkSyncBlockId","type":"uint32"},{"indexed":true,"internalType":"uint32","name":"accountId","type":"uint32"},{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint16","name":"tokenId","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"FullExitCommit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint64","name":"serialId","type":"uint64"},{"indexed":false,"internalType":"enum Operations.OpType","name":"opType","type":"uint8"},{"indexed":false,"internalType":"bytes","name":"pubData","type":"bytes"},{"indexed":false,"internalType":"uint256","name":"expirationBlock","type":"uint256"}],"name":"NewPriorityRequest","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"uint16","name":"tokenId","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"},{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"OnchainDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint16","name":"tokenId","type":"uint16"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"OnchainWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"queueStartIndex","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"queueEndIndex","type":"uint32"}],"name":"PendingWithdrawalsAdd","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"queueStartIndex","type":"uint32"},{"indexed":false,"internalType":"uint32","name":"queueEndIndex","type":"uint32"}],"name":"PendingWithdrawalsComplete","type":"event"},{"constant":true,"inputs":[],"name":"EMPTY_STRING_KECCAK","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint32","name":"","type":"uint32"}],"name":"authFacts","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes22","name":"","type":"bytes22"}],"name":"balancesToWithdraw","outputs":[{"internalType":"uint128","name":"balanceToWithdraw","type":"uint128"},{"internalType":"uint8","name":"gasReserveValue","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint32","name":"","type":"uint32"}],"name":"blocks","outputs":[{"internalType":"uint32","name":"committedAtBlock","type":"uint32"},{"internalType":"uint64","name":"priorityOperations","type":"uint64"},{"internalType":"uint32","name":"chunks","type":"uint32"},{"internalType":"bytes32","name":"withdrawalsDataHash","type":"bytes32"},{"internalType":"bytes32","name":"commitment","type":"bytes32"},{"internalType":"bytes32","name":"stateRoot","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint64","name":"_n","type":"uint64"}],"name":"cancelOutstandingDepositsForExodusMode","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_blockNumber","type":"uint32"},{"internalType":"uint32","name":"_feeAccount","type":"uint32"},{"internalType":"bytes32[]","name":"_newBlockInfo","type":"bytes32[]"},{"internalType":"bytes","name":"_publicData","type":"bytes"},{"internalType":"bytes","name":"_ethWitness","type":"bytes"},{"internalType":"uint32[]","name":"_ethWitnessSizes","type":"uint32[]"}],"name":"commitBlock","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_n","type":"uint32"}],"name":"completeWithdrawals","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"},{"internalType":"uint104","name":"_amount","type":"uint104"},{"internalType":"address","name":"_franklinAddr","type":"address"}],"name":"depositERC20","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_franklinAddr","type":"address"}],"name":"depositETH","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_accountId","type":"uint32"},{"internalType":"uint16","name":"_tokenId","type":"uint16"},{"internalType":"uint128","name":"_amount","type":"uint128"},{"internalType":"uint256[]","name":"_proof","type":"uint256[]"}],"name":"exit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"uint32","name":"","type":"uint32"},{"internalType":"uint16","name":"","type":"uint16"}],"name":"exited","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"exodusMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"firstPendingWithdrawalIndex","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"firstPriorityRequestId","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_accountId","type":"uint32"},{"internalType":"address","name":"_token","type":"address"}],"name":"fullExit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"uint16","name":"_tokenId","type":"uint16"}],"name":"getBalanceToWithdraw","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"getNoticePeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"initializationParameters","type":"bytes"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"isReadyForUpgrade","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"numberOfPendingWithdrawals","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint32","name":"","type":"uint32"}],"name":"pendingWithdrawals","outputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint16","name":"tokenId","type":"uint16"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint64","name":"","type":"uint64"}],"name":"priorityRequests","outputs":[{"internalType":"enum Operations.OpType","name":"opType","type":"uint8"},{"internalType":"bytes","name":"pubData","type":"bytes"},{"internalType":"uint256","name":"expirationBlock","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_maxBlocksToRevert","type":"uint32"}],"name":"revertBlocks","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_pubkey_hash","type":"bytes"},{"internalType":"uint32","name":"_nonce","type":"uint32"}],"name":"setAuthPubkeyHash","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalBlocksCommitted","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalBlocksVerified","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalCommittedPriorityRequests","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalOpenPriorityRequests","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"triggerExodusIfNeeded","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"upgradeParameters","type":"bytes"}],"name":"upgrade","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"upgradeCanceled","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"upgradeFinishes","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"upgradeNoticePeriodStarted","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradePreparationActivationTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradePreparationActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"upgradePreparationStarted","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint32","name":"_blockNumber","type":"uint32"},{"internalType":"uint256[]","name":"_proof","type":"uint256[]"},{"internalType":"bytes","name":"_withdrawalsData","type":"bytes"}],"name":"verifyBlock","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"},{"internalType":"uint128","name":"_amount","type":"uint128"}],"name":"withdrawERC20","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint128","name":"_amount","type":"uint128"},{"internalType":"uint128","name":"_maxAmount","type":"uint128"}],"name":"withdrawERC20Guarded","outputs":[{"internalType":"uint128","name":"withdrawnAmount","type":"uint128"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint128","name":"_amount","type":"uint128"}],"name":"withdrawETH","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]';
const zkSyncContractAddressMainnet = '0xaBEA9132b05A70803a4E85094fD0e1800777fBEF';
const zkSyncContractAddressRinkeby = '0x82F67958A5474e40E1485742d648C0b0686b6e5D';
// Grant data
let grantHeaders = [ 'Grant', 'Amount', 'Total CLR Match Amount' ]; // cart column headers
let grantData = []; // data for grants in cart, initialized in mounted hook
Vue.use(VueTelInput);
Vue.component('grants-cart', {
delimiters: [ '[[', ']]' ],
data: function() {
return {
// Checkout, shared
adjustGitcoinFactor: false, // if true, show section for user to adjust Gitcoin's percentage
tokenList: undefined, // array of all tokens for selected network
isLoading: undefined,
gitcoinFactorRaw: 5, // By default, 5% of donation amount goes to Gitcoin
grantHeaders,
grantData,
comments: undefined,
hideWalletAddress: true,
windowWidth: window.innerWidth,
userAddress: undefined,
// Checkout, zkSync
zkSyncContractAddress: undefined,
depositContractToUse: undefined, // what address to deposit through, batch contract or regular zkSync contract
ethersProvider: undefined,
signer: undefined, // signer from regular web3 wallet
syncProvider: undefined,
gitcoinSyncWallet: undefined, // wallet from zkSync wallet using Gitcoin-specific signature
nominalSyncWallet: undefined, // default wallet from zkSync using their SDK
showZkSyncModal: false,
zkSyncAllowanceData: undefined,
zkSyncDepositTxHash: undefined,
zkSyncCheckoutStep1Status: 'not-started', // valid values: not-started, pending, complete
zkSyncCheckoutStep2Status: 'not-started', // valid values: not-started, pending, complete, not-applicable
zkSyncCheckoutStep3Status: 'not-started', // valid values: not-started, pending, complete
numberOfConfirmationsNeeded: undefined, // number of confirmations user must wait for deposit tx
currentConfirmationNumber: 0, // current number of confirmations received for deposit tx
zkSyncCheckoutFlowStep: 0, // used for UI updates during the final step
currentTxNumber: 0, // used as part of the UI updates during the final step
zkSyncWasInterrupted: undefined, // read from local storage, true if user closes window before deposit is complete
showAdvancedSettings: false, // advanced settings let user deposit extra funds into zkSync
zkSyncAdditionalDeposits: [], // array of objects of: { amount: ABC, tokenSymbol: 'XYZ' }
zkSyncDonationInputsEthAmount: undefined, // version of donationInputsEthAmount, but used to account for additional deposit amount
hasSufficientZkSyncBalance: true, // starts as true, is true if user already has enough funds in their zkSync account for checkout
maxPossibleSignatures: 4, // for Flow A, start by assuming 4 -- two logins, set signing key, one transfer
isZkSyncModalLoading: false, // modal requires async actions before loading, so show loading spinner to improve UX
zkSyncWalletState: undefined, // state of user's nominal zkSync wallet
// SMS validation
csrf: $("input[name='csrfmiddlewaretoken']").val(),
validationStep: 'intro',
showValidation: false,
phone: '',
validNumber: false,
errorMessage: '',
verified: document.verified,
code: '',
timePassed: 0,
timeInterval: 0,
display_email_option: false,
countDownActive: false
};
},
computed: {
// Returns true if user is logged in with GitHub, false otherwise
isLoggedIn() {
return document.contxt.github_handle;
},
// Returns true of screen size is smaller than 576 pixels (Bootstrap's small size)
isMobileDevice() {
return this.windowWidth < 576;
},
// Array of arrays, item i lists supported tokens for donating to grant given by grantData[i]
currencies() {
if (!this.grantData || !this.tokenList)
return undefined;
// Get supported tokens for each grant
const currencies = this.grantData.map(grant => {
// Return full list if grant accepts all tokens
if (grant.grant_token_address === '0x0000000000000000000000000000000000000000') {
return this.tokenList.map(token => token.name);
}
// Return ETH + selected token otherwise
let allowedTokens = ['ETH'];
this.tokenList.forEach(tokenData => {
if (tokenData.addr === grant.grant_token_address)
allowedTokens.push(tokenData.name);
});
return allowedTokens;
});
return currencies;
},
// Percentage of donation that goes to Gitcoin
gitcoinFactor() {
return Number(this.gitcoinFactorRaw) / 100;
},
// Amounts being donated to grants
donationsToGrants() {
return this.donationSummaryTotals(1 - this.gitcoinFactor);
},
// Amounts being donated to Gitcoin
donationsToGitcoin() {
return this.donationSummaryTotals(this.gitcoinFactor);
},
// Total amounts being donated
donationsTotal() {
return this.donationSummaryTotals(1);
},
// String describing user's donations to grants
donationsToGrantsString() {
return this.donationSummaryString('donationsToGrants', 2);
},
// String describing user's donations to Gitcoin
donationsToGitcoinString() {
return this.donationSummaryString('donationsToGitcoin', 4);
},
// String describing user's total donations
donationsTotalString() {
return this.donationSummaryString('donationsTotal', 2);
},
// Array of objects containing all donations and associated data
donationInputs() {
if (!this.grantData)
return undefined;
// Generate array of objects containing donation info from cart
let gitcoinFactor = 100 * this.gitcoinFactor;
const donations = this.grantData.map((grant, index) => {
const tokenDetails = this.getTokenByName(grant.grant_donation_currency);
const amount = this.toWeiString(
Number(grant.grant_donation_amount),
tokenDetails.decimals,
100 - gitcoinFactor
);
return {
token: tokenDetails.addr,
amount,
dest: grant.grant_admin_address,
name: grant.grant_donation_currency, // token abbreviation, e.g. DAI
grant, // all grant data from localStorage
comment: this.comments[index], // comment left by donor to grant owner
tokenApprovalTxHash: '' // tx hash of token approval required for this donation
};
});
// Append the Gitcoin donations (these already account for gitcoinFactor)
Object.keys(this.donationsToGitcoin).forEach((token) => {
const tokenDetails = this.getTokenByName(token);
const amount = this.toWeiString(this.donationsToGitcoin[token], tokenDetails.decimals);
const gitcoinGrantInfo = {
// Manually fill this in so we can access it for the POST requests.
// We use empty strings for fields that are not needed here
grant_admin_address: gitcoinAddress,
grant_contract_address: '0xeb00a9c1Aa8C8f4b20C5d3dDA2bbC64Aa39AF752',
grant_contract_version: '1',
grant_donation_amount: this.donationsToGitcoin[token],
grant_donation_clr_match: '',
grant_donation_currency: token,
grant_donation_num_rounds: 1,
grant_id: '86',
grant_image_css: '',
grant_logo: '',
grant_slug: 'gitcoin-sustainability-fund',
grant_title: 'Gitcoin Grants Round 7+ Development Fund',
grant_token_address: '0x0000000000000000000000000000000000000000',
grant_token_symbol: '',
isAutomatic: true // we add this field to help properly format the POST requests
};
donations.push({
amount,
token: tokenDetails.addr,
dest: gitcoinAddress,
name: token, // token abbreviation, e.g. DAI
grant: gitcoinGrantInfo, // equivalent to grant data from localStorage
comment: '', // comment left by donor to grant owner
tokenApprovalTxHash: '' // tx hash of token approval required for this donation
});
});
return donations;
},
// Total amount of ETH that needs to be sent along with the transaction
donationInputsEthAmount() {
// Get the total ETH we need to send
const initialValue = new BN('0');
const ethAmountBN = this.donationInputs.reduce((accumulator, currentValue) => {
return currentValue.token === ETH_ADDRESS
? accumulator.add(new BN(currentValue.amount)) // ETH donation
: accumulator.add(new BN('0')); // token donation
}, initialValue);
return ethAmountBN.toString(10);
},
// Estimated gas limit for the transaction
donationInputsGasLimitL1() {
// The below heuristics are used instead of `estimateGas()` so we can send the donation
// transaction before the approval txs are confirmed, because if the approval txs
// are not confirmed then estimateGas will fail.
// If we have a cart where all donations are in Dai, we use a linear regression to
// estimate gas costs based on real checkout transaction data, and add a 50% margin
const donationCurrencies = this.donationInputs.map(donation => donation.token);
const daiAddress = this.getTokenByName('DAI').addr;
const isAllDai = donationCurrencies.every((addr) => addr === daiAddress);
if (isAllDai) {
if (donationCurrencies.length === 1) {
// Special case since we overestimate here otherwise
return 80000;
}
// Below curve found by running script at the repo below around 9AM PT on 2020-Jun-19
// then generating a conservative best-fit line
// https://github.com/mds1/Gitcoin-Checkout-Gas-Analysis
return 25000 * donationCurrencies.length + 125000;
}
// Otherwise, based on contract tests, we use the more conservative heuristic below to get
// a gas estimate. The estimates used here are based on testing the cost of a single
// donation (i.e. one item in the cart). Because gas prices go down with batched
// transactions, whereas this assumes they're constant, this gives us a conservative estimate
const gasLimit = this.donationInputs.reduce((accumulator, currentValue) => {
const tokenAddr = currentValue.token.toLowerCase();
if (currentValue.token === ETH_ADDRESS) {
return accumulator + 50000; // ETH donation gas estimate
} else if (tokenAddr === '0x960b236A07cf122663c4303350609A66A7B288C0'.toLowerCase()) {
return accumulator + 170000; // ANT donation gas estimate
} else if (tokenAddr === '0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d'.toLowerCase()) {
return accumulator + 500000; // aDAI donation gas estimate
} else if (tokenAddr === '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643'.toLowerCase()) {
return accumulator + 450000; // cDAI donation gas estimate
}
return accumulator + 100000; // generic token donation gas estimate
}, 0);
return gasLimit;
},
maxPossibleTransactions() {
if (!this.donationsTotal) {
return '-';
}
let number = 1;
Object.keys(this.donationsTotal).forEach((token) => {
if (token !== 'ETH') {
number += 1;
}
});
return number;
},
// =============================================================================================
// ============================= START ZKSYNC COMPUTED PROPERTIES ==============================
// =============================================================================================
// Link to L2 account (Flow A) or L1 deposit transaction (Flow B) on block explorer. For L2
// we link to an account instead of a transfer because there are multiple transfers if multiple
// tokens are being used
zkSyncBlockExplorerUrl() {
// Flow A, zkScan link
if (this.hasSufficientZkSyncBalance) {
if (document.web3network === 'mainnet')
return `https://zkscan.io/explorer/accounts/${this.userAddress}`;
return `https://${document.web3network}.zkscan.io/explorer/accounts/${this.userAddress}`;
}
// Flow B, etherscan link
if (!this.zkSyncDepositTxHash)
return undefined;
if (document.web3network === 'mainnet')
return `https://etherscan.io/tx/${this.zkSyncDepositTxHash}`;
return `https://${document.web3network}.etherscan.io/tx/${this.zkSyncDepositTxHash}`;
},
// Array of supported tokens
zkSyncSupportedTokens() {
if (!document.web3network)
return [];
if (document.web3network === 'rinkeby')
return [ 'ETH', 'USDT', 'LINK' ];
return [ 'ETH', 'DAI', 'USDC', 'USDT', 'LINK', 'WBTC', 'PAN' ];
},
// Estimated gas limit for zkSync checkout
zkSyncDonationInputsGasLimit() {
// The below heuristics are used instead of `estimateGas()` so we can send the donation
// transaction before the approval txs are confirmed, because if the approval txs
// are not confirmed then estimateGas will fail.
// zkSync transfer costs from their docs
const gasPerTransfer = 2000;
// Deposit into zkSync costs
const depositGasCost = {
'ETH': 200000,
'DAI': 250000,
'USDC': 250000,
'USDT': 250000,
'LINK': 250000,
'WBTC': 250000,
'PAN': 250000
};
// Make sure all tokens in cart are supported
const donationCurrencies = this.donationInputs.map(donation => donation.name);
for (let i = 0; i < donationCurrencies.length; i += 1) {
if (!this.zkSyncSupportedTokens.includes(donationCurrencies[i])) {
// Include that token is not supported
return '10000000';
}
}
// If user has enough funds in their zkSync wallet, estimation is straightforward
if (this.hasSufficientZkSyncBalance) {
return String(this.donationInputs.length * gasPerTransfer);
}
// Otherwise, if they only have one token in cart, use those estimates
const numberOfTokens = Array.from(new Set(donationCurrencies)).length;
switch (numberOfTokens) {
case 1:
tokenName = donationCurrencies[0];
return depositGasCost[tokenName];
case 2:
return 250000 * 2;
case 3:
return 250000 * 3;
case 4:
return 250000 * 4;
case 5:
return 250000 * 5;
case 6:
return 250000 * 6;
case 7:
return 250000 * 7;
default:
// Too many tokens, zkSync does not support them all
return '10000000';
}
},
/**
* @notice Returns a list of tokens in the users cart that do not support zkSync
*/
zkSyncUnsupportedTokens() {
let unsupported = [];
const donationCurrencies = this.donationInputs.map(donation => donation.name);
for (let i = 0; i < donationCurrencies.length; i += 1) {
if (!this.zkSyncSupportedTokens.includes(donationCurrencies[i])) {
// Include that token is not supported
unsupported.push(donationCurrencies[i]);
}
}
return Array.from(new Set(unsupported));
},
/**
* @notice Make a recommendation to the user about which checkout to use
*/
checkoutRecommendation() {
const estimateL1 = Number(this.donationInputsGasLimitL1);
const estimateZkSync = Number(this.zkSyncDonationInputsGasLimit);
if (estimateL1 < estimateZkSync) {
const savingsInGas = estimateZkSync - estimateL1;
const savingsInPercent = Math.round(savingsInGas / estimateZkSync * 100);
return {
name: 'Standard checkout',
savingsInGas,
savingsInPercent
};
}
const savingsInGas = estimateL1 - estimateZkSync;
const savingsInPercent = Math.round(savingsInGas / estimateL1 * 100);
return {
name: 'zkSync',
savingsInGas,
savingsInPercent
};
}
// =============================================================================================
// ============================== END ZKSYNC COMPUTED PROPERTIES ===============================
// =============================================================================================
},
methods: {
dismissVerification() {
localStorage.setItem('dismiss-sms-validation', true);
this.showValidation = false;
},
showSMSValidationModal() {
if (!this.verified) {
this.showValidation = true;
} else {
_alert('You have been verified previously');
}
},
validateCode() {
const vm = this;
if (vm.code) {
const verificationRequest = fetchData('/sms/validate/', 'POST', {
code: vm.code,
phone: vm.phone
}, {'X-CSRFToken': vm.csrf});
$.when(verificationRequest).then(response => {
vm.verificationEnabled = false;
vm.verified = true;
vm.validationStep = 'verifyNumber';
vm.showValidation = false;
_alert('You have been verified', 'success');
}).catch((e) => {
vm.errorMessage = e.responseJSON.msg;
});
}
},
startVerification() {
this.phone = '';
this.validationStep = 'requestVerification';
this.validNumber = false;
this.errorMessage = '';
this.code = '';
this.timePassed = 0;
this.timeInterval = 0;
this.display_email_option = false;
},
countdown() {
const vm = this;
if (!vm.countDownActive) {
vm.countDownActive = true;
setInterval(() => {
vm.timePassed += 1;
}, 1000);
}
},
resendCode(delivery_method) {
const e164 = this.phone.replace(/\s/g, '');
const vm = this;
vm.errorMessage = '';
if (vm.validNumber) {
const verificationRequest = fetchData('/sms/request', 'POST', {
phone: e164,
delivery_method: delivery_method || 'sms'
}, {'X-CSRFToken': vm.csrf});
vm.errorMessage = '';
$.when(verificationRequest).then(response => {
// set the cooldown time to one minute
this.timePassed = 0;
this.timeInterval = 60;
this.countdown();
this.display_email_option = response.allow_email;
}).catch((e) => {
vm.errorMessage = e.responseJSON.msg;
});
}
},
requestVerification(event) {
const e164 = this.phone.replace(/\s/g, '');
const vm = this;
if (vm.validNumber) {
const verificationRequest = fetchData('/sms/request', 'POST', {
phone: e164
}, {'X-CSRFToken': vm.csrf});
vm.errorMessage = '';
$.when(verificationRequest).then(response => {
vm.validationStep = 'verifyNumber';
this.timePassed = 0;
this.timeInterval = 60;
this.countdown();
this.display_email_option = response.allow_email;
}).catch((e) => {
vm.errorMessage = e.responseJSON.msg;
});
}
},
isValidNumber(validation) {
console.log(validation);
this.validNumber = validation.isValid;
},
loginWithGitHub() {
window.location.href = `${window.location.origin}/login/github/?next=/grants/cart`;
},
confirmClearCart() {
if (confirm('are you sure')) {
this.clearCart();
}
},
clearCart() {
CartData.clearCart();
this.grantData = [];
update_cart_title();
},
shareCart() {
_alert('Cart URL copied to clipboard', 'success', 1000);
copyToClipboard(CartData.share_url());
},
removeGrantFromCart(id) {
CartData.removeIdFromCart(id);
this.grantData = CartData.loadCart();
update_cart_title();
},
addComment(id, text) {
// Set comment at this index to an empty string to show textarea
this.grantData[id].grant_comments = text ? text : '';
CartData.setCart(this.grantData);
this.$forceUpdate();
$('input[type=textarea]').focus();
},
/**
* @notice Generates an object where keys are token names and value are the total amount
* being donated in that token. Scale factor scales the amounts used by a constant
* @dev The addition here is based on human-readable numbers so BN is not needed
*/
donationSummaryTotals(scaleFactor = 1) {
const totals = {};
this.grantData.forEach(grant => {
if (!totals[grant.grant_donation_currency]) {
// First time seeing this token, set the field and initial value
totals[grant.grant_donation_currency] = Number(grant.grant_donation_amount) * scaleFactor;
} else {
// We've seen this token, so just update the total
totals[grant.grant_donation_currency] += (Number(grant.grant_donation_amount) * scaleFactor);
}
});
return totals;
},
/**
* @notice Returns a string of the form "3 DAI + 0.5 ETH + 10 USDC" which describe the
* user's donations for a given property
*/
donationSummaryString(propertyName, maximumFractionDigits = 2) {
if (!this[propertyName]) {
return undefined;
}
let string = '';
Object.keys(this[propertyName]).forEach(key => {
// Round to 2 digits
const amount = this[propertyName][key];
const formattedAmount = amount.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits
});
if (string === '') {
string += `${formattedAmount} ${key}`;
} else {
string += `+ ${formattedAmount} ${key}`;
}
});
return string;
},
handleError(err) {
console.error(err); // eslint-disable-line no-console
let message = 'There was an error';
if (err.message)
message = err.message;
else if (err.msg)
message = err.msg;
else if (typeof err === 'string')
message = err;
_alert(message, 'error');
indicateMetamaskPopup(true);
},
/**
* @notice Get token address and decimals
* @dev We use this instead of tokenNameToDetails in tokens.js because we use a different
* address to represent ETH
* @param {String} name Token name, e.g. ETH or DAI
*/
getTokenByName(name) {
if (name === 'ETH') {
return {
addr: ETH_ADDRESS,
name: 'ETH',
decimals: 18,
priority: 1
};
}
var network = document.web3network;
return tokens(network).filter(token => token.name === name)[0];
},
/**
* @notice Returns a string of the human-readable value, in "Wei", where by wei we refer
* to the proper integer value based on the number of token decimals
* @param {Number} number Human-readable number to convert, e.g. 0.1 or 3
* @param {Number} decimals Number of decimals for conversion to Wei
* @param {Number} scaleFactor Factor to multiply number by, as percent*100, e.g. value of 100
* means multiply by scale factor of 1
*/
toWeiString(number, decimals, scaleFactor = 100) {
let wei;
try {
wei = web3.utils.toWei(String(number));
} catch (e) {
// When numbers are too small toWei fails because there's too many decimal places
wei = Math.round(number * 10 ** 18);
}
const base = new BN(10, 10);
const factor = base.pow(new BN(18 - decimals, 10));
const scale = new BN(scaleFactor, 10);
const amount = (new BN(wei)).mul(scale).div(new BN(100, 10));
return amount.div(factor).toString(10);
},
async applyAmountToAllGrants(grant) {
const preferredAmount = grant.grant_donation_amount;
const preferredTokenName = grant.grant_donation_currency;
const fallbackAmount = await this.valueToEth(preferredAmount, preferredTokenName);
this.grantData.forEach((grant, index) => {
const acceptedCurrencies = this.currencies[index]; // tokens accepted by this grant
if (!acceptedCurrencies.includes(preferredTokenName)) {
// If the selected token is not available, fallback to ETH
this.grantData[index].grant_donation_amount = fallbackAmount;
this.grantData[index].grant_donation_currency = 'ETH';
} else {
// Otherwise use the user selected option
this.grantData[index].grant_donation_amount = preferredAmount;
this.grantData[index].grant_donation_currency = preferredTokenName;
}
});
},
/**
* @notice Must be called at the beginning of each checkout flow (L1, zkSync, etc.)
*/
async initializeCheckout() {
// Prompt web3 login if not connected
if (!provider) {
return await onConnect();
}
if (typeof ga !== 'undefined') {
ga('send', 'event', 'Grant Checkout', 'click', 'Person');
}
// Throw if invalid Gitcoin contribution percentage
if (Number(this.gitcoinFactorRaw) < 0 || Number(this.gitcoinFactorRaw) > 99) {
throw new Error('Gitcoin contribution amount must be between 0% and 99%');
}
// Throw if there's negative values in the cart
this.donationInputs.forEach(donation => {
if (Number(donation.amount) < 0) {
throw new Error('Cannot have negative donation amounts');
}
});
// Initialization complete, return address of current user
const userAddress = (await web3.eth.getAccounts())[0];
return userAddress;
},
/**
* @notice For each token, checks if an approval is needed against the specified contract, and
* returns the data
* @param userAddress User's web3 address
* @param targetContract Address of the contract to check allowance against (e.g. the
* regular BulkCheckout contract, the zkSync contract, etc.)
*/
async getAllowanceData(userAddress, targetContract) {
// Get list of tokens user is donating with
const selectedTokens = Object.keys(this.donationsToGrants);
// Initialize return variable
let allowanceData = [];
// Define function that calculates the total required allowance for the specified token
const calcTotalAllowance = (tokenDetails) => {
const initialValue = new BN('0');
return this.donationInputs.reduce((accumulator, currentValue) => {
return currentValue.token === tokenDetails.addr
? accumulator.add(new BN(currentValue.amount)) // token donation
: accumulator.add(new BN('0')); // ETH donation
}, initialValue);
};
// Loop over each token in the cart and check allowance
for (let i = 0; i < selectedTokens.length; i += 1) {
const tokenName = selectedTokens[i];
const tokenDetails = this.getTokenByName(tokenName);
// If ETH donation no approval is necessary, just check balance
if (tokenDetails.name === 'ETH') {
const userEthBalance = await web3.eth.getBalance(userAddress);
if (new BN(userEthBalance, 10).lt(new BN(this.donationInputsEthAmount, 10))) {
// User ETH balance is too small compared to selected donation amounts
throw new Error('Insufficient ETH balance to complete checkout');
}
// ETH balance is sufficient, continue to next iteration since no approval check
continue;
}
// Get current allowance
const tokenContract = new web3.eth.Contract(token_abi, tokenDetails.addr);
const allowance = new BN(await getAllowance(targetContract, tokenDetails.addr), 10);
// Get required allowance based on donation amounts
// We use reduce instead of this.donationsTotal because this.donationsTotal will
// not have floating point errors, but the actual amounts used will
const requiredAllowance = calcTotalAllowance(tokenDetails);
// Check user token balance against requiredAllowance
const userTokenBalance = await tokenContract.methods
.balanceOf(userAddress)
.call({ from: userAddress });
if (new BN(userTokenBalance, 10).lt(requiredAllowance)) {
// Balance is too small, exit checkout flow
throw new Error(`Insufficient ${tokenName} balance to complete checkout`, 'error');
}
// If no allowance is needed, continue to next token
if (allowance.gte(new BN(requiredAllowance))) {
continue;
}
// If we do need to set the allowance, save off the required info to request it later
allowanceData.push({
allowance: requiredAllowance.toString(),
contract: tokenContract,
tokenName
});
} // end checking approval requirements for each token being used for donations
return allowanceData;
},
/**
* @notice Requests all allowances and executes checkout once all allowance transactions
* have been sent
* @param allowanceData Output from getAllowanceData() function
* @param targetContract Address of the contract to check allowance against (e.g. the
* regular BulkCheckout contract, the zkSync contract, etc.)
* @param callback Function to after allowance approval transactions are sent
* @param callbackParams Array of input arguments to pass to the callback function
*/
async requestAllowanceApprovalsThenExecuteCallback(
allowanceData,
userAddress,
targetContract,
callback = undefined,
callbackParams = []
) {
console.log('Requesting token approvals...');
if (allowanceData.length === 0) {
console.log('✅ No approvals needed');
if (callback)
await callback(...callbackParams);
return;
}
indicateMetamaskPopup();
for (let i = 0; i < allowanceData.length; i += 1) {
const allowance = allowanceData[i].allowance;
const contract = allowanceData[i].contract;
const tokenName = allowanceData[i].tokenName;
const approvalTx = contract.methods.approve(targetContract, allowance);
// We split this into two very similar branches, because on the last approval
// we execute the callback (the main donation flow) after we get the transaction hash
if (i !== allowanceData.length - 1) {
approvalTx
.send({ from: userAddress })
.on('transactionHash', (txHash) => {
this.setApprovalTxHash(tokenName, txHash);
})
.on('error', (error, receipt) => {
// If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
this.handleError(error);
});
} else {
approvalTx
.send({ from: userAddress })
.on('transactionHash', async(txHash) => { // eslint-disable-line no-loop-func
indicateMetamaskPopup(true);
this.setApprovalTxHash(tokenName, txHash);
console.log('✅ Received all token approvals');
if (callback) {
await callback(...callbackParams);
}
})
.on('error', (error, receipt) => {
// If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
this.handleError(error);
});
}
}
},
/**
* @notice Checkout flow
*/
async checkout() {
try {
// Setup -----------------------------------------------------------------------------------
const userAddress = await this.initializeCheckout();
// Token approvals and balance checks (just checks data, does not execute approavals)
const allowanceData = await this.getAllowanceData(
userAddress,
bulkCheckoutAddress
);
// Send donation if no approvals -----------------------------------------------------------
if (allowanceData.length === 0) {
// Send transaction and exit function
this.sendDonationTx(userAddress);
return;
}
// Request approvals then send donations ---------------------------------------------------
await this.requestAllowanceApprovalsThenExecuteCallback(
allowanceData,
userAddress,
bulkCheckoutAddress,
this.sendDonationTx,
[userAddress]
);
} catch (err) {
this.handleError(err);
}
},
/**
* @notice Saves off the transaction hash of the approval transaction to include with the POST
* payload to be stored in Gitcoin's DB
*/
setApprovalTxHash(tokenName, txHash) {
this.donationInputs.forEach((donation, index) => {
if (donation.name === tokenName) {
this.donationInputs[index].tokenApprovalTxHash = txHash;
}
});
},
/**
* Returns donation inputs for a transaction, filtered to remove unused data
*/
getDonationInputs() {
// We use parse and stringify to avoid mutating this.donationInputs since we use it later
const donationInputs = JSON.parse(JSON.stringify(this.donationInputs)).map(donation => {
delete donation.name;
delete donation.grant;
delete donation.comment;
delete donation.tokenApprovalTxHash;
return donation;
});
// Remove donations of zero value
const donationInputsFiltered = donationInputs.filter(donation => {
return Number(donation.amount) !== 0;
});
return donationInputsFiltered;
},
async sendDonationTx(userAddress) {
// Get our donation inputs
const bulkTransaction = new web3.eth.Contract(bulkCheckoutAbi, bulkCheckoutAddress);
const donationInputsFiltered = this.getDonationInputs();
indicateMetamaskPopup();
bulkTransaction.methods
.donate(donationInputsFiltered)
.send({ from: userAddress, gas: this.donationInputsGasLimitL1, value: this.donationInputsEthAmount })
.on('transactionHash', async(txHash) => {
console.log('Donation transaction hash: ', txHash);
indicateMetamaskPopup(true);
_alert('Saving contributions. Please do not leave this page.', 'success', 2000);
await this.postToDatabase(txHash, bulkCheckoutAddress, userAddress); // Save contributions to database
await this.finalizeCheckout(); // Update UI and redirect
})
.on('error', (error, receipt) => {
// If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
this.handleError(error);
});
},
/**
* @notice POSTs donation data to database. Intended to be called from finalizeCheckout()
*/
async postToDatabase(txHash, contractAddress, userAddress) {
// this.donationInputs is the array used for bulk donations
// We loop through each donation and POST the required data
const donations = this.donationInputs;
const csrfmiddlewaretoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
// Configure template payload
const saveSubscriptionPayload = {
// Values that are constant for all donations
contributor_address: userAddress,
csrfmiddlewaretoken,
frequency_count: 1,
frequency_unit: 'rounds',
gas_price: 0,
gitcoin_donation_address: gitcoinAddress,
hide_wallet_address: this.hideWalletAddress,
match_direction: '+',
network: document.web3network,
num_periods: 1,
real_period_seconds: 0,
recurring_or_not: 'once',
signature: 'onetime',
split_tx_id: txHash, // this txhash is our bulk donation hash
splitter_contract_address: contractAddress,
subscription_hash: 'onetime',
// Values that vary by donation
'gitcoin-grant-input-amount': [],
admin_address: [],