-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathcontract.ts
1203 lines (1081 loc) · 35.9 KB
/
contract.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
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import { Web3Context, Web3EventEmitter, Web3PromiEvent } from 'web3-core';
import { ContractExecutionError, SubscriptionError, Web3ContractError } from 'web3-errors';
import {
call,
estimateGas,
getLogs,
NewHeadsSubscription,
sendTransaction,
SendTransactionEvents,
} from 'web3-eth';
import {
AbiConstructorFragment,
AbiErrorFragment,
AbiEventFragment,
AbiFragment,
AbiFunctionFragment,
ContractAbi,
ContractConstructorArgs,
ContractEvent,
ContractEvents,
ContractMethod,
encodeEventSignature,
encodeFunctionSignature,
FilterAbis,
isAbiErrorFragment,
isAbiEventFragment,
isAbiFunctionFragment,
jsonInterfaceMethodToString,
} from 'web3-eth-abi';
import {
Address,
BlockNumberOrTag,
BlockTags,
Bytes,
EthExecutionAPI,
Filter,
HexString,
LogsInput,
Mutable,
Common,
} from 'web3-types';
import {
DataFormat,
DEFAULT_RETURN_FORMAT,
format,
isDataFormat,
toChecksumAddress,
} from 'web3-utils';
import {
isNullish,
validator,
utils as validatorUtils,
ValidationSchemaInput,
Web3ValidatorError,
Web3ValidationErrorObject,
} from 'web3-validator';
import { ALL_EVENTS_ABI } from './constants';
import {
decodeEventABI,
decodeMethodReturn,
encodeEventABI,
encodeMethodABI,
decodeErrorData,
} from './encoding';
import { LogsSubscription } from './log_subscription';
import {
ContractAbiWithSignature,
ContractEventOptions,
ContractInitOptions,
ContractOptions,
EventLog,
NonPayableCallOptions,
NonPayableMethodObject,
NonPayableTxOptions,
PayableCallOptions,
PayableMethodObject,
PayableTxOptions,
Web3ContractContext,
} from './types';
import {
getEstimateGasParams,
getEthTxCallParams,
getSendTxParams,
isContractInitOptions,
isWeb3ContractContext,
} from './utils';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ContractBoundMethod<
Abi extends AbiFunctionFragment,
Method extends ContractMethod<Abi> = ContractMethod<Abi>,
> = (
...args: Method['Inputs']
) => Method['Abi']['stateMutability'] extends 'payable' | 'pure'
? PayableMethodObject<Method['Inputs'], Method['Outputs']>
: NonPayableMethodObject<Method['Inputs'], Method['Outputs']>;
// To avoid circular dependency between types and encoding, declared these types here.
export type ContractMethodsInterface<Abi extends ContractAbi> = {
[MethodAbi in FilterAbis<
Abi,
AbiFunctionFragment & { type: 'function' }
> as MethodAbi['name']]: ContractBoundMethod<MethodAbi>;
// To allow users to use method signatures
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} & { [key: string]: ContractBoundMethod<any> };
/**
* The event object can be accessed from `myContract.events.myEvent`.
*
* \> Remember: To subscribe to an event, your provider must have support for subscriptions.
*
* ```ts
* const subscription = await myContract.events.MyEvent([options])
* ```
*
* @param options - The options used to subscribe for the event
* @returns - A Promise resolved with {@link LogsSubscription} object
*/
export type ContractBoundEvent = (options?: ContractEventOptions) => LogsSubscription;
// To avoid circular dependency between types and encoding, declared these types here.
export type ContractEventsInterface<
Abi extends ContractAbi,
Events extends ContractEvents<Abi> = ContractEvents<Abi>,
> = {
[Name in keyof Events | 'allEvents']: ContractBoundEvent;
} & {
[key: string]: ContractBoundEvent;
};
// To avoid circular dependency between types and encoding, declared these types here.
export type ContractEventEmitterInterface<Abi extends ContractAbi> = {
[EventAbi in FilterAbis<
Abi,
AbiFunctionFragment & { type: 'event' }
> as EventAbi['name']]: ContractEvent<EventAbi>['Inputs'];
};
type EventParameters = Parameters<typeof encodeEventABI>[2];
const contractSubscriptions = {
logs: LogsSubscription,
newHeads: NewHeadsSubscription,
newBlockHeaders: NewHeadsSubscription,
};
/**
* The class designed to interact with smart contracts on the Ethereum blockchain.
*/
export class Contract<Abi extends ContractAbi>
extends Web3Context<EthExecutionAPI, typeof contractSubscriptions>
implements Web3EventEmitter<ContractEventEmitterInterface<Abi>>
{
/**
* The options `object` for the contract instance. `from`, `gas` and `gasPrice` are used as fallback values when sending transactions.
*
* ```ts
* myContract.options;
* > {
* address: '0x1234567890123456789012345678901234567891',
* jsonInterface: [...],
* from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
* gasPrice: '10000000000000',
* gas: 1000000
* }
*
* myContract.options.from = '0x1234567890123456789012345678901234567891'; // default from address
* myContract.options.gasPrice = '20000000000000'; // default gas price in wei
* myContract.options.gas = 5000000; // provide as fallback always 5M gas
* ```
*/
public readonly options: ContractOptions;
/**
* Can be used to set {@link Contract.defaultAccount} for all contracts.
*/
public static defaultAccount?: HexString;
/**
* Can be used to set {@link Contract.defaultBlock} for all contracts.
*/
public static defaultBlock?: BlockNumberOrTag;
/**
* Can be used to set {@link Contract.defaultHardfork} for all contracts.
*/
public static defaultHardfork?: string;
/**
* Can be used to set {@link Contract.defaultCommon} for all contracts.
*/
public static defaultCommon?: Common;
/**
* Can be used to set {@link Contract.transactionSendTimeout} for all contracts.
*/
public static transactionSendTimeout?: number;
/**
* Can be used to set {@link Contract.transactionBlockTimeout} for all contracts.
*/
public static transactionBlockTimeout?: number;
/**
* Can be used to set {@link Contract.transactionConfirmationBlocks} for all contracts.
*/
public static transactionConfirmationBlocks?: number;
/**
* Can be used to set {@link Contract.transactionPollingInterval} for all contracts.
*/
public static transactionPollingInterval?: number;
/**
* Can be used to set {@link Contract.transactionPollingTimeout} for all contracts.
*/
public static transactionPollingTimeout?: number;
/**
* Can be used to set {@link Contract.transactionReceiptPollingInterval} for all contracts.
*/
public static transactionReceiptPollingInterval?: number;
/**
* Can be used to set {@link Contract.transactionConfirmationPollingInterval} for all contracts.
*/
public static transactionConfirmationPollingInterval?: number;
/**
* Can be used to set {@link Contract.blockHeaderTimeout} for all contracts.
*/
public static blockHeaderTimeout?: number;
/**
* Can be used to set {@link Contract.handleRevert} for all contracts.
*/
public static handleRevert?: boolean;
private _jsonInterface!: ContractAbiWithSignature;
private _address?: Address;
private _functions: Record<
string,
{
signature: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
method: ContractBoundMethod<any>;
}
> = {};
private readonly _overloadedMethodAbis: Map<string, AbiFunctionFragment[]>;
private _methods!: ContractMethodsInterface<Abi>;
private _events!: ContractEventsInterface<Abi>;
/**
* Creates a new contract instance with all its methods and events defined in its {@doclink glossary/json_interface | json interface} object.
*
* ```ts
* new web3.eth.Contract(jsonInterface[, address][, options])
* ```
*
* @param jsonInterface - The JSON interface for the contract to instantiate.
* @param address - The address of the smart contract to call.
* @param options - The options of the contract. Some are used as fallbacks for calls and transactions.
* @param context - The context of the contract used for customizing the behavior of the contract.
* @returns - The contract instance with all its methods and events.
*
* ```ts title="Example"
* var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
* from: '0x1234567890123456789012345678901234567891', // default from address
* gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
* });
* ```
*
* To use the type safe interface for these contracts you have to include the ABI definitions in your Typescript project and then declare these as `const`.
*
* ```ts title="Example"
* const myContractAbi = [....] as const; // ABI definitions
* const myContract = new web3.eth.Contract(myContractAbi, '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe');
* ```
*/
public constructor(
jsonInterface: Abi,
context?: Web3ContractContext,
returnFormat?: DataFormat,
);
public constructor(
jsonInterface: Abi,
address: Address,
contextOrReturnFormat?: Web3ContractContext | DataFormat,
returnFormat?: DataFormat,
);
public constructor(
jsonInterface: Abi,
options?: ContractInitOptions,
contextOrReturnFormat?: Web3ContractContext | DataFormat,
returnFormat?: DataFormat,
);
public constructor(
jsonInterface: Abi,
address: Address,
options: ContractInitOptions,
contextOrReturnFormat?: Web3ContractContext | DataFormat,
returnFormat?: DataFormat,
);
public constructor(
jsonInterface: Abi,
addressOrOptionsOrContext?: Address | ContractInitOptions | Web3ContractContext,
optionsOrContextOrReturnFormat?: ContractInitOptions | Web3ContractContext | DataFormat,
contextOrReturnFormat?: Web3ContractContext | DataFormat,
returnFormat?: DataFormat,
) {
super({
// Due to abide by the rule that super must be first call in constructor
// Have to do this complex ternary conditions
// eslint-disable-next-line no-nested-ternary
...(isWeb3ContractContext(addressOrOptionsOrContext)
? addressOrOptionsOrContext
: isWeb3ContractContext(optionsOrContextOrReturnFormat)
? optionsOrContextOrReturnFormat
: contextOrReturnFormat),
provider:
typeof addressOrOptionsOrContext !== 'string'
? addressOrOptionsOrContext?.provider ??
// eslint-disable-next-line no-nested-ternary
(typeof optionsOrContextOrReturnFormat === 'object' &&
'provider' in optionsOrContextOrReturnFormat
? optionsOrContextOrReturnFormat.provider
: typeof contextOrReturnFormat === 'object' &&
'provider' in contextOrReturnFormat
? contextOrReturnFormat?.provider
: Contract.givenProvider)
: undefined,
registeredSubscriptions: contractSubscriptions,
});
this._overloadedMethodAbis = new Map<string, AbiFunctionFragment[]>();
// eslint-disable-next-line no-nested-ternary
const returnDataFormat = isDataFormat(contextOrReturnFormat)
? contextOrReturnFormat
: isDataFormat(optionsOrContextOrReturnFormat)
? optionsOrContextOrReturnFormat
: returnFormat ?? DEFAULT_RETURN_FORMAT;
const address =
typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined;
// eslint-disable-next-line no-nested-ternary
const options = isContractInitOptions(addressOrOptionsOrContext)
? addressOrOptionsOrContext
: isContractInitOptions(optionsOrContextOrReturnFormat)
? optionsOrContextOrReturnFormat
: undefined;
this._parseAndSetJsonInterface(jsonInterface, returnDataFormat);
if (!isNullish(address)) {
this._parseAndSetAddress(address, returnDataFormat);
}
this.options = {
address,
jsonInterface: this._jsonInterface,
gas: options?.gas ?? options?.gasLimit,
gasPrice: options?.gasPrice,
gasLimit: options?.gasLimit,
from: options?.from,
data: options?.data,
};
Object.defineProperty(this.options, 'address', {
set: (value: Address) => this._parseAndSetAddress(value, returnDataFormat),
get: () => this._address,
});
Object.defineProperty(this.options, 'jsonInterface', {
set: (value: ContractAbi) => this._parseAndSetJsonInterface(value, returnDataFormat),
get: () => this._jsonInterface,
});
}
public get defaultAccount() {
return (this.constructor as typeof Contract).defaultAccount ?? super.defaultAccount;
}
public set defaultAccount(value: Address | undefined) {
super.defaultAccount = value;
}
public get defaultBlock() {
return (this.constructor as typeof Contract).defaultBlock ?? super.defaultBlock;
}
public set defaultBlock(value: BlockNumberOrTag) {
super.defaultBlock = value;
}
public get defaultHardfork() {
return (this.constructor as typeof Contract).defaultHardfork ?? super.defaultHardfork;
}
public set defaultHardfork(value: string) {
super.defaultHardfork = value;
}
public get defaultCommon(): Common | undefined {
return (this.constructor as typeof Contract).defaultCommon ?? super.defaultCommon;
}
public set defaultCommon(value: Common | undefined) {
super.defaultCommon = value;
}
public get transactionSendTimeout() {
return (
(this.constructor as typeof Contract).transactionSendTimeout ??
super.transactionSendTimeout
);
}
public set transactionSendTimeout(value: number) {
super.transactionSendTimeout = value;
}
public get transactionBlockTimeout() {
return (
(this.constructor as typeof Contract).transactionBlockTimeout ??
super.transactionBlockTimeout
);
}
public set transactionBlockTimeout(value: number) {
super.transactionBlockTimeout = value;
}
public get transactionConfirmationBlocks() {
return (
(this.constructor as typeof Contract).transactionConfirmationBlocks ??
super.transactionConfirmationBlocks
);
}
public set transactionConfirmationBlocks(value: number) {
super.transactionConfirmationBlocks = value;
}
public get transactionPollingInterval() {
return (
(this.constructor as typeof Contract).transactionPollingInterval ??
super.transactionPollingInterval
);
}
public set transactionPollingInterval(value: number) {
super.transactionPollingInterval = value;
}
public get transactionPollingTimeout() {
return (
(this.constructor as typeof Contract).transactionPollingTimeout ??
super.transactionPollingTimeout
);
}
public set transactionPollingTimeout(value: number) {
super.transactionPollingTimeout = value;
}
public get transactionReceiptPollingInterval() {
return (
(this.constructor as typeof Contract).transactionReceiptPollingInterval ??
super.transactionReceiptPollingInterval
);
}
public set transactionReceiptPollingInterval(value: number | undefined) {
super.transactionReceiptPollingInterval = value;
}
public get transactionConfirmationPollingInterval() {
return (
(this.constructor as typeof Contract).transactionConfirmationPollingInterval ??
super.transactionConfirmationPollingInterval
);
}
public set transactionConfirmationPollingInterval(value: number | undefined) {
super.transactionConfirmationPollingInterval = value;
}
public get blockHeaderTimeout() {
return (this.constructor as typeof Contract).blockHeaderTimeout ?? super.blockHeaderTimeout;
}
public set blockHeaderTimeout(value: number) {
super.blockHeaderTimeout = value;
}
public get handleRevert() {
return (this.constructor as typeof Contract).handleRevert ?? super.handleRevert;
}
public set handleRevert(value: boolean) {
super.handleRevert = value;
}
/**
* Subscribe to an event.
*
* ```ts
* await myContract.events.MyEvent([options])
* ```
*
* There is a special event `allEvents` that can be used to subscribe all events.
*
* ```ts
* await myContract.events.allEvents([options])
* ```
*
* @returns - When individual event is accessed will returns {@link ContractBoundEvent} object
*/
public get events() {
return this._events;
}
/**
* Creates a transaction object for that method, which then can be `called`, `send`, `estimated`, `createAccessList` , or `ABI encoded`.
*
* The methods of this smart contract are available through:
*
* The name: `myContract.methods.myMethod(123)`
* The name with parameters: `myContract.methods['myMethod(uint256)'](123)`
* The signature `myContract.methods['0x58cf5f10'](123)`
*
* This allows calling functions with same name but different parameters from the JavaScript contract object.
*
* \> The method signature does not provide a type safe interface, so we recommend to use method `name` instead.
*
* ```ts
* // calling a method
* const result = await myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});
*
* // or sending and using a promise
* const receipt = await myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});
*
* // or sending and using the events
* const sendObject = myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'});
* sendObject.on('transactionHash', function(hash){
* ...
* });
* sendObject.on('receipt', function(receipt){
* ...
* });
* sendObject.on('confirmation', function(confirmationNumber, receipt){
* ...
* });
* sendObject.on('error', function(error, receipt) {
* ...
* });
* ```
*
* @returns - Either returns {@link PayableMethodObject} or {@link NonPayableMethodObject} based on the definitions of the {@doclink glossary/json_interface | json interface} of that contract.
*/
public get methods() {
return this._methods;
}
/**
* Clones the current contract instance. This doesn't deploy contract on blockchain and only creates a local clone.
*
* @returns - The new contract instance.
*
* ```ts
* const contract1 = new eth.Contract(abi, address, {gasPrice: '12345678', from: fromAddress});
*
* const contract2 = contract1.clone();
* contract2.options.address = address2;
*
* (contract1.options.address !== contract2.options.address);
* > true
* ```
*/
public clone() {
if (this.options.address) {
return new Contract<Abi>(
this._jsonInterface as unknown as Abi,
this.options.address,
{
gas: this.options.gas,
gasPrice: this.options.gasPrice,
gasLimit: this.options.gasLimit,
from: this.options.from,
data: this.options.data,
provider: this.currentProvider,
},
this.getContextObject(),
);
}
return new Contract<Abi>(
this._jsonInterface as unknown as Abi,
{
gas: this.options.gas,
gasPrice: this.options.gasPrice,
gasLimit: this.options.gasLimit,
from: this.options.from,
data: this.options.data,
provider: this.currentProvider,
},
this.getContextObject(),
);
}
/**
* Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance.
*
* ```ts
* myContract.deploy({
* data: '0x12345...',
* arguments: [123, 'My String']
* })
* .send({
* from: '0x1234567890123456789012345678901234567891',
* gas: 1500000,
* gasPrice: '30000000000000'
* }, function(error, transactionHash){ ... })
* .on('error', function(error){ ... })
* .on('transactionHash', function(transactionHash){ ... })
* .on('receipt', function(receipt){
* console.log(receipt.contractAddress) // contains the new contract address
* })
* .on('confirmation', function(confirmationNumber, receipt){ ... })
* .then(function(newContractInstance){
* console.log(newContractInstance.options.address) // instance with the new contract address
* });
*
*
* // When the data is already set as an option to the contract itself
* myContract.options.data = '0x12345...';
*
* myContract.deploy({
* arguments: [123, 'My String']
* })
* .send({
* from: '0x1234567890123456789012345678901234567891',
* gas: 1500000,
* gasPrice: '30000000000000'
* })
* .then(function(newContractInstance){
* console.log(newContractInstance.options.address) // instance with the new contract address
* });
*
*
* // Simply encoding
* myContract.deploy({
* data: '0x12345...',
* arguments: [123, 'My String']
* })
* .encodeABI();
* > '0x12345...0000012345678765432'
*
*
* // Gas estimation
* myContract.deploy({
* data: '0x12345...',
* arguments: [123, 'My String']
* })
* .estimateGas(function(err, gas){
* console.log(gas);
* });
* ```
*
* @returns - The transaction object
*/
public deploy(deployOptions?: {
/**
* The byte code of the contract.
*/
data?: HexString;
/**
* The arguments which get passed to the constructor on deployment.
*/
arguments?: ContractConstructorArgs<Abi>;
}) {
let abi = this._jsonInterface.find(j => j.type === 'constructor') as AbiConstructorFragment;
if (!abi) {
abi = {
type: 'constructor',
inputs: [],
stateMutability: '',
} as AbiConstructorFragment;
}
const data = format(
{ eth: 'bytes' },
deployOptions?.data ?? this.options.data,
DEFAULT_RETURN_FORMAT,
);
if (!data || data.trim() === '0x') {
throw new Web3ContractError('contract creation without any data provided.');
}
const args = deployOptions?.arguments ?? [];
const contractOptions = { ...this.options, data };
return {
arguments: args,
send: (
options?: PayableTxOptions,
): Web3PromiEvent<
Contract<Abi>,
SendTransactionEvents<typeof DEFAULT_RETURN_FORMAT>
> => {
const modifiedOptions = { ...options };
// Remove to address
// modifiedOptions.to = '0x0000000000000000000000000000000000000000';
delete modifiedOptions.to;
return this._contractMethodDeploySend(
abi as AbiFunctionFragment,
args as unknown[],
modifiedOptions,
contractOptions,
);
},
estimateGas: async <ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
options?: PayableCallOptions,
returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
) => {
const modifiedOptions = { ...options };
// Remove to address
delete modifiedOptions.to;
return this._contractMethodEstimateGas({
abi: abi as AbiFunctionFragment,
params: args as unknown[],
returnFormat,
options: modifiedOptions,
contractOptions,
});
},
encodeABI: () =>
encodeMethodABI(
abi as AbiFunctionFragment,
args as unknown[],
format({ eth: 'bytes' }, data as Bytes, DEFAULT_RETURN_FORMAT),
),
};
}
/**
* Gets past events for this contract.
*
* ```ts
* const events = await myContract.getPastEvents('MyEvent', {
* filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
* fromBlock: 0,
* toBlock: 'latest'
* });
*
* > [{
* returnValues: {
* myIndexedParam: 20,
* myOtherIndexedParam: '0x123456789...',
* myNonIndexParam: 'My String'
* },
* raw: {
* data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
* topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
* },
* event: 'MyEvent',
* signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
* logIndex: 0,
* transactionIndex: 0,
* transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
* blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
* blockNumber: 1234,
* address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
* },{
* ...
* }]
* ```
*
* @param eventName - The name of the event in the contract, or `allEvents` to get all events.
* @param filter - The filter options used to get events.
* @param returnFormat - Return format
* @returns - An array with the past event `Objects`, matching the given event name and filter.
*/
public async getPastEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
returnFormat?: ReturnFormat,
): Promise<(string | EventLog)[]>;
public async getPastEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
eventName: keyof ContractEvents<Abi> | 'allEvents',
returnFormat?: ReturnFormat,
): Promise<(string | EventLog)[]>;
public async getPastEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
filter: Omit<Filter, 'address'>,
returnFormat?: ReturnFormat,
): Promise<(string | EventLog)[]>;
public async getPastEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
eventName: keyof ContractEvents<Abi> | 'allEvents',
filter: Omit<Filter, 'address'>,
returnFormat?: ReturnFormat,
): Promise<(string | EventLog)[]>;
public async getPastEvents<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
param1?: keyof ContractEvents<Abi> | 'allEvents' | Omit<Filter, 'address'> | ReturnFormat,
param2?: Omit<Filter, 'address'> | ReturnFormat,
param3?: ReturnFormat,
): Promise<(string | EventLog)[]> {
const eventName = typeof param1 === 'string' ? param1 : 'allEvents';
const filter =
// eslint-disable-next-line no-nested-ternary
typeof param1 !== 'string' && !isDataFormat(param1)
? param1
: !isDataFormat(param2)
? param2
: {};
// eslint-disable-next-line no-nested-ternary
const returnFormat = isDataFormat(param1)
? param1
: isDataFormat(param2)
? param2
: param3 ?? DEFAULT_RETURN_FORMAT;
const abi =
eventName === 'allEvents'
? ALL_EVENTS_ABI
: (this._jsonInterface.find(
j => 'name' in j && j.name === eventName,
) as AbiEventFragment & { signature: string });
if (!abi) {
throw new Web3ContractError(`Event ${eventName} not found.`);
}
const { fromBlock, toBlock, topics, address } = encodeEventABI(
this.options,
abi,
filter ?? {},
returnFormat,
);
const logs = await getLogs(this, { fromBlock, toBlock, topics, address }, returnFormat);
return logs.map(log =>
typeof log === 'string'
? log
: decodeEventABI(abi, log as LogsInput, this._jsonInterface, returnFormat),
);
}
private _parseAndSetAddress(value?: Address, returnFormat: DataFormat = DEFAULT_RETURN_FORMAT) {
this._address = value
? toChecksumAddress(format({ eth: 'address' }, value, returnFormat))
: value;
}
private _parseAndSetJsonInterface(
abis: ContractAbi,
returnFormat: DataFormat = DEFAULT_RETURN_FORMAT,
) {
this._functions = {};
this._methods = {} as ContractMethodsInterface<Abi>;
this._events = {} as ContractEventsInterface<Abi>;
let result: ContractAbi = [];
const functionsAbi = abis.filter(abi => abi.type !== 'error');
const errorsAbi = abis.filter(abi =>
isAbiErrorFragment(abi),
) as unknown as AbiErrorFragment[];
for (const a of functionsAbi) {
const abi: Mutable<AbiFragment & { signature: HexString }> = {
...a,
signature: '',
};
if (isAbiFunctionFragment(abi)) {
const methodName = jsonInterfaceMethodToString(abi);
const methodSignature = encodeFunctionSignature(methodName);
abi.signature = methodSignature;
// make constant and payable backwards compatible
abi.constant =
abi.stateMutability === 'view' ??
abi.stateMutability === 'pure' ??
abi.constant;
abi.payable = abi.stateMutability === 'payable' ?? abi.payable;
const contractMethod = this._createContractMethod(abi, errorsAbi);
this._overloadedMethodAbis.set(abi.name, [
...(this._overloadedMethodAbis.get(abi.name) ?? []),
abi,
]);
if (methodName in this._functions) {
this._functions[methodName] = {
signature: methodSignature,
method: contractMethod,
};
} else {
this._functions[methodName] = {
signature: methodSignature,
method: contractMethod,
};
}
// We don't know a particular type of the Abi method so can't type check
this._methods[abi.name as keyof ContractMethodsInterface<Abi>] = this._functions[
methodName
].method as never;
// We don't know a particular type of the Abi method so can't type check
this._methods[methodName as keyof ContractMethodsInterface<Abi>] = this._functions[
methodName
].method as never;
// We don't know a particular type of the Abi method so can't type check
this._methods[methodSignature as keyof ContractMethodsInterface<Abi>] = this
._functions[methodName].method as never;
} else if (isAbiEventFragment(abi)) {
const eventName = jsonInterfaceMethodToString(abi);
const eventSignature = encodeEventSignature(eventName);
const event = this._createContractEvent(abi, returnFormat);
abi.signature = eventSignature;
if (!(eventName in this._events) || abi.name === 'bound') {
// It's a private type and we don't want to expose it and no need to check
this._events[eventName as keyof ContractEventsInterface<Abi>] = event as never;
}
// It's a private type and we don't want to expose it and no need to check
this._events[abi.name as keyof ContractEventsInterface<Abi>] = event as never;
// It's a private type and we don't want to expose it and no need to check
this._events[eventSignature as keyof ContractEventsInterface<Abi>] = event as never;
}
this._events.allEvents = this._createContractEvent(ALL_EVENTS_ABI, returnFormat);
result = [...result, abi];
}
this._jsonInterface = [...result] as unknown as ContractAbiWithSignature;
}
// eslint-disable-next-line class-methods-use-this
private _getAbiParams(abi: AbiFunctionFragment, params: unknown[]): Array<unknown> {
try {
return validatorUtils.transformJsonDataToAbiFormat(abi.inputs ?? [], params);
} catch (error) {
throw new Web3ContractError(
`Invalid parameters for method ${abi.name}: ${(error as Error).message}`,
);
}
}
private _createContractMethod<T extends AbiFunctionFragment, E extends AbiErrorFragment>(
abi: T,
errorsAbis: E[],
): ContractBoundMethod<T> {
return (...params: unknown[]) => {
let abiParams!: Array<unknown>;
const abis = this._overloadedMethodAbis.get(abi.name) ?? [];
let methodAbi: AbiFunctionFragment = abis[0];
const arrayOfAbis: AbiFunctionFragment[] = abis.filter(
_abi => (_abi.inputs ?? []).length === params.length,
);
if (abis.length === 1 || arrayOfAbis.length === 0) {
abiParams = this._getAbiParams(methodAbi, params);
validator.validate(abi.inputs ?? [], abiParams);
} else {
const errors: Web3ValidationErrorObject[] = [];