-
-
Notifications
You must be signed in to change notification settings - Fork 585
/
getContract.ts
1171 lines (1142 loc) · 40.6 KB
/
getContract.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
import type {
Abi,
AbiEvent,
AbiFunction,
AbiParametersToPrimitiveTypes,
Address,
ExtractAbiEvent,
ExtractAbiEventNames,
ExtractAbiFunction,
ExtractAbiFunctionNames,
} from 'abitype'
import type { Account } from '../accounts/types.js'
import type { Client } from '../clients/createClient.js'
import type { Transport } from '../clients/transports/createTransport.js'
import type { Chain } from '../types/chain.js'
import type {
AbiEventParametersToPrimitiveTypes,
ContractEventName,
ContractFunctionArgs,
ContractFunctionName,
MaybeExtractEventArgsFromAbi,
} from '../types/contract.js'
import type {
IsNarrowable,
IsNever,
IsUndefined,
Or,
Prettify,
UnionOmit,
} from '../types/utils.js'
import type { ErrorType } from '../errors/utils.js'
import { getAction } from '../utils/getAction.js'
import {
type CreateContractEventFilterParameters,
type CreateContractEventFilterReturnType,
createContractEventFilter,
} from './public/createContractEventFilter.js'
import {
type EstimateContractGasParameters,
type EstimateContractGasReturnType,
estimateContractGas,
} from './public/estimateContractGas.js'
import {
type GetContractEventsParameters,
type GetContractEventsReturnType,
getContractEvents,
} from './public/getContractEvents.js'
import {
type ReadContractParameters,
type ReadContractReturnType,
readContract,
} from './public/readContract.js'
import {
type SimulateContractParameters,
type SimulateContractReturnType,
simulateContract,
} from './public/simulateContract.js'
import {
type WatchContractEventParameters,
type WatchContractEventReturnType,
watchContractEvent,
} from './public/watchContractEvent.js'
import {
type WriteContractParameters,
type WriteContractReturnType,
writeContract,
} from './wallet/writeContract.js'
type KeyedClient<
TTransport extends Transport = Transport,
TChain extends Chain | undefined = Chain | undefined,
TAccount extends Account | undefined = Account | undefined,
> =
| {
public?: Client<TTransport, TChain>
wallet: Client<TTransport, TChain, TAccount>
}
| {
public: Client<TTransport, TChain>
wallet?: Client<TTransport, TChain, TAccount>
}
export type GetContractParameters<
TTransport extends Transport = Transport,
TChain extends Chain | undefined = Chain | undefined,
TAccount extends Account | undefined = Account | undefined,
TAbi extends Abi | readonly unknown[] = Abi,
TClient extends
| Client<TTransport, TChain, TAccount>
| KeyedClient<TTransport, TChain, TAccount> =
| Client<TTransport, TChain, TAccount>
| KeyedClient<TTransport, TChain, TAccount>,
TAddress extends Address = Address,
> = {
/** Contract ABI */
abi: TAbi
/** Contract address */
address: TAddress
/** The Client.
*
* If you pass in a [`publicClient`](https://viem.sh/docs/clients/public), the following methods are available:
*
* - [`createEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)
* - [`estimateGas`](https://viem.sh/docs/contract/estimateContractGas)
* - [`getEvents`](https://viem.sh/docs/contract/getContractEvents)
* - [`read`](https://viem.sh/docs/contract/readContract)
* - [`simulate`](https://viem.sh/docs/contract/simulateContract)
* - [`watchEvent`](https://viem.sh/docs/contract/watchContractEvent)
*
* If you pass in a [`walletClient`](https://viem.sh/docs/clients/wallet), the following methods are available:
*
* - [`estimateGas`](https://viem.sh/docs/contract/estimateContractGas)
* - [`write`](https://viem.sh/docs/contract/writeContract)
*/
client: TClient
}
export type GetContractReturnType<
TAbi extends Abi | readonly unknown[] = Abi,
TClient extends Client | KeyedClient = Client | KeyedClient,
TAddress extends Address = Address,
_EventNames extends string = TAbi extends Abi
? Abi extends TAbi
? string
: ExtractAbiEventNames<TAbi>
: string,
_ReadFunctionNames extends string = TAbi extends Abi
? Abi extends TAbi
? string
: ExtractAbiFunctionNames<TAbi, 'pure' | 'view'>
: string,
_WriteFunctionNames extends string = TAbi extends Abi
? Abi extends TAbi
? string
: ExtractAbiFunctionNames<TAbi, 'nonpayable' | 'payable'>
: string,
_Narrowable extends boolean = IsNarrowable<TAbi, Abi>,
_PublicClient extends Client | unknown = TClient extends {
public: Client
}
? TClient['public']
: TClient,
_WalletClient extends Client | unknown = TClient extends {
wallet: Client
}
? TClient['wallet']
: TClient,
> = Prettify<
Prettify<
(_PublicClient extends Client
? (IsNever<_ReadFunctionNames> extends true
? unknown
: {
/**
* Calls a read-only function on a contract, and returns the response.
*
* A "read-only" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.
*
* Internally, `read` uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi([
* 'function balanceOf(address owner) view returns (uint256)',
* ]),
* client: publicClient,
* })
* const result = await contract.read.balanceOf(['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'])
* // 424122n
*/
read: {
[functionName in _ReadFunctionNames]: GetReadFunction<
_Narrowable,
TAbi,
functionName extends ContractFunctionName<
TAbi,
'pure' | 'view'
>
? functionName
: never
>
}
}) &
(IsNever<_WriteFunctionNames> extends true
? unknown
: {
/**
* Estimates the gas necessary to complete a transaction without submitting it to the network.
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint() public']),
* client: publicClient,
* })
* const gas = await contract.estimateGas.mint({
* account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
* })
*/
estimateGas: {
[functionName in _WriteFunctionNames]: GetEstimateFunction<
_Narrowable,
_PublicClient['chain'],
undefined,
TAbi,
functionName extends ContractFunctionName<
TAbi,
'nonpayable' | 'payable'
>
? functionName
: never
>
}
/**
* Simulates/validates a contract interaction. This is useful for retrieving return data and revert reasons of contract write functions.
*
* This function does not require gas to execute and does not change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract), but also supports contract write functions.
*
* Internally, `simulate` uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint() public']),
* client: publicClient,
* })
* const result = await contract.simulate.mint({
* account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
* })
*/
simulate: {
[functionName in _WriteFunctionNames]: GetSimulateFunction<
_Narrowable,
_PublicClient['chain'],
_WalletClient extends Client
? _WalletClient['account']
: _PublicClient['account'],
TAbi,
functionName extends ContractFunctionName<
TAbi,
'nonpayable' | 'payable'
>
? functionName
: never
>
}
}) &
(IsNever<_EventNames> extends true
? unknown
: {
/**
* Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),
* client: publicClient,
* })
* const filter = await contract.createEventFilter.Transfer()
*/
createEventFilter: {
[EventName in _EventNames]: GetEventFilter<
_Narrowable,
TAbi,
EventName extends ContractEventName<TAbi>
? EventName
: never
>
}
/**
* Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),
* client: publicClient,
* })
* const filter = await contract.createEventFilter.Transfer()
*/
getEvents: {
[EventName in _EventNames]: GetEventsFunction<
_Narrowable,
TAbi,
EventName extends ContractEventName<TAbi>
? EventName
: never
>
}
/**
* Watches and returns emitted contract event logs.
*
* This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).
*
* `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),
* client: publicClient,
* })
* const filter = await contract.createEventFilter.Transfer()
* const unwatch = contract.watchEvent.Transfer(
* { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },
* { onLogs: (logs) => console.log(logs) },
* )
*/
watchEvent: {
[EventName in _EventNames]: GetWatchEvent<
_Narrowable,
TAbi,
EventName extends ContractEventName<TAbi>
? EventName
: never
>
}
})
: unknown) &
(_WalletClient extends Client
? IsNever<_WriteFunctionNames> extends true
? unknown
: {
/**
* Estimates the gas necessary to complete a transaction without submitting it to the network.
*
* @example
* import { createWalletClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint() public']),
* client: walletClient,
* })
* const gas = await contract.estimateGas.mint({
* account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',
* })
*/
estimateGas: {
[functionName in _WriteFunctionNames]: GetEstimateFunction<
_Narrowable,
_WalletClient['chain'],
_WalletClient['account'],
TAbi,
functionName extends ContractFunctionName<
TAbi,
'nonpayable' | 'payable'
>
? functionName
: never
>
}
/**
* Executes a write function on a contract.
*
* A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a [Transaction](https://viem.sh/docs/glossary/terms) is needed to be broadcast in order to change the state.
*
* Internally, `write` uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).
*
* __Warning: The `write` internally sends a transaction – it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to [simulate the contract write with `contract.simulate`](https://viem.sh/docs/contract/writeContract#usage) before you execute it.__
*
* @example
* import { createWalletClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const walletClient = createWalletClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),
* client: walletClient,
* })
* const hash = await contract.write.min([69420], {
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* })
*/
write: {
[functionName in _WriteFunctionNames]: GetWriteFunction<
_Narrowable,
_WalletClient['chain'],
_WalletClient['account'],
TAbi,
functionName extends ContractFunctionName<
TAbi,
'nonpayable' | 'payable'
>
? functionName
: never
>
}
}
: unknown)
> & { address: TAddress; abi: TAbi }
>
export type GetContractErrorType = ErrorType
/**
* Gets type-safe interface for performing contract-related actions with a specific `abi` and `address`.
*
* - Docs https://viem.sh/docs/contract/getContract
*
* Using Contract Instances can make it easier to work with contracts if you don't want to pass the `abi` and `address` properites every time you perform contract actions, e.g. [`readContract`](https://viem.sh/docs/contract/readContract), [`writeContract`](https://viem.sh/docs/contract/writeContract), [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas), etc.
*
* @example
* import { createPublicClient, getContract, http, parseAbi } from 'viem'
* import { mainnet } from 'viem/chains'
*
* const publicClient = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const contract = getContract({
* address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',
* abi: parseAbi([
* 'function balanceOf(address owner) view returns (uint256)',
* 'function ownerOf(uint256 tokenId) view returns (address)',
* 'function totalSupply() view returns (uint256)',
* ]),
* client: publicClient,
* })
*/
export function getContract<
TTransport extends Transport,
TAddress extends Address,
const TAbi extends Abi | readonly unknown[],
const TClient extends
| Client<TTransport, TChain, TAccount>
| KeyedClient<TTransport, TChain, TAccount>,
TChain extends Chain | undefined = Chain | undefined,
TAccount extends Account | undefined = Account | undefined,
>({
abi,
address,
client: client_,
}: GetContractParameters<
TTransport,
TChain,
TAccount,
TAbi,
TClient,
TAddress
>): GetContractReturnType<TAbi, TClient, TAddress> {
const client = client_ as
| Client<TTransport, TChain, TAccount>
| KeyedClient<TTransport, TChain, TAccount>
const [publicClient, walletClient] = (() => {
if (!client) return [undefined, undefined]
if ('public' in client && 'wallet' in client)
return [client.public as Client, client.wallet as Client]
if ('public' in client) return [client.public as Client, undefined]
if ('wallet' in client) return [undefined, client.wallet as Client]
return [client, client]
})()
const hasPublicClient = publicClient !== undefined && publicClient !== null
const hasWalletClient = walletClient !== undefined && walletClient !== null
const contract: {
[_ in
| 'abi'
| 'address'
| 'createEventFilter'
| 'estimateGas'
| 'getEvents'
| 'read'
| 'simulate'
| 'watchEvent'
| 'write']?: unknown
} = {}
let hasReadFunction = false
let hasWriteFunction = false
let hasEvent = false
for (const item of abi as Abi) {
if (item.type === 'function')
if (item.stateMutability === 'view' || item.stateMutability === 'pure')
hasReadFunction = true
else hasWriteFunction = true
else if (item.type === 'event') hasEvent = true
// Exit early if all flags are `true`
if (hasReadFunction && hasWriteFunction && hasEvent) break
}
if (hasPublicClient) {
if (hasReadFunction)
contract.read = new Proxy(
{},
{
get(_, functionName: string) {
return (
...parameters: [
args?: readonly unknown[] | undefined,
options?: UnionOmit<
ReadContractParameters,
'abi' | 'address' | 'functionName' | 'args'
>,
]
) => {
const { args, options } = getFunctionParameters(parameters)
return getAction(
publicClient,
readContract,
'readContract',
)({
abi,
address,
functionName,
args,
...options,
} as ReadContractParameters)
}
},
},
)
if (hasWriteFunction)
contract.simulate = new Proxy(
{},
{
get(_, functionName: string) {
return (
...parameters: [
args?: readonly unknown[],
options?: UnionOmit<
SimulateContractParameters,
'abi' | 'address' | 'functionName' | 'args'
>,
]
) => {
const { args, options } = getFunctionParameters(parameters)
return getAction(
publicClient,
simulateContract,
'simulateContract',
)({
abi,
address,
functionName,
args,
...options,
} as SimulateContractParameters)
}
},
},
)
if (hasEvent) {
contract.createEventFilter = new Proxy(
{},
{
get(_, eventName: string) {
return (
...parameters: [
args?: readonly unknown[] | object,
options?: Omit<
CreateContractEventFilterParameters,
'abi' | 'address' | 'eventName' | 'args'
>,
]
) => {
const abiEvent = (abi as readonly AbiEvent[]).find(
(x: AbiEvent) => x.type === 'event' && x.name === eventName,
)
const { args, options } = getEventParameters(
parameters,
abiEvent!,
)
return getAction(
publicClient,
createContractEventFilter,
'createContractEventFilter',
)({
abi,
address,
eventName,
args,
...options,
} as CreateContractEventFilterParameters)
}
},
},
)
contract.getEvents = new Proxy(
{},
{
get(_, eventName: string) {
return (
...parameters: [
args?: readonly unknown[] | object,
options?: Omit<
GetContractEventsParameters,
'abi' | 'address' | 'eventName'
>,
]
) => {
const abiEvent = (abi as readonly AbiEvent[]).find(
(x: AbiEvent) => x.type === 'event' && x.name === eventName,
)
const { args, options } = getEventParameters(
parameters,
abiEvent!,
)
return getAction(
publicClient,
getContractEvents,
'getContractEvents',
)({
abi,
address,
eventName,
args,
...options,
} as unknown as GetContractEventsParameters)
}
},
},
)
contract.watchEvent = new Proxy(
{},
{
get(_, eventName: string) {
return (
...parameters: [
args?: readonly unknown[] | object,
options?: Omit<
WatchContractEventParameters,
'abi' | 'address' | 'eventName'
>,
]
) => {
const abiEvent = (abi as readonly AbiEvent[]).find(
(x: AbiEvent) => x.type === 'event' && x.name === eventName,
)
const { args, options } = getEventParameters(
parameters,
abiEvent!,
)
return getAction(
publicClient,
watchContractEvent,
'watchContractEvent',
)({
abi,
address,
eventName,
args,
...options,
} as unknown as WatchContractEventParameters)
}
},
},
)
}
}
if (hasWalletClient) {
if (hasWriteFunction)
contract.write = new Proxy(
{},
{
get(_, functionName: string) {
return (
...parameters: [
args?: readonly unknown[],
options?: UnionOmit<
WriteContractParameters,
'abi' | 'address' | 'functionName' | 'args'
>,
]
) => {
const { args, options } = getFunctionParameters(parameters)
return getAction(
walletClient,
writeContract,
'writeContract',
)({
abi,
address,
functionName,
args,
...(options as any),
})
}
},
},
)
}
if (hasPublicClient || hasWalletClient)
if (hasWriteFunction)
contract.estimateGas = new Proxy(
{},
{
get(_, functionName: string) {
return (
...parameters: [
args?: readonly unknown[],
options?: UnionOmit<
EstimateContractGasParameters,
'abi' | 'address' | 'functionName' | 'args'
>,
]
) => {
const { args, options } = getFunctionParameters(parameters)
const client = (publicClient ?? walletClient)!
return getAction(
client,
estimateContractGas,
'estimateContractGas',
)({
abi,
address,
functionName,
args,
...options,
account:
(options as EstimateContractGasParameters).account ??
(walletClient as unknown as Client).account,
} as any)
}
},
},
)
contract.address = address
contract.abi = abi
return contract as unknown as GetContractReturnType<TAbi, TClient, TAddress>
}
/**
* @internal exporting for testing only
*/
export function getFunctionParameters(
values: [args?: readonly unknown[], options?: object],
) {
const hasArgs = values.length && Array.isArray(values[0])
const args = hasArgs ? values[0]! : []
const options = (hasArgs ? values[1] : values[0]) ?? {}
return { args, options }
}
/**
* @internal exporting for testing only
*/
export function getEventParameters(
values: [args?: object | unknown[], options?: object],
abiEvent: AbiEvent,
) {
let hasArgs = false
// If first item is array, must be `args`
if (Array.isArray(values[0])) hasArgs = true
// Check if first item is `args` or `options`
else if (values.length === 1) {
// if event has indexed inputs, must have `args`
hasArgs = abiEvent.inputs.some((x) => x.indexed)
// If there are two items in array, must have `args`
} else if (values.length === 2) {
hasArgs = true
}
const args = hasArgs ? values[0]! : undefined
const options = (hasArgs ? values[1] : values[0]) ?? {}
return { args, options }
}
type GetReadFunction<
Narrowable extends boolean,
TAbi extends Abi | readonly unknown[],
TFunctionName extends ContractFunctionName<TAbi, 'pure' | 'view'>,
TArgs extends ContractFunctionArgs<
TAbi,
'pure' | 'view',
TFunctionName
> = ContractFunctionArgs<TAbi, 'pure' | 'view', TFunctionName>,
TAbiFunction extends AbiFunction = TAbi extends Abi
? ExtractAbiFunction<TAbi, TFunctionName>
: AbiFunction,
Args = AbiParametersToPrimitiveTypes<TAbiFunction['inputs']>,
Options = Prettify<
UnionOmit<
ReadContractParameters<TAbi, TFunctionName, TArgs>,
'abi' | 'address' | 'args' | 'functionName'
>
>,
> = Narrowable extends true
? (
...parameters: Args extends readonly []
? [options?: Options]
: [args: Args, options?: Options]
) => Promise<ReadContractReturnType<TAbi, TFunctionName, TArgs>>
: (
...parameters:
| [options?: Options]
| [args: readonly unknown[], options?: Options]
) => Promise<ReadContractReturnType>
type GetEstimateFunction<
Narrowable extends boolean,
TChain extends Chain | undefined,
TAccount extends Account | undefined,
TAbi extends Abi | readonly unknown[],
TFunctionName extends ContractFunctionName<TAbi, 'nonpayable' | 'payable'>,
TArgs extends ContractFunctionArgs<
TAbi,
'nonpayable' | 'payable',
TFunctionName
> = ContractFunctionArgs<TAbi, 'nonpayable' | 'payable', TFunctionName>,
TAbiFunction extends AbiFunction = TAbi extends Abi
? ExtractAbiFunction<TAbi, TFunctionName>
: AbiFunction,
Args = AbiParametersToPrimitiveTypes<TAbiFunction['inputs']>,
Options = Prettify<
UnionOmit<
EstimateContractGasParameters<TAbi, TFunctionName, TArgs, TChain>,
'abi' | 'address' | 'args' | 'functionName'
>
>,
// For making `options` parameter required if `TAccount`
IsOptionsRequired = IsUndefined<TAccount>,
> = Narrowable extends true
? (
...parameters: Args extends readonly []
? IsOptionsRequired extends true
? [options: Options]
: [options?: Options]
: [
args: Args,
...parameters: IsOptionsRequired extends true
? [options: Options]
: [options?: Options],
]
) => Promise<EstimateContractGasReturnType>
: (
...parameters:
| (IsOptionsRequired extends true
? [options: Options]
: [options?: Options])
| [
args: readonly unknown[],
...parameters: IsOptionsRequired extends true
? [options: Options]
: [options?: Options],
]
) => Promise<EstimateContractGasReturnType>
type GetSimulateFunction<
Narrowable extends boolean,
TChain extends Chain | undefined,
TAccount extends Account | undefined,
TAbi extends Abi | readonly unknown[],
TFunctionName extends ContractFunctionName<TAbi, 'nonpayable' | 'payable'>,
TArgs extends ContractFunctionArgs<
TAbi,
'nonpayable' | 'payable',
TFunctionName
> = ContractFunctionArgs<TAbi, 'nonpayable' | 'payable', TFunctionName>,
TAbiFunction extends AbiFunction = TAbi extends Abi
? ExtractAbiFunction<TAbi, TFunctionName>
: AbiFunction,
Args = AbiParametersToPrimitiveTypes<TAbiFunction['inputs']>,
> = Narrowable extends true
? <
TChainOverride extends Chain | undefined,
TAccountOverride extends Account | Address | undefined = undefined,
>(
...parameters: Args extends readonly []
? [
options?: Omit<
SimulateContractParameters<
TAbi,
TFunctionName,
TArgs,
TChain,
TChainOverride,
TAccountOverride
>,
'abi' | 'address' | 'args' | 'functionName'
>,
]
: [
args: Args,
options?: Omit<
SimulateContractParameters<
TAbi,
TFunctionName,
TArgs,
TChain,
TChainOverride,
TAccountOverride
>,
'abi' | 'address' | 'args' | 'functionName'
>,
]
) => Promise<
SimulateContractReturnType<
TAbi,
TFunctionName,
TArgs,
TChain,
TAccount,
TChainOverride,
TAccountOverride
>
>
: <
TChainOverride extends Chain | undefined,
TAccountOverride extends Account | Address | undefined = undefined,
>(
...parameters:
| [
options?: Omit<
SimulateContractParameters<
TAbi,
TFunctionName,
TArgs,
TChain,
TChainOverride,
TAccountOverride
>,
'abi' | 'address' | 'args' | 'functionName'
>,
]
| [
args: readonly unknown[],
options?: Omit<
SimulateContractParameters<
TAbi,
TFunctionName,
TArgs,
TChain,
TChainOverride,
TAccountOverride
>,
'abi' | 'address' | 'args' | 'functionName'
>,
]
) => Promise<SimulateContractReturnType>
type GetWriteFunction<
Narrowable extends boolean,
TChain extends Chain | undefined,
TAccount extends Account | undefined,
TAbi extends Abi | readonly unknown[],
TFunctionName extends ContractFunctionName<TAbi, 'nonpayable' | 'payable'>,
TArgs extends ContractFunctionArgs<