This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 676
/
api.ts
3668 lines (3460 loc) · 139 KB
/
api.ts
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
//#region Imports
import {
Tag,
BlockLogs,
VM_EXCEPTION,
VM_EXCEPTIONS,
CodedError,
DATA,
InternalFilter,
FilterTypes,
QUANTITY,
EthereumRawAccount
} from "@ganache/ethereum-utils";
import { BaseFeeHeader, Block, RuntimeBlock } from "@ganache/ethereum-block";
import {
Transaction,
TransactionFactory,
TypedTransaction
} from "@ganache/ethereum-transaction";
import {
toRpcSig,
hashPersonalMessage,
KECCAK256_NULL
} from "@ethereumjs/util";
import { signTypedData_v4 } from "eth-sig-util";
import {
Data,
ecsign,
Heap,
Quantity,
PromiEvent,
Api,
keccak,
JsonRpcErrorCode,
min,
max
} from "@ganache/utils";
import Blockchain from "./blockchain";
import { EthereumInternalOptions } from "@ganache/ethereum-options";
import Wallet from "./wallet";
import Emittery from "emittery";
import estimateGas, {
EstimateGasResult,
EstimateGasRunArgs
} from "./helpers/gas-estimator";
import { assertArgLength } from "./helpers/assert-arg-length";
import { parseFilterDetails, parseFilterRange } from "./helpers/filter-parsing";
import { decode } from "@ganache/rlp";
import { Address } from "@ganache/ethereum-address";
import { GanacheRawBlock } from "@ganache/ethereum-block";
import { Capacity } from "./miner/miner";
import { Ethereum } from "./api-types";
async function autofillDefaultTransactionValues(
tx: TypedTransaction,
eth_estimateGas: (
tx: Ethereum.Transaction,
tag: QUANTITY | Ethereum.Tag
) => Promise<Quantity>,
eth_maxPriorityFeePerGas: () => Promise<Quantity>,
transaction: Ethereum.Transaction,
blockchain: Blockchain,
options: EthereumInternalOptions
) {
if (tx.gas.isNull()) {
const defaultLimit = options.miner.defaultTransactionGasLimit;
if (defaultLimit === Quantity.Empty) {
// if the default limit is `Quantity.Empty` use a gas estimate
tx.gas = await eth_estimateGas(transaction, Tag.latest);
} else {
tx.gas = defaultLimit;
}
}
if ("gasPrice" in tx && tx.gasPrice.isNull()) {
tx.gasPrice = options.miner.defaultGasPrice;
}
if ("maxFeePerGas" in tx && tx.maxFeePerGas.isNull()) {
const block = blockchain.blocks.latest;
tx.maxFeePerGas = Quantity.from(
Block.calcNBlocksMaxBaseFee(3, <BaseFeeHeader>block.header)
);
}
if ("maxPriorityFeePerGas" in tx && tx.maxPriorityFeePerGas.isNull()) {
tx.maxPriorityFeePerGas = await eth_maxPriorityFeePerGas();
}
}
const version = process.env.VERSION || "DEV";
//#endregion
//#region Constants
const CLIENT_VERSION = `Ganache/v${version}/EthereumJS TestRPC/v${version}/ethereum-js`;
const PROTOCOL_VERSION = Data.from("0x3f");
const RPC_MODULES = {
eth: "1.0",
net: "1.0",
rpc: "1.0",
web3: "1.0",
evm: "1.0",
personal: "1.0"
} as const;
//#endregion
//#region helpers
/**
* Combines RuntimeErrors for a list of rejected or reverted transactions.
* @param transactions Array of transactions with errors to assert.
*/
function assertExceptionalTransactions(transactions: TypedTransaction[]) {
let baseError: string = null;
let errors: string[];
const data = {};
transactions.forEach(transaction => {
if (transaction.execException) {
if (baseError) {
baseError = VM_EXCEPTIONS;
errors.push(
`${transaction.hash.toString()}: ${transaction.execException}\n`
);
data[transaction.execException.data.hash] =
transaction.execException.data;
} else {
baseError = VM_EXCEPTION;
errors = [transaction.execException.message];
data[transaction.execException.data.hash] =
transaction.execException.data;
}
}
});
if (baseError) {
const err = new Error(baseError + errors.join("\n"));
(err as any).data = data;
throw err;
}
}
//#endregion helpers
export default class EthereumApi implements Api {
readonly [index: string]: (...args: any) => Promise<any>;
readonly #getId = (
id => () =>
Quantity.from(++id)
)(0);
readonly #filters = new Map<string, InternalFilter>();
readonly #subscriptions = new Map<string, Emittery.UnsubscribeFn>();
readonly #options: EthereumInternalOptions;
readonly #blockchain: Blockchain;
readonly #wallet: Wallet;
/**
* This is the Ethereum API that the provider interacts with.
* The only methods permitted on the prototype are the supported json-rpc
* methods.
* @param options -
* @param wallet -
* @param emitter -
*/
constructor(
options: EthereumInternalOptions,
wallet: Wallet,
blockchain: Blockchain
) {
this.#options = options;
this.#wallet = wallet;
this.#blockchain = blockchain;
}
//#region db
/**
* Stores a string in the local database.
*
* @param dbName - Database name.
* @param key - Key name.
* @param value - String to store.
* @returns returns true if the value was stored, otherwise false.
* @example
* ```javascript
* console.log(await provider.send("db_putString", ["testDb", "testKey", "testValue"] ));
* ```
*/
@assertArgLength(3)
async db_putString(
dbName: string,
key: string,
value: string
): Promise<boolean> {
return false;
}
/**
* Returns string from the local database.
*
* @param dbName - Database name.
* @param key - Key name.
* @returns The previously stored string.
* @example
* ```javascript
* console.log(await provider.send("db_getString", ["testDb", "testKey"] ));
* ```
*/
@assertArgLength(2)
async db_getString(dbName: string, key: string) {
return "";
}
/**
* Stores binary data in the local database.
*
* @param dbName - Database name.
* @param key - Key name.
* @param data - Data to store.
* @returns true if the value was stored, otherwise false.
* @example
* ```javascript
* console.log(await provider.send("db_putHex", ["testDb", "testKey", "0x0"] ));
* ```
*/
@assertArgLength(3)
async db_putHex(dbName: string, key: string, data: DATA) {
return false;
}
/**
* Returns binary data from the local database.
*
* @param dbName - Database name.
* @param key - Key name.
* @returns The previously stored data.
* @example
* ```javascript
* console.log(await provider.send("db_getHex", ["testDb", "testKey"] ));
* ```
*/
@assertArgLength(2)
async db_getHex(dbName: string, key: string) {
return "0x00";
}
//#endregion
//#region bzz
/**
* Returns the kademlia table in a readable table format.
* @returns Returns the kademlia table in a readable table format.
* @example
* ```javascript
* console.log(await provider.send("bzz_hive"));
* ```
*/
@assertArgLength(0)
async bzz_hive() {
return [];
}
/**
* Returns details about the swarm node.
* @returns Returns details about the swarm node.
* @example
* ```javascript
* console.log(await provider.send("bzz_info"));
* ```
*/
@assertArgLength(0)
async bzz_info() {
return [];
}
//#endregion
//#region evm
/**
* Force a single block to be mined.
*
* Mines a block independent of whether or not mining is started or stopped.
* Will mine an empty block if there are no available transactions to mine.
*
* @param timestamp - the timestamp the block should be mined with.
* EXPERIMENTAL: Optionally, specify an `options` object with `timestamp`
* and/or `blocks` fields. If `blocks` is given, it will mine exactly `blocks`
* number of blocks, regardless of any other blocks mined or reverted during it's
* operation. This behavior is subject to change!
*
* @returns The string `"0x0"`. May return additional meta-data in the future.
*
* @example
* ```javascript
* console.log("start", await provider.send("eth_blockNumber"));
* await provider.send("evm_mine", [{blocks: 5}] ); // mines 5 blocks
* console.log("end", await provider.send("eth_blockNumber"));
* ```
*/
async evm_mine(): Promise<"0x0">;
async evm_mine(timestamp: number): Promise<"0x0">;
async evm_mine(options: Ethereum.MineOptions): Promise<"0x0">;
@assertArgLength(0, 1)
async evm_mine(arg?: number | Ethereum.MineOptions): Promise<"0x0"> {
// `MINE_ONLY_ONE_BLOCK` refers to the number of blocks mined per call to `blockchain.mine()`
const MINE_ONLY_ONE_BLOCK = true;
const blockchain = this.#blockchain;
const options = this.#options;
const vmErrorsOnRPCResponse = options.chain.vmErrorsOnRPCResponse;
// Since `typeof null === "object"` we have to guard against that
if (arg !== null && typeof arg === "object") {
let { blocks, timestamp } = arg;
if (blocks == null) {
blocks = 1;
}
// TODO(perf): add an option to mine a bunch of blocks in a batch so
// we can save them all to the database in one go.
// Developers like to move the blockchain forward by thousands of blocks
// at a time and doing this would make it way faster
for (let i = 0; i < blocks; i++) {
const { transactions } = await blockchain.mine(
Capacity.FillBlock,
MINE_ONLY_ONE_BLOCK,
timestamp
);
if (vmErrorsOnRPCResponse) {
assertExceptionalTransactions(transactions);
}
}
} else {
const timestamp = arg as number | null;
const { transactions } = await blockchain.mine(
Capacity.FillBlock,
MINE_ONLY_ONE_BLOCK,
timestamp
);
if (vmErrorsOnRPCResponse) {
assertExceptionalTransactions(transactions);
}
}
return "0x0";
}
/**
* Sets the given account's nonce to the specified value. Mines a new block
* before returning.
*
* Warning: this will result in an invalid state tree.
*
* @param address - The account address to update.
* @param nonce - The nonce value to be set.
* @returns `true` if it worked, otherwise `false`.
* @example
* ```javascript
* const nonce = "0x3e8";
* const [address] = await provider.request({ method: "eth_accounts", params: [] });
* const result = await provider.send("evm_setAccountNonce", [address, nonce] );
* console.log(result);
* ```
*/
@assertArgLength(2)
async evm_setAccountNonce(address: DATA, nonce: QUANTITY) {
// TODO: the effect of this function could happen during a block mine operation, which would cause all sorts of
// issues. We need to figure out a good way of timing this.
// Issue: https://github.com/trufflesuite/ganache/issues/1646
const vmAddress = Address.from(address);
const blockchain = this.#blockchain;
const eei = blockchain.vm.eei;
const account = await eei.getAccount(vmAddress);
account.nonce = Quantity.toBigInt(nonce);
await eei.checkpoint();
await eei.putAccount(vmAddress, account);
await eei.commit();
// TODO: do we need to mine a block here? The changes we're making really don't make any sense at all
// and produce an invalid trie going forward.
await blockchain.mine(Capacity.Empty);
return true;
}
/**
* Sets the given account's balance to the specified WEI value. Mines a new block
* before returning.
*
* Warning: this will result in an invalid state tree.
*
* @param address - The account address to update.
* @param balance - The balance value, in WEI, to be set.
* @returns `true` if it worked, otherwise `false`.
* @example
* ```javascript
* const balance = "0x3e8";
* const [address] = await provider.request({ method: "eth_accounts", params: [] });
* const result = await provider.send("evm_setAccountBalance", [address, balance] );
* console.log(result);
* ```
*/
@assertArgLength(2)
async evm_setAccountBalance(address: DATA, balance: QUANTITY) {
// TODO: the effect of this function could happen during a block mine operation, which would cause all sorts of
// issues. We need to figure out a good way of timing this.
// Issue: https://github.com/trufflesuite/ganache/issues/1646
const vmAddress = Address.from(address);
const blockchain = this.#blockchain;
const eei = blockchain.vm.eei;
const account = await eei.getAccount(vmAddress);
account.balance = Quantity.toBigInt(balance);
await eei.checkpoint();
await eei.putAccount(vmAddress, account);
await eei.commit();
// TODO: do we need to mine a block here? The changes we're making really don't make any sense at all
// and produce an invalid trie going forward.
await blockchain.mine(Capacity.Empty);
return true;
}
/**
* Sets the given account's code to the specified data. Mines a new block
* before returning.
*
* Warning: this will result in an invalid state tree.
*
* @param address - The account address to update.
* @param code - The code to be set.
* @returns `true` if it worked, otherwise `false`.
* @example
* ```javascript
* const data = "0xbaddad42";
* const [address] = await provider.request({ method: "eth_accounts", params: [] });
* const result = await provider.send("evm_setAccountCode", [address, data] );
* console.log(result);
* ```
*/
@assertArgLength(2)
async evm_setAccountCode(address: DATA, code: DATA) {
// TODO: the effect of this function could happen during a block mine operation, which would cause all sorts of
// issues. We need to figure out a good way of timing this.
// Issue: https://github.com/trufflesuite/ganache/issues/1646
const vmAddress = Address.from(address);
const codeBuffer = Data.toBuffer(code);
const blockchain = this.#blockchain;
const eei = blockchain.vm.eei;
// The ethereumjs-vm StateManager does not allow to set empty code,
// therefore we will manually set the code hash when "clearing" the contract code
await eei.checkpoint();
if (codeBuffer.length > 0) {
await eei.putContractCode(vmAddress, codeBuffer);
} else {
const account = await eei.getAccount(vmAddress);
account.codeHash = KECCAK256_NULL;
await eei.putAccount(vmAddress, account);
}
await eei.commit();
// TODO: do we need to mine a block here? The changes we're making really don't make any sense at all
// and produce an invalid trie going forward.
await blockchain.mine(Capacity.Empty);
return true;
}
/**
* Sets the given account's storage slot to the specified data. Mines a new block
* before returning.
*
* Warning: this will result in an invalid state tree.
*
* @param address - The account address to update.
* @param slot - The storage slot that should be set.
* @param value - The value to be set.
* @returns `true` if it worked, otherwise `false`.
* @example
* ```javascript
* const slot = "0x0000000000000000000000000000000000000000000000000000000000000005";
* const data = "0xbaddad42";
* const [address] = await provider.request({ method: "eth_accounts", params: [] });
* const result = await provider.send("evm_setAccountStorageAt", [address, slot, data] );
* console.log(result);
* ```
*/
@assertArgLength(3)
async evm_setAccountStorageAt(address: DATA, slot: DATA, value: DATA) {
// TODO: the effect of this function could happen during a block mine operation, which would cause all sorts of
// issues. We need to figure out a good way of timing this.
// Issue: https://github.com/trufflesuite/ganache/issues/1646
const vmAddress = Address.from(address);
const slotBuffer = Data.toBuffer(slot);
const valueBuffer = Data.toBuffer(value);
const blockchain = this.#blockchain;
const eei = blockchain.vm.eei;
await eei.checkpoint();
await eei.putContractStorage(vmAddress, slotBuffer, valueBuffer);
await eei.commit();
// TODO: do we need to mine a block here? The changes we're making really don't make any sense at all
// and produce an invalid trie going forward.
await blockchain.mine(Capacity.Empty);
return true;
}
/**
* Jump forward in time by the given amount of time, in seconds.
* @param seconds - Number of seconds to jump forward in time by. Must be greater than or equal to `0`.
* @returns Returns the total time adjustment, in seconds.
* @example
* ```javascript
* const seconds = 10;
* const timeAdjustment = await provider.send("evm_increaseTime", [seconds] );
* console.log(timeAdjustment);
* ```
*/
@assertArgLength(1)
async evm_increaseTime(seconds: number | QUANTITY) {
const milliseconds =
(typeof seconds === "number" ? seconds : Quantity.toNumber(seconds)) *
1000;
return Math.floor(this.#blockchain.increaseTime(milliseconds) / 1000);
}
/**
* Sets the internal clock time to the given timestamp.
*
* Warning: This will allow you to move *backwards* in time, which may cause
* new blocks to appear to be mined before old blocks. This will result in
* an invalid state.
*
* @param time - JavaScript timestamp (millisecond precision).
* @returns The amount of *seconds* between the given timestamp and now.
* @example
* ```javascript
* const currentDate = Date.now();
* setTimeout(async () => {
* const time = await provider.send("evm_setTime", [currentDate] );
* console.log(time); // should be about two seconds ago
* }, 1000);
* ```
*/
@assertArgLength(0, 1)
async evm_setTime(time: number | QUANTITY | Date) {
let timestamp: number;
switch (typeof time) {
case "object":
timestamp = time.getTime();
break;
case "number":
timestamp = time;
break;
default:
timestamp = Quantity.toNumber(time);
break;
}
const blockchain = this.#blockchain;
const offsetMilliseconds = blockchain.setTimeDiff(timestamp);
// convert offsetMilliseconds to seconds:
return Math.floor(offsetMilliseconds / 1000);
}
/**
* Revert the state of the blockchain to a previous snapshot. Takes a single
* parameter, which is the snapshot id to revert to. This deletes the given
* snapshot, as well as any snapshots taken after (e.g.: reverting to id 0x1
* will delete snapshots with ids 0x1, 0x2, etc.)
*
* @param snapshotId - The snapshot id to revert.
* @returns `true` if a snapshot was reverted, otherwise `false`.
*
* @example
* ```javascript
* const [from, to] = await provider.send("eth_accounts");
* const startingBalance = BigInt(await provider.send("eth_getBalance", [from] ));
*
* // take a snapshot
* const snapshotId = await provider.send("evm_snapshot");
*
* // send value to another account (over-simplified example)
* await provider.send("eth_subscribe", ["newHeads"] );
* await provider.send("eth_sendTransaction", [{from, to, value: "0xffff"}] );
* await provider.once("message"); // Note: `await provider.once` is non-standard
*
* // ensure balance has updated
* const newBalance = await provider.send("eth_getBalance", [from] );
* assert(BigInt(newBalance) < startingBalance);
*
* // revert the snapshot
* const isReverted = await provider.send("evm_revert", [snapshotId] );
* assert(isReverted);
* console.log({isReverted: isReverted});
*
* // ensure balance has reverted
* const endingBalance = await provider.send("eth_getBalance", [from] );
* const isBalanceReverted = assert.strictEqual(BigInt(endingBalance), startingBalance);
* console.log({isBalanceReverted: isBalanceReverted});
* ```
*/
@assertArgLength(1)
async evm_revert(snapshotId: QUANTITY) {
return this.#blockchain.revert(Quantity.from(snapshotId));
}
/**
* Snapshot the state of the blockchain at the current block. Takes no
* parameters. Returns the id of the snapshot that was created. A snapshot can
* only be reverted once. After a successful `evm_revert`, the same snapshot
* id cannot be used again. Consider creating a new snapshot after each
* `evm_revert` if you need to revert to the same point multiple times.
*
* @returns The hex-encoded identifier for this snapshot.
*
* @example
* ```javascript
* const provider = ganache.provider();
* const [from, to] = await provider.send("eth_accounts");
* const startingBalance = BigInt(await provider.send("eth_getBalance", [from] ));
*
* // take a snapshot
* const snapshotId = await provider.send("evm_snapshot");
*
* // send value to another account (over-simplified example)
* await provider.send("eth_subscribe", ["newHeads"] );
* await provider.send("eth_sendTransaction", [{from, to, value: "0xffff"}] );
* await provider.once("message"); // Note: `await provider.once` is non-standard
*
* // ensure balance has updated
* const newBalance = await provider.send("eth_getBalance", [from] );
* assert(BigInt(newBalance) < startingBalance);
*
* // revert the snapshot
* const isReverted = await provider.send("evm_revert", [snapshotId] );
* assert(isReverted);
*
* // ensure balance has reverted
* const endingBalance = await provider.send("eth_getBalance", [from] );
* const isBalanceReverted = assert.strictEqual(BigInt(endingBalance), startingBalance);
* console.log({isBalanceReverted: isBalanceReverted});
* ```
*/
async evm_snapshot() {
return Quantity.from(this.#blockchain.snapshot());
}
/**
* Adds any arbitrary account to the `personal` namespace.
*
* Note: accounts already known to the `personal` namespace and accounts
* returned by `eth_accounts` cannot be re-added using this method.
* @param address - The address of the account to add to the `personal`
* namespace.
* @param passphrase - The passphrase used to encrypt the account's private key.
* NOTE: this passphrase will be needed for all `personal` namespace calls
* that require a password.
* @returns `true` if the account was successfully added. `false` if the
* account is already in the `personal` namespace.
* @example
* ```javascript
* const address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";
* const passphrase = "passphrase"
* const result = await provider.send("evm_addAccount", [address, passphrase] );
* console.log(result);
* ```
*/
async evm_addAccount(address: DATA, passphrase: string) {
const addy = Address.from(address);
return this.#wallet.addUnknownAccount(addy, passphrase);
}
/**
* Removes an account from the `personal` namespace.
*
* Note: accounts not known to the `personal` namespace cannot be removed
* using this method.
* @param address - The address of the account to remove from the `personal`
* namespace.
* @param passphrase - The passphrase used to decrypt the account's private key.
* @returns `true` if the account was successfully removed. `false` if the
* account was not in the `personal` namespace.
* @example
* ```javascript
* const [address] = await provider.request({ method: "eth_accounts", params: [] });
* const passphrase = "passphrase"
* const result = await provider.send("evm_removeAccount", [address, passphrase] );
* console.log(result);
* ```
*/
async evm_removeAccount(address: DATA, passphrase: string) {
const addy = Address.from(address);
return this.#wallet.removeKnownAccount(addy, passphrase);
}
//#endregion evm
//#region miner
/**
* Resume the CPU mining process with the given number of threads.
*
* Note: `threads` is ignored.
* @param threads - Number of threads to resume the CPU mining process with.
* @returns `true`.
* @example
* ```javascript
* await provider.send("miner_stop");
* // check that eth_mining returns false
* console.log(await provider.send("eth_mining"));
* await provider.send("miner_start");
* // check that eth_mining returns true
* console.log(await provider.send("eth_mining"));
* ```
*/
@assertArgLength(0, 1)
async miner_start(threads: number = 1) {
if (this.#options.miner.instamine === "eager") {
const resumption = await this.#blockchain.resume(threads);
// resumption can be undefined if the blockchain isn't currently paused
if (
resumption &&
resumption.transactions != null &&
this.#options.chain.vmErrorsOnRPCResponse
) {
assertExceptionalTransactions(resumption.transactions);
}
} else {
this.#blockchain.resume(threads);
}
return true;
}
/**
* Stop the CPU mining operation.
* @returns `true`.
* @example
* ```javascript
* // check that eth_mining returns true
* console.log(await provider.send("eth_mining"));
* await provider.send("miner_stop");
* // check that eth_mining returns false
* console.log(await provider.send("eth_mining"));
* ```
*/
@assertArgLength(0)
async miner_stop() {
this.#blockchain.pause();
return true;
}
/**
* Sets the default accepted gas price when mining transactions.
* Any transactions that don't specify a gas price will use this amount.
* Transactions that are below this limit are excluded from the mining process.
* @param number - Default accepted gas price.
* @returns `true`.
* @example
* ```javascript
* console.log(await provider.send("miner_setGasPrice", [300000] ));
* ```
*/
@assertArgLength(1)
async miner_setGasPrice(number: QUANTITY) {
this.#options.miner.defaultGasPrice = Quantity.from(number);
return true;
}
/**
* Sets the etherbase, where mining rewards will go.
* @param address - The address where the mining rewards will go.
* @returns `true`.
* @example
* ```javascript
* const [account] = await provider.request({ method: "eth_accounts", params: [] });
* console.log(await provider.send("miner_setEtherbase", [account] ));
* ```
*/
@assertArgLength(1)
async miner_setEtherbase(address: DATA) {
this.#blockchain.coinbase = Address.from(address);
return true;
}
/**
* Set the extraData block header field a miner can include.
* @param extra - The `extraData` to include.
* @returns If successfully set returns `true`, otherwise returns an error.
* @example
* ```javascript
* console.log(await provider.send("miner_setExtra", ["0x0"] ));
* ```
*/
@assertArgLength(1)
async miner_setExtra(extra: DATA) {
const bytes = Data.from(extra);
const length = bytes.toBuffer().length;
if (length > 32) {
throw new Error(`extra exceeds max length. ${length} > 32`);
}
this.#options.miner.extraData = bytes;
return true;
}
//#endregion
//#region web3
/**
* Returns the current client version.
* @returns The current client version.
* @example
* ```javascript
* console.log(await provider.send("web3_clientVersion"));
* ```
*/
@assertArgLength(0)
async web3_clientVersion() {
return CLIENT_VERSION;
}
/**
* Returns Keccak-256 (not the standardized SHA3-256) of the given data.
* @param data - the data to convert into a SHA3 hash.
* @returns The SHA3 result of the given string.
* @example
* ```javascript
* const data = "hello trufflers";
* const sha3 = await provider.send("web3_sha3", [data] );
* console.log(sha3);
* ```
*/
@assertArgLength(1)
async web3_sha3(data: DATA) {
return Data.from(keccak(Data.toBuffer(data)));
}
//#endregion
//#region net
/**
* Returns the current network id.
* @returns The current network id. This value should NOT be JSON-RPC
* Quantity/Data encoded.
* @example
* ```javascript
* console.log(await provider.send("net_version"));
* ```
*/
@assertArgLength(0)
async net_version() {
return this.#options.chain.networkId.toString();
}
/**
* Returns `true` if client is actively listening for network connections.
* @returns `true` when listening, otherwise `false`.
* @example
* ```javascript
* console.log(await provider.send("net_listening"));
* ```
*/
@assertArgLength(0)
async net_listening() {
return true;
}
/**
* Returns number of peers currently connected to the client.
* @returns Number of connected peers.
* @example
* ```javascript
* console.log(await provider.send("net_peerCount"));
* ```
*/
@assertArgLength(0)
async net_peerCount() {
return Quantity.Zero;
}
//#endregion
//#region eth
/**
* Generates and returns an estimate of how much gas is necessary to allow the
* transaction to complete. The transaction will not be added to the
* blockchain. Note that the estimate may be significantly more than the
* amount of gas actually used by the transaction, for a variety of reasons
* including EVM mechanics and node performance.
*
* Transaction call object:
* * `from`: `DATA`, 20 bytes (optional) - The address the transaction is sent from.
* * `to`: `DATA`, 20 bytes - The address the transaction is sent to.
* * `gas`: `QUANTITY` (optional) - Integer of the maximum gas allowance for the transaction.
* * `gasPrice`: `QUANTITY` (optional) - Integer of the price of gas in wei.
* * `value`: `QUANTITY` (optional) - Integer of the value in wei.
* * `data`: `DATA` (optional) - Hash of the method signature and the ABI encoded parameters.
*
* @param transaction - The transaction call object as seen in source.
* @param blockNumber - Integer block number, or the string "latest", "earliest"
* or "pending".
*
* @returns The amount of gas used.
*
* @example
* ```javascript
* const [from, to] = await provider.request({ method: "eth_accounts", params: [] });
* const gasEstimate = await provider.request({ method: "eth_estimateGas", params: [{ from, to }, "latest" ] });
* console.log(gasEstimate);
* ```
*/
@assertArgLength(1, 2)
async eth_estimateGas(
transaction: Ethereum.Transaction,
blockNumber: QUANTITY | Ethereum.Tag = Tag.latest
): Promise<Quantity> {
const blockchain = this.#blockchain;
const blocks = blockchain.blocks;
const parentBlock = await blocks.get(blockNumber);
const parentHeader = parentBlock.header;
const options = this.#options;
const generateVM = async () => {
// note(hack): blockchain.vm.copy() doesn't work so we just do it this way
// /shrug
const vm = await blockchain.createVmFromStateTrie(
blockchain.trie.copy(false),
options.chain.allowUnlimitedContractSize,
false
);
return vm;
};
return new Promise((resolve, reject) => {
const { coinbase } = blockchain;
const tx = TransactionFactory.fromRpc(
transaction as Transaction,
blockchain.common
);
if (tx.from == null) {
tx.from = coinbase;
}
if (tx.gas.isNull()) {
// eth_estimateGas isn't subject to regular transaction gas limits
tx.gas = options.miner.callGasLimit;
}
const block = new RuntimeBlock(
Quantity.from((parentHeader.number.toBigInt() || 0n) + 1n),
parentHeader.parentHash,
new Address(parentHeader.miner.toBuffer()),
tx.gas,
parentHeader.gasUsed,
parentHeader.timestamp,
options.miner.difficulty,
parentHeader.totalDifficulty,
blockchain.getMixHash(parentHeader.parentHash.toBuffer()),
0n // no baseFeePerGas for estimates
);
const runArgs: EstimateGasRunArgs = {
tx: tx.toVmTransaction(),
block,
skipBalance: true,
skipNonce: true
};
estimateGas(
generateVM,
runArgs,
(err: Error, result: EstimateGasResult) => {
if (err) return void reject(err);
resolve(Quantity.from(result.gasEstimate));
}
);
});
}
/**
* Returns the current ethereum protocol version.
* @returns The current ethereum protocol version.
* @example
* ```javascript
* const version = await provider.request({ method: "eth_protocolVersion", params: [] });
* console.log(version);
* ```
*/
@assertArgLength(0)
async eth_protocolVersion() {
return PROTOCOL_VERSION;
}
/**
* Returns an object containing data about the sync status or `false` when not syncing.
*
* @returns An object with sync status data or `false`, when not syncing.
*
* * `startingBlock`: \{bigint\} The block at which the import started (will
* only be reset, after the sync reached his head).
* * `currentBlock`: \{bigint\} The current block, same as `eth_blockNumber`.
* * `highestBlock`: \{bigint\} The estimated highest block.
*
* @example
* ```javascript
* const result = await provider.request({ method: "eth_syncing", params: [] });
* console.log(result);
* ```
*/
@assertArgLength(0)