-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathtestHelpers.js
1436 lines (1273 loc) · 45.5 KB
/
testHelpers.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
const { web3 } = require("./web3");
const constants = require("./constants");
const assert = require("assert");
const util = require("ethereumjs-util");
const MockCodeCheckArtifact = require("../../build/contracts/MockCodeCheck.json");
const AdharmaSmartWalletImplementationArtifact = require("../../build/contracts/AdharmaSmartWalletImplementation.json");
const AdharmaKeyRingImplementationArtifact = require("../../build/contracts/AdharmaKeyRingImplementation.json");
const DharmaUpgradeBeaconControllerManagerArtifact = require("../../build/contracts/DharmaUpgradeBeaconControllerManager.json");
const DharmaUpgradeBeaconControllerArtifact = require("../../build/contracts/DharmaUpgradeBeaconController.json");
const DharmaUpgradeBeaconArtifact = require("../../build/contracts/DharmaUpgradeBeacon.json");
const DharmaKeyRingUpgradeBeaconArtifact = require("../../build/contracts/DharmaKeyRingUpgradeBeacon.json");
const DharmaUpgradeBeaconEnvoyArtifact = require("../../build/contracts/DharmaUpgradeBeaconEnvoy.json");
const DharmaAccountRecoveryManagerV2Artifact = require("../../build/contracts/DharmaAccountRecoveryManagerV2.json");
const DharmaKeyRegistryV2Artifact = require("../../build/contracts/DharmaKeyRegistryV2.json");
const DharmaSmartWalletFactoryV1Artifact = require("../../build/contracts/DharmaSmartWalletFactoryV1.json");
const DharmaSmartWalletFactoryV2Artifact = require("../../build/contracts/DharmaSmartWalletFactoryV2.json");
const DharmaSmartWalletImplementationV6Artifact = require("../../build/contracts/DharmaSmartWalletImplementationV6.json");
const DharmaSmartWalletImplementationV7Artifact = require("../../build/contracts/DharmaSmartWalletImplementationV7.json");
const DharmaKeyRingImplementationV1Artifact = require("../../build/contracts/DharmaKeyRingImplementationV1.json");
const DharmaKeyRingFactoryV1Artifact = require("../../build/contracts/DharmaKeyRingFactoryV1.json");
const DharmaKeyRingFactoryV2Artifact = require("../../build/contracts/DharmaKeyRingFactoryV2.json");
const DharmaKeyRingFactoryV3Artifact = require("../../build/contracts/DharmaKeyRingFactoryV3.json");
const UpgradeBeaconProxyV1Artifact = require("../../build/contracts/UpgradeBeaconProxyV1.json");
const KeyRingUpgradeBeaconProxyV1Artifact = require("../../build/contracts/KeyRingUpgradeBeaconProxyV1.json");
const DharmaUpgradeMultisigArtifact = require("../../build/contracts/DharmaUpgradeMultisig.json");
const DharmaAccountRecoveryMultisigArtifact = require("../../build/contracts/DharmaAccountRecoveryMultisig.json");
const DharmaAccountRecoveryOperatorMultisigArtifact = require("../../build/contracts/DharmaAccountRecoveryOperatorMultisig.json");
const DharmaKeyRegistryMultisigArtifact = require("../../build/contracts/DharmaKeyRegistryMultisig.json");
const DharmaEscapeHatchRegistryArtifact = require("../../build/contracts/DharmaEscapeHatchRegistry.json");
const UpgradeBeaconImplementationCheckArtifact = require("../../build/contracts/UpgradeBeaconImplementationCheck.json");
const BadBeaconArtifact = require("../../build/contracts/BadBeacon.json");
const BadBeaconTwoArtifact = require("../../build/contracts/BadBeaconTwo.json");
const TimelockEdgecaseTesterArtifact = require("../../build/contracts/TimelockEdgecaseTester.json");
const MockDharmaKeyRingFactoryArtifact = require("../../build/contracts/MockDharmaKeyRingFactory.json");
const IERC20Artifact = require("../../build/contracts/IERC20.json");
const CTokenInterfaceArtifact = require("../../build/contracts/CTokenInterface.json");
const BalanceCheckerArtifact = require("../../build/contracts/BalanceChecker.json");
class Tester {
constructor(testingContext) {
this.context = testingContext;
this.failed = 0;
this.passed = 0;
const UpgradeBeaconImplementationCheckDeployer = new web3.eth.Contract(
UpgradeBeaconImplementationCheckArtifact.abi
);
UpgradeBeaconImplementationCheckDeployer.options.data =
UpgradeBeaconImplementationCheckArtifact.bytecode;
this.UpgradeBeaconImplementationCheckDeployer = UpgradeBeaconImplementationCheckDeployer;
}
async init() {
// get available addresses and assign them to various roles
const addresses = await web3.eth.getAccounts();
if (addresses.length < 1) {
console.log("cannot find enough addresses to run tests!");
process.exit(1);
}
let latestBlock = await web3.eth.getBlock("latest");
this.originalAddress = addresses[0];
this.address = await this.setupNewDefaultAddress(
"0xfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeedfeed"
);
this.addressTwo = await this.setupNewDefaultAddress(
"0xf00df00df00df00df00df00df00df00df00df00df00df00df00df00df00df00d"
);
this.ownerOne = await this.setupNewDefaultAddress(
constants.MOCK_OWNER_PRIVATE_KEYS[0]
);
this.ownerTwo = await this.setupNewDefaultAddress(
constants.MOCK_OWNER_PRIVATE_KEYS[1]
);
this.ownerThree = await this.setupNewDefaultAddress(
constants.MOCK_OWNER_PRIVATE_KEYS[2]
);
this.ownerFour = await this.setupNewDefaultAddress(
constants.MOCK_OWNER_PRIVATE_KEYS[3]
);
this.ownerFive = await this.setupNewDefaultAddress(
constants.MOCK_OWNER_PRIVATE_KEYS[4]
);
this.gasLimit = latestBlock.gasLimit;
const BalanceCheckerDeployer = new web3.eth.Contract(
BalanceCheckerArtifact.abi
);
BalanceCheckerDeployer.options.data = BalanceCheckerArtifact.bytecode;
this.BalanceChecker = await this.runTest(
`BalanceChecker contract deployment`,
BalanceCheckerDeployer,
"",
"deploy"
);
const MockCodeCheckDeployer = new web3.eth.Contract(
MockCodeCheckArtifact.abi
);
MockCodeCheckDeployer.options.data = MockCodeCheckArtifact.bytecode;
this.MockCodeCheck = await this.runTest(
`MockCodeCheck contract deployment`,
MockCodeCheckDeployer,
"",
"deploy"
);
await this.runTest(
"Deployed MockCodeCheck code is correct",
this.MockCodeCheck,
"code",
"call",
[this.MockCodeCheck.options.address],
true,
value => {
assert.strictEqual(
value,
MockCodeCheckArtifact.deployedBytecode
);
}
);
await this.runTest(
"Deployed MockCodeCheck has correct extcodehash",
this.MockCodeCheck,
"hash",
"call",
[this.MockCodeCheck.options.address],
true,
value => {
assert.strictEqual(
value,
web3.utils.keccak256(
MockCodeCheckArtifact.deployedBytecode,
{ encoding: "hex" }
)
);
}
);
await this.setupDeployedContracts();
}
async setupNewDefaultAddress(newPrivateKey) {
const pubKey = await web3.eth.accounts.privateKeyToAccount(
newPrivateKey
);
await web3.eth.accounts.wallet.add(pubKey);
await web3.eth.sendTransaction({
from: this.originalAddress,
to: pubKey.address,
value: 2 * 10 ** 18,
gas: "0x5208",
gasPrice: "0x4A817C800"
});
return pubKey.address;
}
async raiseGasLimit(necessaryGas) {
let iterations = 9999;
if (necessaryGas > 8000000) {
console.error("the gas needed is too high!");
process.exit(1);
} else if (typeof necessaryGas === "undefined") {
iterations = 20;
necessaryGas = 8000000;
}
// bring up gas limit if necessary by doing additional transactions
let block = await web3.eth.getBlock("latest");
while (iterations > 0 && block.gasLimit < necessaryGas) {
await web3.eth.sendTransaction({
from: this.originalAddress,
to: this.originalAddress,
value: "0x01",
gas: "0x5208",
gasPrice: "0x4A817C800"
});
block = await web3.eth.getBlock("latest");
iterations--;
}
console.log("raising gasLimit, currently at " + block.gasLimit);
return block.gasLimit;
}
async getDeployGas(dataPayload) {
await web3.eth
.estimateGas({
from: address,
data: dataPayload
})
.catch(async error => {
if (
error.message ===
"Returned error: gas required exceeds allowance or always failing " +
"transaction"
) {
await this.raiseGasLimit();
await this.getDeployGas(dataPayload);
}
});
return web3.eth.estimateGas({
from: address,
data: dataPayload
});
}
async advanceTime(time) {
return new Promise((resolve, reject) => {
web3.currentProvider.send(
{
jsonrpc: "2.0",
method: "evm_increaseTime",
params: [time],
id: new Date().getTime()
},
(err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
}
);
});
}
async takeSnapshot() {
return new Promise((resolve, reject) => {
web3.currentProvider.send(
{
jsonrpc: "2.0",
method: "evm_snapshot",
id: new Date().getTime()
},
(err, snapshotId) => {
if (err) {
return reject(err);
}
return resolve(snapshotId);
}
);
});
}
async revertToSnapShot(id) {
return new Promise((resolve, reject) => {
web3.currentProvider.send(
{
jsonrpc: "2.0",
method: "evm_revert",
params: [id],
id: new Date().getTime()
},
(err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
}
);
});
}
async advanceBlock() {
return new Promise((resolve, reject) => {
web3.currentProvider.send(
{
jsonrpc: "2.0",
method: "evm_mine",
id: new Date().getTime()
},
(err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
}
);
});
}
async rpc(request) {
return new Promise((okay, fail) =>
web3.currentProvider.send(request, (err, res) =>
err ? fail(err) : okay(res)
)
);
}
async getLatestBlockNumber() {
let { result: num } = await this.rpc({
method: "eth_blockNumber",
id: new Date().getTime() // for snapshotting
});
return num;
}
async advanceBlocks(blocksToAdvance, nonce) {
if (blocksToAdvance < 1) {
throw new Error("must advance at least one block.");
}
let currentBlockNumberHex = await this.getLatestBlockNumber();
const accountNonce =
typeof nonce === "undefined"
? await web3.eth.getTransactionCount(this.address)
: nonce;
const extraBlocks = blocksToAdvance - 1;
const extraBlocksHex =
"0x" + (extraBlocks + parseInt(currentBlockNumberHex)).toString(16);
const nextBlockNumber = blocksToAdvance + 1;
const nextBlockNumberHex =
"0x" +
(nextBlockNumber + parseInt(currentBlockNumberHex)).toString(16);
await this.rpc({
method: "evm_mineBlockNumber",
params: [extraBlocksHex],
id: new Date().getTime()
});
const newBlockNumberHex =
"0x" +
(blocksToAdvance + parseInt(currentBlockNumberHex)).toString(16);
currentBlockNumberHex = await this.getLatestBlockNumber();
if (currentBlockNumberHex !== newBlockNumberHex) {
console.error(
`current block is now ${parseInt(
currentBlockNumberHex
)} - evm_mineBlockNumber failed... (expected ${parseInt(
newBlockNumberHex
)})`
);
process.exit(1);
}
const dummyTxReceipt = await web3.eth.sendTransaction({
from: this.address,
to: this.address,
data: "0x",
value: 0,
gas: 21000,
gasPrice: 1,
nonce: accountNonce
});
return await web3.eth.getBlock(dummyTxReceipt.blockHash);
}
async advanceTimeAndBlock(time) {
await this.advanceTime(time);
await this.advanceBlock();
return Promise.resolve(web3.eth.getBlock("latest"));
}
async advanceTimeAndBlocks(blocks, nonce) {
if (blocks < 2) {
return reject("must advance by at least two blocks.");
}
//let block = await web3.eth.getBlock(await this.getLatestBlockNumber())
await this.advanceTime(blocks * 15);
//block = await web3.eth.getBlock(await this.getLatestBlockNumber())
// next block must be extracted from this function ('getBlock' breaks)
return await this.advanceBlocks(blocks - 1, nonce);
}
signHashedPrefixedHexString(hashedHexString, account) {
const sig = util.ecsign(
util.toBuffer(
web3.utils.keccak256(
// prefix => "\x19Ethereum Signed Message:\n32"
"0x19457468657265756d205369676e6564204d6573736167653a0a3332" +
hashedHexString.slice(2),
{ encoding: "hex" }
)
),
util.toBuffer(web3.eth.accounts.wallet[account].privateKey)
);
return (
util.bufferToHex(sig.r) +
util.bufferToHex(sig.s).slice(2) +
web3.utils.toHex(sig.v).slice(2)
);
}
signHashedPrefixedHashedHexString(hexString, account) {
const sig = util.ecsign(
util.toBuffer(
web3.utils.keccak256(
// prefix => "\x19Ethereum Signed Message:\n32"
"0x19457468657265756d205369676e6564204d6573736167653a0a3332" +
web3.utils
.keccak256(hexString, { encoding: "hex" })
.slice(2),
{ encoding: "hex" }
)
),
util.toBuffer(web3.eth.accounts.wallet[account].privateKey)
);
return (
util.bufferToHex(sig.r) +
util.bufferToHex(sig.s).slice(2) +
web3.utils.toHex(sig.v).slice(2)
);
}
async sendTransaction(
instance,
method,
args,
from,
value,
gas,
gasPrice,
transactionShouldSucceed,
nonce
) {
return instance.methods[method](...args)
.send({
from: from,
value: value,
gas: gas,
gasPrice: gasPrice,
nonce: nonce
})
.on("confirmation", (confirmationNumber, r) => {
confirmations[r.transactionHash] = confirmationNumber;
})
.catch(error => {
if (transactionShouldSucceed) {
console.error(error);
}
return { status: false };
});
}
async callMethod(
instance,
method,
args,
from,
value,
gas,
gasPrice,
callShouldSucceed
) {
let callSucceeded = true;
const returnValues = await instance.methods[method](...args)
.call({
from: from,
value: value,
gas: gas,
gasPrice: gasPrice
})
.catch(error => {
if (callShouldSucceed) {
console.error(error);
}
callSucceeded = false;
});
return { callSucceeded, returnValues };
}
async send(
title,
instance,
method,
args,
from,
value,
gas,
gasPrice,
transactionShouldSucceed,
assertionCallback,
nonce
) {
const receipt = await this.sendTransaction(
instance,
method,
args,
from,
value,
gas,
gasPrice,
transactionShouldSucceed,
nonce
);
const transactionSucceeded = receipt.status;
if (transactionSucceeded) {
try {
assertionCallback(receipt);
} catch (error) {
console.log(error);
return false; // return false if assertions fail and throw an error
}
}
//return true if transaction success matches expectations, false if expectations are mismatched
return transactionSucceeded === transactionShouldSucceed;
}
async call(
title,
instance,
method,
args,
from,
value,
gas,
gasPrice,
callShouldSucceed,
assertionCallback
) {
const { callSucceeded, returnValues } = await this.callMethod(
instance,
method,
args,
from,
value,
gas,
gasPrice,
callShouldSucceed
);
// if call succeeds, try assertion callback
if (callSucceeded) {
try {
assertionCallback(returnValues);
} catch (error) {
console.log(error);
return false;
}
}
return callSucceeded === callShouldSucceed;
}
async deploy(
title,
instance,
args,
from,
value,
gas,
gasPrice,
shouldSucceed,
assertionCallback
) {
let deployData = instance.deploy({ arguments: args }).encodeABI();
let deployGas = await web3.eth
.estimateGas({
from: from,
data: deployData
})
.catch(error => {
if (shouldSucceed) {
console.error(error);
}
return this.gasLimit;
});
if (deployGas > this.gasLimit) {
console.error(
` ✘ ${title}: deployment costs exceed block gas limit!`
);
process.exit(1);
}
if (typeof gas === "undefined") {
gas = deployGas;
}
if (deployGas > gas) {
console.error(` ✘ ${title}: deployment costs exceed supplied gas.`);
process.exit(1);
}
let signed;
let deployHash;
let receipt;
const contract = await instance
.deploy({ arguments: args })
.send({
from: from,
gas: gas,
gasPrice: gasPrice
})
.on("transactionHash", hash => {
deployHash = hash;
})
.on("receipt", r => {
receipt = r;
})
.on("confirmation", (confirmationNumber, r) => {
confirmations[r.transactionHash] = confirmationNumber;
})
.catch(error => {
if (shouldSucceed) {
console.error(error);
}
receipt = { status: false };
});
if (receipt.status !== shouldSucceed) {
if (contract) {
return [false, contract, gas];
}
return [false, instance, gas];
} else if (!shouldSucceed) {
if (contract) {
return [true, contract, gas];
}
return [true, instance, gas];
}
assert.ok(receipt.status);
let assertionsPassed;
try {
assertionCallback(receipt);
assertionsPassed = true;
} catch (error) {
assertionsPassed = false;
}
if (contract) {
return [assertionsPassed, contract, gas];
}
return [assertionsPassed, instance, gas];
}
/* aggregates the first 3 functions
* run test without coverage, once they're passing then run with coverage
* coverage changes the gas -- orders of magnitued more expensive
* any test that are gas dependent get grilled under coverage test
*
*
* default: send
*/
async runTest(
title,
instance,
method,
callOrSendOrDeploy,
args,
shouldSucceed,
assertionCallback,
from,
value,
gas,
nonce
) {
if (typeof callOrSendOrDeploy === "undefined") {
callOrSendOrDeploy = "send";
}
if (typeof args === "undefined") {
args = [];
}
if (typeof shouldSucceed === "undefined") {
shouldSucceed = true;
}
if (typeof assertionCallback === "undefined") {
assertionCallback = value => {};
}
if (typeof from === "undefined") {
from = this.address;
}
if (typeof value === "undefined") {
value = 0;
}
if (typeof gas === "undefined" && callOrSendOrDeploy !== "deploy") {
gas = 6009006;
if (this.context === "coverage") {
gas = this.gasLimit - 1;
}
}
let ok = false;
let contract;
let deployGas;
if (callOrSendOrDeploy === "send") {
ok = await this.send(
title,
instance,
method,
args,
from,
value,
gas,
1,
shouldSucceed,
assertionCallback,
nonce
);
} else if (callOrSendOrDeploy === "call") {
ok = await this.call(
title,
instance,
method,
args,
from,
value,
gas,
1,
shouldSucceed,
assertionCallback
);
} else if (callOrSendOrDeploy === "deploy") {
const fields = await this.deploy(
title,
instance,
args,
from,
value,
gas,
1,
shouldSucceed,
assertionCallback
);
ok = fields[0];
contract = fields[1];
deployGas = fields[2];
} else {
console.error("must use call, send, or deploy!");
process.exit(1);
}
if (ok) {
console.log(
` ✓ ${
callOrSendOrDeploy === "deploy" ? "successful " : ""
}${title}${
callOrSendOrDeploy === "deploy" ? ` (${deployGas} gas)` : ""
}`
);
this.passed++;
} else {
console.log(
` ✘ ${
callOrSendOrDeploy === "deploy" ? "failed " : ""
}${title}${
callOrSendOrDeploy === "deploy" ? ` (${deployGas} gas)` : ""
}`
);
this.failed++;
}
if (contract) {
return contract;
}
}
async withBalanceCheck(account, initial, final, test, testArgs) {
// Get the initial balances.
const initialBalances = await this.getBalances(account);
const initialBalancesSet = new Set(Object.keys(initialBalances));
const initialSet = new Set(Object.keys(initial));
const finalSet = new Set(Object.keys(final));
// Initial and final sets must both have the same balance checks.
assert.strictEqual(initialSet.size, finalSet.size);
assert.strictEqual(
initialSet.size,
new Set([...initialSet, ...finalSet]).size
);
// Ensure that all the specified balance checks are actually returned.
assert.strictEqual(
new Set([...initialSet].filter(x => !initialBalancesSet.has(x)))
.size,
0
);
// Get specified keys from balance check and compare to expected values.
const balanceChecks = [
...new Set([...initialSet].filter(x => initialBalancesSet.has(x)))
];
for (const balance of balanceChecks) {
assert.strictEqual(initialBalances[balance], initial[balance]);
}
// Run the test.
await test.bind(this)(...testArgs);
// Get the final balances.
const finalBalances = await this.getBalances(account);
for (const balance of balanceChecks) {
assert.strictEqual(finalBalances[balance], final[balance]);
}
}
async getBalances(account) {
const balances = await this.BalanceChecker.methods
.getBalances(account)
.call()
.catch(error => {
console.error(error);
process.exit(1);
});
const underlyingBalances = await this.BalanceChecker.methods
.getUnderlyingBalances(account)
.call()
.catch(error => {
console.error(error);
process.exit(1);
});
return {
account,
dDai:
parseFloat(web3.utils.fromWei(balances.dDaiBalance, "gwei")) *
10,
dUSDC:
parseFloat(web3.utils.fromWei(balances.dUSDCBalance, "gwei")) *
10,
dai: parseFloat(web3.utils.fromWei(balances.daiBalance, "ether")),
usdc: parseFloat(web3.utils.fromWei(balances.usdcBalance, "mwei")),
sai: parseFloat(web3.utils.fromWei(balances.saiBalance, "ether")),
cSai:
parseFloat(web3.utils.fromWei(balances.cSaiBalance, "gwei")) *
10,
cDai:
parseFloat(web3.utils.fromWei(balances.cDaiBalance, "gwei")) *
10,
cUSDC:
parseFloat(web3.utils.fromWei(balances.cUSDCBalance, "gwei")) *
10,
ether: parseFloat(
web3.utils.fromWei(balances.etherBalance, "ether")
),
dDaiUnderlying: parseFloat(
web3.utils.fromWei(
underlyingBalances.dDaiBalanceUnderlying,
"ether"
)
),
dUSDCUnderlying: parseFloat(
web3.utils.fromWei(
underlyingBalances.dUSDCBalanceUnderlying,
"mwei"
)
),
cSaiUnderlying: parseFloat(
web3.utils.fromWei(
underlyingBalances.cSaiBalanceUnderlying,
"ether"
)
),
cDaiUnderlying: parseFloat(
web3.utils.fromWei(
underlyingBalances.cDaiBalanceUnderlying,
"ether"
)
),
cUSDCUnderlying: parseFloat(
web3.utils.fromWei(
underlyingBalances.cUSDCBalanceUnderlying,
"mwei"
)
),
dDaiRaw: balances.dDaiBalance,
dUSDCRaw: balances.dUSDCBalance,
daiRaw: balances.daiBalance,
usdcRaw: balances.usdcBalance,
saiRaw: balances.saiBalance,
cSaiRaw: balances.cSaiBalance,
cDaiRaw: balances.cDaiBalance,
cUSDCRaw: balances.cUSDCBalance,
etherRaw: balances.etherBalance,
dDaiUnderlyingRaw: underlyingBalances.dDaiBalanceUnderlying,
dUSDCUnderlyingRaw: underlyingBalances.dUSDCBalanceUnderlying,
cSaiUnderlyingRaw: underlyingBalances.cSaiBalanceUnderlying,
cDaiUnderlyingRaw: underlyingBalances.cDaiBalanceUnderlying,
cUSDCUnderlyingRaw: underlyingBalances.cUSDCBalanceUnderlying
};
}
getEvents(receipt, contractNames) {
const { events } = receipt;
// web3 "helpfully" collects multiple events into arrays... flatten them :)
let flattenedEvents = {};
for (const e of Object.values(events)) {
if (Array.isArray(e)) {
for (const n of e) {
flattenedEvents[n.logIndex] = n;
}
} else {
flattenedEvents[e.logIndex] = e;
}
}
return Object.values(flattenedEvents)
.map(value => {
// Handle MKR events independently (Pot and Vat called by cDai)
if (value.raw.topics.length === 4) {
const callerAddress = web3.utils.toChecksumAddress(
"0x" + value.raw.topics[1].slice(26)
);
return {
address: contractNames[value.address],
eventName: null,
returnValues: {
selector: value.raw.topics[0].slice(0, 10),
caller:
callerAddress in contractNames
? contractNames[callerAddress]
: callerAddress,
arg1: value.raw.topics[2],
arg2: value.raw.topics[3]
}
};
}
const topic = value.raw.topics[0];
const log = constants.EVENT_DETAILS[topic];
return {
address: contractNames[value.address],
eventName: log.name,
returnValues: web3.eth.abi.decodeLog(
log.abi,
value.raw.data,
value.raw.topics.slice(1)
)
};
})
.filter(value => value !== null);
}
async checkAndDeploy(
name,
address,
salt,
runtimeCode,
creationCode,
mockCodeCheck,
create2Factory
) {
let currentCode;
await this.runTest(
`Checking ${name} runtime code`,
mockCodeCheck,
"code",
"call",
[address],
true,
value => {
currentCode = value;
}
);
if (currentCode !== runtimeCode) {
await this.runTest(
`${name} contract address check through immutable create2 factory`,
create2Factory,
"findCreate2Address",
"call",
[salt, creationCode],
true,
value => {
assert.strictEqual(value, address);
}