-
Notifications
You must be signed in to change notification settings - Fork 879
Expand file tree
/
Copy pathEVMCompatabilityTest.js
More file actions
1460 lines (1227 loc) · 56 KB
/
EVMCompatabilityTest.js
File metadata and controls
1460 lines (1227 loc) · 56 KB
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 { expect } = require("chai");
const {isBigNumber} = require("hardhat/common");
const {uniq, shuffle} = require("lodash");
const { ethers, upgrades } = require('hardhat');
const { getImplementationAddress } = require('@openzeppelin/upgrades-core');
const { deployEvmContract, setupSigners, fundAddress, getCosmosTx, getEvmTx, waitForBaseFeeToEq, waitForBaseFeeToBeGt} = require("./lib")
const axios = require("axios");
const { default: BigNumber } = require("bignumber.js");
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delay() {
// await sleep(3000)
}
function debug(msg) {
// leaving commented out to make output readable (unless debugging)
// console.log(msg)
}
async function sendTransactionAndCheckGas(sender, recipient, amount) {
// Get the balance of the sender before the transaction
const balanceBefore = await ethers.provider.getBalance(sender.address);
// Send the transaction
const tx = await sender.sendTransaction({
to: recipient.address,
value: amount
});
// Wait for the transaction to be mined and get the receipt
const receipt = await tx.wait();
// Get the balance of the sender after the transaction
const balanceAfter = await ethers.provider.getBalance(sender.address);
// Calculate the total cost of the transaction (amount + gas fees)
const gasPrice = receipt.gasPrice;
const gasUsed = receipt.gasUsed;
const totalCost = gasPrice * gasUsed + BigInt(amount);
// Check that the sender's balance decreased by the total cost
return balanceBefore - balanceAfter === totalCost
}
function generateWallet() {
const wallet = ethers.Wallet.createRandom();
return wallet.connect(ethers.provider);
}
function generateWallets(num) {
const arr = []
for(let i=0; i<num; i++) {
const wallet = ethers.Wallet.createRandom();
arr.push(wallet);
}
return arr;
}
async function sendTx(sender, txn, responses) {
const txResponse = await sender.sendTransaction(txn);
responses.push({nonce: txn.nonce, response: txResponse})
}
describe("EVM Test", function () {
describe("EVMCompatibilityTester", function () {
let evmTester;
let testToken;
let owner;
let evmAddr;
let firstNonce;
// The first contract address deployed from 0xF87A299e6bC7bEba58dbBe5a5Aa21d49bCD16D52
// should always be 0xbD5d765B226CaEA8507EE030565618dAFFD806e2 when sent with nonce=0
const firstContractAddress = "0xbD5d765B226CaEA8507EE030565618dAFFD806e2";
// This function deploys a new instance of the contract before each test
beforeEach(async function () {
if(evmTester && testToken) {
return
}
const accounts = await setupSigners(await ethers.getSigners())
owner = accounts[0].signer;
debug(`OWNER = ${owner.address}`)
firstNonce = await ethers.provider.getTransactionCount(owner.address)
const TestToken = await ethers.getContractFactory("TestToken")
testToken = await TestToken.deploy("TestToken", "TTK");
const EVMCompatibilityTester = await ethers.getContractFactory("EVMCompatibilityTester");
evmTester = await EVMCompatibilityTester.deploy({ gasPrice: ethers.parseUnits('100', 'gwei') });
await Promise.all([evmTester.waitForDeployment(), testToken.waitForDeployment()])
let tokenAddr = await testToken.getAddress()
evmAddr = await evmTester.getAddress()
debug(`Token: ${tokenAddr}, EvmAddr: ${evmAddr}`);
});
describe("Deployment", function () {
it("Should deploy successfully", async function () {
expect(await evmTester.getAddress()).to.be.properAddress;
expect(await testToken.getAddress()).to.be.properAddress;
expect(await evmTester.getAddress()).to.not.equal(await testToken.getAddress());
});
it("Should have correct address", async function () {
if(firstNonce > 0) {
this.skip()
} else {
expect(await testToken.getAddress()).to.equal(firstContractAddress);
}
});
it("Should estimate gas for a contract deployment", async function () {
const callData = evmTester.interface.encodeFunctionData("createToken", ["TestToken", "TTK"]);
const estimatedGas = await ethers.provider.estimateGas({
to: await evmTester.getAddress(),
data: callData
});
expect(estimatedGas).to.greaterThan(0);
});
});
describe("Contract Factory", function() {
it("should deploy a second contract from createToken", async function () {
const txResponse = await evmTester.createToken("TestToken", "TTK", { gasPrice: ethers.parseUnits('100', 'gwei') });
const testerAddress = await evmTester.getAddress();
const receipt = await txResponse.wait();
const newTokenAddress = receipt.logs[0].address;
expect(newTokenAddress).to.not.equal(testerAddress);
const TestToken = await ethers.getContractFactory("TestToken")
const tokenInstance = await TestToken.attach(newTokenAddress);
const bal = await tokenInstance.balanceOf(await owner.getAddress());
expect(bal).to.equal(100);
});
})
describe("Call Another Contract", function(){
it("should set balance and then retrieve it via callAnotherContract", async function () {
const setAmount = ethers.parseUnits("1000", 18);
await delay()
// Set balance
await testToken.setBalance(owner.address, setAmount, { gasPrice: ethers.parseUnits('100', 'gwei') });
// Prepare call data for balanceOf function of MyToken
const balanceOfData = testToken.interface.encodeFunctionData("balanceOf", [owner.address]);
const tokenAddress = await testToken.getAddress()
await delay()
// Call balanceOf using callAnotherContract from EVMCompatibilityTester
await evmTester.callAnotherContract(tokenAddress, balanceOfData);
await delay()
// Verify the balance using MyToken contract directly
const balance = await testToken.balanceOf(owner.address);
expect(balance).to.equal(setAmount);
});
})
describe("Msg Properties", function() {
it("Should store and retrieve msg properties correctly", async function() {
// Store msg properties
const txResponse = await evmTester.storeMsgProperties({ value: 1, gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait();
// Retrieve stored msg properties
const msgDetails = await evmTester.lastMsgDetails();
debug(msgDetails)
// Assertions
expect(msgDetails.sender).to.equal(owner.address);
expect(msgDetails.value).to.equal(1);
// `data` is the encoded function call, which is difficult to predict and assert
// `gas` is the remaining gas after the transaction, which is also difficult to predict and assert
});
});
describe("Block Properties", function () {
it("Should have consistent block properties for a block", async function () {
const currentBlockNumber = await ethers.provider.getBlockNumber();
const iface = new ethers.Interface(["function getBlockProperties() view returns (bytes32 blockHash, address coinbase, uint256 prevrandao, uint256 gaslimit, uint256 number, uint256 timestamp)"]);
const addr = await evmTester.getAddress()
const tx = {
to: addr,
data: iface.encodeFunctionData("getBlockProperties", []),
blockTag: currentBlockNumber-2
};
const result = await ethers.provider.call(tx);
// wait for block to change
while(true){
const bn = await ethers.provider.getBlockNumber();
if(bn !== currentBlockNumber){
break
}
await sleep(100)
}
const result2 = await ethers.provider.call(tx);
expect(result).to.equal(result2)
});
it("Should return correct gas limit via GASLIMIT opcode", async function () {
// First call setGasLimit() to capture the gas limit during transaction execution
const setGasLimitTx = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
await setGasLimitTx.wait();
// Now read the captured gas limit
const contractGasLimit = await evmTester.getGasLimit();
// Get the current block and its gas limit
const currentBlock = await ethers.provider.getBlock("latest");
const blockGasLimit = currentBlock.gasLimit;
// The gas limit returned by the contract should match the block's gas limit
expect(contractGasLimit).to.equal(blockGasLimit);
// Gas limit should be a reasonable value (greater than 0)
expect(contractGasLimit).to.be.greaterThan(0);
debug(`Contract gas limit: ${contractGasLimit}`);
debug(`Block gas limit: ${blockGasLimit}`);
});
it("Should return consistent gas limit across multiple calls", async function () {
// Set gas limit multiple times and verify consistency
const setTx1 = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
await setTx1.wait();
const gasLimit1 = await evmTester.getGasLimit();
const setTx2 = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
await setTx2.wait();
const gasLimit2 = await evmTester.getGasLimit();
const setTx3 = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
await setTx3.wait();
const gasLimit3 = await evmTester.getGasLimit();
// All calls should return the same gas limit
expect(gasLimit1).to.equal(gasLimit2);
expect(gasLimit2).to.equal(gasLimit3);
});
it("Should access gas limit directly via inline assembly", async function () {
// First capture the gas limit using setGasLimit() in a transaction context
const setGasLimitTx = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
await setGasLimitTx.wait();
// Read the captured gas limit
const gasLimitFromAssembly = await evmTester.getGasLimit();
// Also get it from getBlockProperties for comparison
const blockProperties = await evmTester.getBlockProperties();
const gasLimitFromBlockProperties = blockProperties.gaslimit;
// Both methods should return the same value
expect(gasLimitFromAssembly).to.equal(gasLimitFromBlockProperties);
// Get the current block and verify against its gas limit
const currentBlock = await ethers.provider.getBlock("latest");
const blockGasLimit = currentBlock.gasLimit;
expect(gasLimitFromAssembly).to.equal(blockGasLimit);
// Verify it's a valid gas limit value
expect(gasLimitFromAssembly).to.be.greaterThan(0);
// Gas limit should be within reasonable bounds (not too small, not too large)
expect(gasLimitFromAssembly).to.be.greaterThan(21000); // Minimum for a simple transaction
expect(gasLimitFromAssembly).to.be.lessThan(100_000_000); // 100M gas seems reasonable as upper bound
debug(`Gas limit from assembly: ${gasLimitFromAssembly}`);
});
it("Should access gas limit correctly within a state-changing transaction", async function () {
// Call setGasLimit() to capture the gas limit during transaction execution
const setGasLimitTx = await evmTester.setGasLimit({ gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await setGasLimitTx.wait();
// Get the gas limit from the contract after the transaction
const gasLimitFromContract = await evmTester.getGasLimit();
// Get the block that contains our transaction
const transactionBlock = await ethers.provider.getBlock(receipt.blockNumber);
const blockGasLimit = transactionBlock.gasLimit;
// The gas limit should match the block's gas limit
expect(gasLimitFromContract).to.equal(blockGasLimit);
// Verify the transaction was successful and gas limit is reasonable
expect(receipt.status).to.equal(1);
expect(gasLimitFromContract).to.be.greaterThan(receipt.gasUsed);
debug(`Transaction gas used: ${receipt.gasUsed}`);
debug(`Block gas limit: ${gasLimitFromContract}`);
});
});
describe("Variable Types", function () {
it("Should set the address correctly and emit an event", async function () {
// Call setAddress
await delay()
const txResponse = await evmTester.setAddressVar({ gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait(); // Wait for the transaction to be mined
await expect(txResponse)
.to.emit(evmTester, 'AddressSet')
.withArgs(owner.address);
});
it("Should set the bool correctly and emit an event", async function () {
// Call setBoolVar
await delay()
const txResponse = await evmTester.setBoolVar(true, { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait(); // Wait for the transaction to be mined
debug(JSON.stringify(txResponse))
await expect(txResponse)
.to.emit(evmTester, 'BoolSet')
.withArgs(owner.address, true);
// Verify that addr is set correctly
expect(await evmTester.boolVar()).to.equal(true);
});
it("Should set the uint256 correctly and emit an event", async function () {
// Call setBoolVar
await delay()
const txResponse = await evmTester.setUint256Var(12345, { gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await txResponse.wait(); // Wait for the transaction to be mined
debug(JSON.stringify(txResponse))
await expect(txResponse)
.to.emit(evmTester, 'Uint256Set')
.withArgs(owner.address, 12345);
// Verify that addr is set correctly
expect(await evmTester.uint256Var()).to.equal(12345);
// Calculate total gas cost
const totalGasCost = receipt.gasUsed * receipt.gasPrice;
console.log("totalGasCost", totalGasCost);
console.log("receipt", receipt);
debug(`Total gas cost: ${ethers.formatEther(totalGasCost)} ETH`);
});
// this uses a newer version of ethers to attempt a blob transaction (different signer wallet)
it("should return an error for blobs", async function(){
const key = "0x57acb95d82739866a5c29e40b0aa2590742ae50425b7dd5b5d279a986370189e"
const signer = new ethers.Wallet(key, ethers.provider);
const blobData = "BLOB";
const blobDataBytes = ethers.toUtf8Bytes(blobData);
const blobHash = ethers.keccak256(blobDataBytes);
const tx = {
type: 3,
to: owner.address,
value: ethers.parseEther("0.1"),
data: '0x',
maxFeePerGas: ethers.parseUnits('100', 'gwei'),
maxPriorityFeePerGas: ethers.parseUnits('1', 'gwei'),
gasLimit: 100000,
maxFeePerBlobGas: ethers.parseUnits('10', 'gwei'),
blobVersionedHashes: [blobHash],
}
await expect(signer.sendTransaction(tx)).to.be.rejectedWith("unsupported transaction type");
})
it("trace balance diff matches up with actual balance change", async function() {
const testCases = [
{
maxPriorityFeePerGas: ethers.parseUnits('1', 'gwei'),
maxFeePerGas: ethers.parseUnits('10', 'gwei')
},
{
maxPriorityFeePerGas: ethers.parseUnits('0', 'gwei'),
maxFeePerGas: ethers.parseUnits('10', 'gwei')
},
{
maxPriorityFeePerGas: ethers.parseUnits('10', 'gwei'),
maxFeePerGas: ethers.parseUnits('10', 'gwei')
}
];
for (const testCase of testCases) {
// send a tx with a gas to elevate the base fee
const heavyTxResponse = await evmTester.useGas(9500000, {
maxPriorityFeePerGas: ethers.parseUnits('10', 'gwei'),
maxFeePerGas: ethers.parseUnits('10', 'gwei'),
type: 2
});
await heavyTxResponse.wait();
await waitForBaseFeeToBeGt(ethers.parseUnits('1', 'gwei'))
const txResponse = await owner.sendTransaction({
to: owner.address,
value: ethers.parseUnits('0', 'ether'),
maxPriorityFeePerGas: testCase.maxPriorityFeePerGas,
maxFeePerGas: testCase.maxFeePerGas,
type: 2
});
const receipt = await txResponse.wait();
const trace = await hre.network.provider.request({
method: "debug_traceTransaction",
params: [receipt.hash, {
tracer: "prestateTracer",
tracerConfig: {
diffMode: true
}
}],
});
const block_ = await ethers.provider.getBlock(receipt.blockNumber)
const baseFeePerGas = block_.baseFeePerGas
const lowerCaseAddress = owner.address.toLowerCase()
const preBalance = BigInt(trace.pre[lowerCaseAddress].balance);
const postBalance = BigInt(trace.post[lowerCaseAddress].balance);
const balanceDiffTrace = preBalance - postBalance;
const expectedGasPrice = baseFeePerGas + testCase.maxPriorityFeePerGas <= testCase.maxFeePerGas ?
baseFeePerGas + testCase.maxPriorityFeePerGas :
testCase.maxFeePerGas
const gotGasPrice = Number(receipt.gasPrice)
const preBalanceBlock = await ethers.provider.getBalance(owner.address, receipt.blockNumber - 1)
const postBalanceBlock = await ethers.provider.getBalance(owner.address, receipt.blockNumber)
const balanceDiffBlock = preBalanceBlock - postBalanceBlock;
expect(gotGasPrice).to.equal(expectedGasPrice)
expect(balanceDiffTrace).to.equal(balanceDiffBlock);
}
});
it("Simple debug_call should work", async function () {
const trace = await hre.network.provider.request({
method: "debug_traceCall",
params: [{
from: owner.address,
to: owner.address,
value: "0x1"
}, "latest"],
id: 1,
jsonrpc: "2.0"
});
expect(trace).to.not.be.null;
expect(trace.gas).to.equal(21000);
expect(trace.failed).to.be.false;
expect(trace.returnValue).to.equal('0x');
expect(trace.structLogs).to.deep.equal([]);
})
it("Should trace a call with timestamp", async function () {
await delay()
await sleep(1000) // make sure test is run in isolation
const txResponse = await evmTester.setTimestamp({ gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await txResponse.wait(); // Wait for the transaction to be mined
// get the timestamp that was saved off during setTimestamp()
const lastTimestamp = await evmTester.lastTimestamp();
// perform two trace calls with a small delay in between
const trace1 = await hre.network.provider.request({
method: "debug_traceTransaction",
params: [receipt.hash],
});
await sleep(500)
const trace2 = await hre.network.provider.request({
method: "debug_traceTransaction",
params: [receipt.hash],
});
// expect consistency in the trace calls (timestamp should be fixed to block)
expect(JSON.stringify(trace1)).to.equal(JSON.stringify(trace2))
// expect timestamp in the actual trace to match the timestamp seen at the time of invocation
let found = false
for(let log of trace1.structLogs) {
if(log.op === "SSTORE" && log.stack.length >= 3) {
const ts = log.stack[2]
expect(ts).to.equal(lastTimestamp)
found = true
break;
}
}
expect(found).to.be.true;
});
it("Should set the string correctly and emit an event", async function () {
await delay()
const txResponse = await evmTester.setStringVar("test", { gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await txResponse.wait(); // Wait for the transaction to be mined
const cosmosTx = await getCosmosTx(ethers.provider, receipt.hash)
expect(cosmosTx.length).to.be.equal(64)
const evmTx = await getEvmTx(ethers.provider, cosmosTx)
expect(evmTx).to.be.equal(receipt.hash)
await expect(txResponse)
.to.emit(evmTester, 'StringSet')
.withArgs(owner.address, "test");
expect(await evmTester.stringVar()).to.equal("test");
});
it("Should set the bytes correctly and emit an event", async function () {
await delay()
const txResponse = await evmTester.setBytesVar(ethers.toUtf8Bytes("test"), { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait();
await expect(txResponse)
.to.emit(evmTester, 'BytesSet')
.withArgs(owner.address, ethers.toUtf8Bytes("test"));
const bytesVar = await evmTester.bytesVar()
expect(ethers.toUtf8String(bytesVar)).to.equal("test");
});
it("Should correctly set and retrieve balances in the mapping", async function () {
const testAmount = 1000;
await delay()
// Send the transaction and wait for it to be confirmed
const txResponse = await evmTester.setBalance(owner.address, testAmount, { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait();
await delay()
// Now check the balance
const balance = await evmTester.balances(owner.address);
expect(balance).to.equal(testAmount);
});
it("Should store and retrieve a private var correctly", async function () {
const testAmount = 12345;
await delay()
const txResponse = await evmTester.storeData(testAmount, { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait(); // Wait for the transaction to be mined
await delay()
const retrievedAmount = await evmTester.retrieveData();
expect(retrievedAmount).to.equal(BigInt(testAmount));
});
});
describe("Require Logic", function(){
it("Should revert when false is passed to revertIfFalse", async function () {
await expect(evmTester.revertIfFalse(false)).to.be.reverted;
});
it("Should not revert when true is passed to revertIfFalse", async function () {
await evmTester.revertIfFalse(true)
});
})
describe("Assembly", function(){
it("Should add numbers correctly", async function () {
expect(await evmTester.addNumbers(10, 20, { gasPrice: ethers.parseUnits('100', 'gwei') })).to.equal(30);
});
it("Should return the current balance of the contract", async function () {
const balance = await evmTester.getContractBalance();
const address = await evmTester.getAddress()
await delay()
expect(balance).to.equal(await ethers.provider.getBalance(address));
});
it("Should return correct value from readFromStorage(index)", async function () {
const testAmount = 12345;
await delay()
const txResponse = await evmTester.storeData(testAmount, { gasPrice: ethers.parseUnits('100', 'gwei') });
await delay()
await txResponse.wait(); // Wait for the transaction to be mined
const retrievedAmount = await evmTester.readFromStorage(0);
expect(retrievedAmount).to.equal(BigInt(testAmount));
});
it("Should work for BLOBBASEFEE opcode", async function () {
const blobBaseFee = await evmTester.getBlobBaseFee();
expect(blobBaseFee).to.deep.equal(BigInt(1));
});
})
describe("Historical query test", function() {
it("Should be able to get historical block data", async function() {
const feeData = await ethers.provider.getFeeData();
const gasPrice = Number(feeData.gasPrice);
const zero = ethers.parseUnits('0', 'ether')
const txResponse = await owner.sendTransaction({
to: owner.address,
gasPrice: gasPrice,
value: zero,
type: 1,
});
const receipt = await txResponse.wait();
const bn = receipt.blockNumber;
// Check historical balance
const balance1 = await ethers.provider.getBalance(owner, bn-1);
const balance2 = await ethers.provider.getBalance(owner, bn);
expect(balance1 - balance2).to.equal(21000 * Number(gasPrice))
// Check historical nonce
const nonce1 = await ethers.provider.getTransactionCount(owner, bn-1);
const nonce2 = await ethers.provider.getTransactionCount(owner, bn);
expect(nonce1 + 1).to.equal(nonce2)
});
});
describe("Gas tests", function() {
it("Should deduct correct amount of gas on transfer", async function () {
const balanceBefore = await ethers.provider.getBalance(owner);
const feeData = await ethers.provider.getFeeData();
const gasPrice = Number(feeData.gasPrice);
const zero = ethers.parseUnits('0', 'ether')
const txResponse = await owner.sendTransaction({
to: owner.address,
gasPrice: gasPrice,
value: zero,
type: 1,
});
await txResponse.wait();
const balanceAfter = await ethers.provider.getBalance(owner);
const diff = balanceBefore - balanceAfter;
expect(diff).to.equal(21000 * gasPrice);
const success = await sendTransactionAndCheckGas(owner, owner, 0)
expect(success).to.be.true
});
it("Should fail if insufficient gas is provided", async function () {
const feeData = await ethers.provider.getFeeData();
const gasPrice = Number(feeData.gasPrice);
const zero = ethers.parseUnits('0', 'ether')
expect(owner.sendTransaction({
to: owner.address,
gasPrice: gasPrice - 1,
value: zero,
type: 1,
})).to.be.reverted;
});
it("Should deduct correct amount even if higher gas price is used", async function () {
const balanceBefore = await ethers.provider.getBalance(owner);
const feeData = await ethers.provider.getFeeData();
const gasPrice = Number(feeData.gasPrice);
const higherGasPrice = Number(gasPrice + 9)
const zero = ethers.parseUnits('0', 'ether')
const txResponse = await owner.sendTransaction({
to: owner.address,
value: zero,
gasPrice: higherGasPrice,
type: 1,
});
await txResponse.wait();
const balanceAfter = await ethers.provider.getBalance(owner);
const diff = balanceBefore - balanceAfter;
expect(diff).to.be.greaterThan(21000 * gasPrice);
const success = await sendTransactionAndCheckGas(owner, owner, 0)
expect(success).to.be.true
});
describe("EIP-1559", async function() {
const zero = ethers.parseUnits('0', 'ether')
const highgp = ethers.parseUnits("400", "gwei");
const gp = ethers.parseUnits("100", "gwei");
const oneGwei = ethers.parseUnits("1", "gwei");
const testCases = [
["No truncation from max priority fee", gp, gp],
["With truncation from max priority fee", gp, highgp],
["With complete truncation from max priority fee", zero, highgp]
];
it("Check base fee on the right block", async function () {
await delay()
// check if base fee is 1gwei, otherwise wait
let iterations = 0
while (true) {
const block = await ethers.provider.getBlock("latest");
const baseFee = Number(block.baseFeePerGas);
if (baseFee === Number(oneGwei)) {
break;
}
iterations += 1
if(iterations > 10) {
throw new Error("base fee hasn't dropped to 1gwei in 10 iterations")
}
await sleep(1000);
}
// use at least 1000000 gas to increase base fee
const txResponse = await evmTester.useGas(1000000, { gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await txResponse.wait();
const blockHeight = receipt.blockNumber;
// make sure block base fee is 1gwei and the block after
// has a base fee higher than 1gwei
const block = await ethers.provider.getBlock(blockHeight);
const baseFee = Number(block.baseFeePerGas);
expect(baseFee).to.equal(oneGwei);
// wait for the next block
while (true) {
const bn = await ethers.provider.getBlockNumber();
if(bn !== blockHeight){
break
}
await sleep(500)
}
const nextBlock = await ethers.provider.getBlock(blockHeight + 1);
const nextBaseFee = Number(nextBlock.baseFeePerGas);
expect(nextBaseFee).to.be.greaterThan(oneGwei);
});
it("Should be able to send many EIP-1559 txs", async function () {
const gp = ethers.parseUnits("100", "gwei");
const zero = ethers.parseUnits('0', 'ether')
for (let i = 0; i < 10; i++) {
const txResponse = await owner.sendTransaction({
to: owner.address,
value: zero,
maxPriorityFeePerGas: gp,
maxFeePerGas: gp,
type: 2
});
await txResponse.wait();
}
});
describe("Differing maxPriorityFeePerGas and maxFeePerGas", async function() {
for (const [name, maxPriorityFeePerGas, maxFeePerGas] of testCases) {
it(`EIP-1559 test: ${name}`, async function() {
const balanceBefore = await ethers.provider.getBalance(owner);
const zero = ethers.parseUnits('0', 'ether')
const txResponse = await owner.sendTransaction({
to: owner.address,
value: zero,
maxPriorityFeePerGas: maxPriorityFeePerGas,
maxFeePerGas: maxFeePerGas,
type: 2
});
const receipt = await txResponse.wait();
// pull base fee from the block of the tx using the receipt
expect(receipt).to.not.be.null;
expect(receipt.status).to.equal(1);
const block = await ethers.provider.getBlock(receipt.blockNumber);
const baseFee = Number(block.baseFeePerGas);
const expectedEffectiveGasPrice = BigInt(baseFee) + maxPriorityFeePerGas > maxFeePerGas ? maxFeePerGas : BigInt(baseFee) + maxPriorityFeePerGas;
const balanceAfter = await ethers.provider.getBalance(owner);
const diff = balanceBefore - balanceAfter;
expect(diff).to.equal(21000 * Number(expectedEffectiveGasPrice));
});
}
});
});
});
describe("JSON-RPC", function() {
it("Should retrieve a transaction by its hash", async function () {
// Send a transaction to get its hash
const txResponse = await evmTester.setBoolVar(true);
await txResponse.wait();
// Retrieve the transaction by its hash
const tx = await ethers.provider.getTransaction(txResponse.hash);
expect(tx).to.not.be.null;
expect(tx.hash).to.equal(txResponse.hash);
});
it("Should retrieve a block by its number", async function () {
// Get the current block number
const currentBlockNumber = await ethers.provider.getBlockNumber();
// Retrieve the block by its number
const block = await ethers.provider.getBlock(currentBlockNumber);
expect(block).to.not.be.null;
expect(block.number).to.equal(currentBlockNumber);
});
it("Should retrieve the latest block", async function () {
// Retrieve the latest block
const block = await ethers.provider.getBlock("latest");
expect(block).to.not.be.null;
});
it("Should get the balance of an account", async function () {
// Get the balance of an account (e.g., the owner)
const balance = await ethers.provider.getBalance(owner.address);
// The balance should be a BigNumber; we can't predict its exact value
expect(isBigNumber(balance)).to.be.true;
});
it("Should get the code at a specific address", async function () {
// Get the code at the address of a deployed contract (e.g., evmTester)
const code = await ethers.provider.getCode(await evmTester.getAddress());
// The code should start with '0x' and be longer than just '0x' for a deployed contract
expect(code.startsWith("0x")).to.be.true;
expect(code.length).to.be.greaterThan(2);
debug(code)
});
it("Should retrieve a block by its hash", async function () {
const blockNumber = await ethers.provider.getBlockNumber();
const block = await ethers.provider.getBlock(blockNumber);
const fetchedBlock = await ethers.provider.getBlock(block.hash);
expect(fetchedBlock).to.not.be.null;
expect(fetchedBlock.hash).to.equal(block.hash);
});
it("Should fetch the number of transactions in a block", async function () {
const block = await ethers.provider.getBlock("latest");
expect(block.transactions).to.be.an('array');
});
it("Should retrieve a transaction receipt", async function () {
const txResponse = await evmTester.setBoolVar(false, {
type: 2, // force it to be EIP-1559
maxPriorityFeePerGas: ethers.parseUnits('400', 'gwei'), // set gas high just to get it included
maxFeePerGas: ethers.parseUnits('400', 'gwei')
});
await txResponse.wait();
const receipt = await ethers.provider.getTransactionReceipt(txResponse.hash);
expect(receipt).to.not.be.undefined;
expect(receipt.hash).to.equal(txResponse.hash);
expect(receipt.blockHash).to.not.be.undefined;
expect(receipt.blockNumber).to.not.be.undefined;
expect(receipt.logsBloom).to.not.be.undefined;
expect(receipt.gasUsed).to.be.greaterThan(0);
expect(receipt.gasPrice).to.be.greaterThan(0);
expect(receipt.type).to.equal(2); // sei is failing this
expect(receipt.status).to.equal(1);
expect(receipt.to).to.equal(await evmTester.getAddress());
expect(receipt.from).to.equal(owner.address);
expect(receipt.cumulativeGasUsed).to.be.greaterThanOrEqual(0); // on seilocal, this is 0
// undefined / null on anvil and goerli
// expect(receipt.contractAddress).to.be.equal(null); // seeing this be null (sei devnet) and not null (anvil, goerli)
expect(receipt.effectiveGasPrice).to.be.undefined;
expect(receipt.transactionHash).to.be.undefined;
expect(receipt.transactionIndex).to.be.undefined;
const logs = receipt.logs
for (let i = 0; i < logs.length; i++) {
const log = logs[i];
expect(log).to.not.be.undefined;
expect(log.address).to.equal(receipt.to);
expect(log.topics).to.be.an('array');
expect(log.data).to.be.a('string');
expect(log.data.startsWith('0x')).to.be.true;
expect(log.data.length).to.be.greaterThan(3);
expect(log.blockNumber).to.equal(receipt.blockNumber);
expect(log.transactionHash).to.not.be.undefined; // somehow log.transactionHash exists but receipt.transactionHash does not
expect(log.transactionHash).to.not.be.undefined;
expect(log.transactionIndex).to.be.greaterThanOrEqual(0);
expect(log.blockHash).to.equal(receipt.blockHash);
// undefined / null on anvil and goerli
expect(log.logIndex).to.be.undefined;
expect(log.removed).to.be.undefined;
}
});
it("Should fetch the current gas price", async function () {
const feeData = await ethers.provider.getFeeData()
expect(isBigNumber(feeData.gasPrice)).to.be.true;
});
it("Should estimate gas for a transaction", async function () {
const estimatedGas = await ethers.provider.estimateGas({
to: await evmTester.getAddress(),
data: evmTester.interface.encodeFunctionData("setBoolVar", [true])
});
expect(isBigNumber(estimatedGas)).to.be.true;
});
it("Should do large estimate gas efficiently", async function () {
batcher = await deployEvmContract("MultiSender");
wallets = generateWallets(12).map(wallet => wallet.address);
const gas = await batcher.batchTransferEqualAmount.estimateGas(wallets, 1000000000000, {value: 100000000000000});
expect(gas).to.be.greaterThan(0);
});
it("Should check the network status", async function () {
const network = await ethers.provider.getNetwork();
expect(network).to.have.property('name');
expect(network).to.have.property('chainId');
});
it("Should fetch the nonce for an account", async function () {
const nonce = await ethers.provider.getTransactionCount(owner.address);
expect(nonce).to.be.a('number');
});
it("Should set log index correctly", async function () {
const blockNumber = await ethers.provider.getBlockNumber();
const numberOfEvents = 5;
// check receipt
const txResponse = await evmTester.emitMultipleLogs(numberOfEvents, { gasPrice: ethers.parseUnits('100', 'gwei') });
const receipt = await txResponse.wait();
expect(receipt.logs.length).to.equal(numberOfEvents)
for(let i=0; i<receipt.logs.length; i++) {
expect(receipt.logs[i].index).to.equal(i);
}
// check logs
const filter = {
fromBlock: blockNumber,
toBlock: 'latest',
address: await evmTester.getAddress(),
topics: [ethers.id("LogIndexEvent(address,uint256)")]
};
const logs = await ethers.provider.getLogs(filter);
expect(logs.length).to.equal(numberOfEvents)
for(let i=0; i<logs.length; i++) {
expect(logs[i].index).to.equal(i);
}
})
it("Should fetch logs for a specific event", async function () {
// Emit an event by making a transaction
const blockNumber = await ethers.provider.getBlockNumber();
const txResponse = await evmTester.setBoolVar(true, { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait();
// Create a filter to get logs
const filter = {
fromBlock: blockNumber,
toBlock: 'latest',
address: await evmTester.getAddress(),
topics: [ethers.id("BoolSet(address,bool)")]
};
// Get the logs
const logs = await ethers.provider.getLogs(filter);
expect(logs).to.be.an('array').that.is.not.empty;
});
it("Should subscribe to an event", async function () {
this.timeout(10000); // Increase timeout for this test
// Create a filter to subscribe to
const filter = {
address: await evmTester.getAddress(),
topics: [ethers.id("BoolSet(address,bool)")]
};
// Subscribe to the filter
const listener = (log) => {
expect(log).to.not.be.null;
ethers.provider.removeListener(filter, listener);
};
ethers.provider.on(filter, listener);
// Trigger the event
const txResponse = await evmTester.setBoolVar(false, { gasPrice: ethers.parseUnits('100', 'gwei') });
await txResponse.wait();
});
it("Should get the current block number", async function () {
const blockNumber = await ethers.provider.getBlockNumber();
expect(blockNumber).to.be.a('number');
});
it("Should fetch a block with full transactions", async function () {
const blockNumber = await ethers.provider.getBlockNumber();
const blockWithTransactions = await ethers.provider.getBlock(blockNumber, true);
expect(blockWithTransactions).to.not.be.null;
expect(blockWithTransactions.transactions).to.be.an('array');
});
it("Should get the chain ID", async function () {
const { chainId } = await ethers.provider.getNetwork()
expect(chainId).to.be.greaterThan(0)
});
it("Should fetch past logs", async function () {
const contractAddress = await evmTester.getAddress()
const filter = {
fromBlock: 1,
toBlock: 'latest',