-
Notifications
You must be signed in to change notification settings - Fork 306
/
ConnectionReadonlyAPI.ts
862 lines (749 loc) · 30.7 KB
/
ConnectionReadonlyAPI.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
import { first, omit, toNumber } from 'lodash-es'
import * as web3_utils from /* webpackDefer: true */ 'web3-utils'
import type { Account, ECKeyIdentifier, Proof, UpdatableWallet, Wallet } from '@masknet/shared-base'
import {
AddressType,
SchemaType,
type ChainId,
type Web3Provider,
type Transaction,
type TransactionDetailed,
type TransactionReceipt,
type Block,
EthereumMethodType,
AccountTransaction,
isNativeTokenAddress,
type TransactionSignature,
type ProviderType,
type Signature,
type UserOperation,
type Web3,
isValidAddress,
isEmptyHex,
getTransactionStatusType,
parseStringOrBytes32,
createERC20Token,
isCryptoPunksContractAddress,
getEthereumConstant,
getTokenConstant,
createAccount,
type NetworkType,
} from '@masknet/web3-shared-evm'
import {
type FungibleToken,
type NonFungibleCollection,
type NonFungibleToken,
type NonFungibleTokenContract,
type NonFungibleTokenMetadata,
type TransactionStatusType,
isSameAddress,
createNonFungibleToken,
resolveCrossOriginURL,
resolveIPFS_URL,
createNonFungibleTokenMetadata,
createNonFungibleTokenContract,
createNonFungibleTokenCollection,
isGreaterThan,
} from '@masknet/web3-shared-base'
import { queryClient } from '@masknet/shared-base-ui'
import { EVMRequestReadonlyAPI } from './RequestReadonlyAPI.js'
import { EVMContractReadonlyAPI } from './ContractReadonlyAPI.js'
import { ConnectionOptionsReadonlyAPI } from './ConnectionOptionsReadonlyAPI.js'
import type { BaseConnection } from '../../Base/apis/Connection.js'
import { fetchJSON } from '../../../helpers/fetchJSON.js'
import type { EVMConnectionOptions } from '../types/index.js'
import type { BaseConnectionOptions } from '../../../entry-types.js'
import { EVMChainResolver } from './ResolverAPI.js'
import type { ConnectionOptionsProvider } from '../../Base/apis/ConnectionOptions.js'
const EMPTY_STRING = Promise.resolve('')
const ZERO = Promise.resolve(0)
interface ERC721Metadata {
name: string
description: string
image: string
}
interface ERC1155Metadata {
name: string
decimals: number
description: string
image: string
}
export class EVMConnectionReadonlyAPI
implements
BaseConnection<
ChainId,
AddressType,
SchemaType,
ProviderType,
Signature,
UserOperation,
Transaction,
TransactionReceipt,
TransactionDetailed,
TransactionSignature,
Block,
Web3,
Web3Provider
>
{
static Default = new EVMConnectionReadonlyAPI()
constructor(protected options?: EVMConnectionOptions) {
this.Contract = new EVMContractReadonlyAPI(this.options)
this.Request = new EVMRequestReadonlyAPI(this.options)
this.ConnectionOptions = new ConnectionOptionsReadonlyAPI(this.options)
}
protected Request
protected Contract
protected ConnectionOptions: ConnectionOptionsProvider<ChainId, ProviderType, NetworkType, Transaction>
getWeb3(initial?: EVMConnectionOptions) {
return this.Request.getWeb3(initial)
}
getWeb3Provider(initial?: EVMConnectionOptions) {
return this.Request.getWeb3Provider(initial)
}
async connect(initial?: EVMConnectionOptions): Promise<Account<ChainId>> {
throw new Error('Method not implemented.')
}
async disconnect(initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
getWallets(initial?: EVMConnectionOptions): Promise<Wallet[]> {
return this.Request.request<Wallet[]>(
{
method: EthereumMethodType.MASK_WALLETS,
params: [],
},
initial,
)
}
async addWallet(wallet: UpdatableWallet, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async updateWallet(
address: string,
wallet: Partial<UpdatableWallet>,
initial?: EVMConnectionOptions,
): Promise<void> {
throw new Error('Method not implemented.')
}
async renameWallet(address: string, name: string, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async removeWallet(address: string, password?: string | undefined, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async resetAllWallets(initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async updateWallets(wallets: Wallet[], initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async removeWallets(wallets: Wallet[], initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async approveFungibleToken(
address: string,
recipient: string,
amount: string,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async approveNonFungibleToken(
address: string,
recipient: string,
tokenId: string,
schema: SchemaType,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async approveAllNonFungibleTokens(
address: string,
recipient: string,
approved: boolean,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async transferFungibleToken(
address: string,
recipient: string,
amount: string,
memo?: string,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async transferNonFungibleToken(
address: string,
tokenId: string,
recipient: string,
amount?: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async getGasPrice(initial?: EVMConnectionOptions): Promise<string> {
return this.Request.request<string>(
{
method: EthereumMethodType.ETH_GAS_PRICE,
params: [],
},
initial,
)
}
async getAddressType(address: string, initial?: EVMConnectionOptions): Promise<AddressType | undefined> {
if (!isValidAddress(address)) return
const code = await this.getCode(address, initial)
return code === '0x' ? AddressType.ExternalOwned : AddressType.Contract
}
async getSchemaType(address: string, initial?: EVMConnectionOptions): Promise<SchemaType | undefined> {
const ERC165_INTERFACE_ID = '0x01ffc9a7'
const EIP5516_INTERFACE_ID = '0x8314f22b'
const EIP5192_INTERFACE_ID = '0xb45a3c0e'
const ERC721_INTERFACE_ID = '0x80ac58cd'
const ERC1155_INTERFACE_ID = '0xd9b67a26'
try {
const options = this.ConnectionOptions.fill(initial)
const erc165Contract = this.Contract.getERC165Contract(address, options)
const [isERC165, isERC721] = await Promise.all([
erc165Contract?.methods.supportsInterface(ERC165_INTERFACE_ID).call(),
erc165Contract?.methods.supportsInterface(ERC721_INTERFACE_ID).call(),
])
if (isERC165 && isERC721) return SchemaType.ERC721
const isERC1155 = await erc165Contract?.methods.supportsInterface(ERC1155_INTERFACE_ID).call()
if (isERC165 && isERC1155) return SchemaType.ERC1155
const [isEIP5516, isEIP5192] = await Promise.all([
erc165Contract?.methods.supportsInterface(EIP5516_INTERFACE_ID).call(),
erc165Contract?.methods.supportsInterface(EIP5192_INTERFACE_ID).call(),
])
if (isEIP5516 || isEIP5192) return SchemaType.SBT
const isERC20 = await this.getCode(address, options)
if (!isEmptyHex(isERC20)) return SchemaType.ERC20
return
} catch {
return
}
}
async getNonFungibleToken(
address: string,
tokenId: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<NonFungibleToken<ChainId, SchemaType>> {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
const allSettled = await Promise.allSettled([
this.getNonFungibleTokenMetadata(address, tokenId, schema, options),
this.getNonFungibleTokenContract(address, schema, options),
])
const [metadata, contract] = allSettled.map((x) => (x.status === 'fulfilled' ? x.value : undefined)) as [
NonFungibleTokenMetadata<ChainId>,
NonFungibleTokenContract<ChainId, SchemaType>,
]
let ownerId: string | undefined
if (actualSchema !== SchemaType.ERC1155) {
const contract = this.Contract.getERC721Contract(address, options)
try {
ownerId = await contract?.methods.ownerOf(tokenId).call()
} catch {}
} else if (options.account) {
const contract = this.Contract.getERC1155Contract(address, options)
try {
const balance = await contract?.methods.balanceOf(options.account, tokenId).call()
ownerId = balance && isGreaterThan(balance, '0') ? options.account : undefined
} catch {}
}
return createNonFungibleToken<ChainId, SchemaType>(
options.chainId,
address,
actualSchema ?? SchemaType.ERC721,
tokenId,
ownerId,
metadata,
contract,
)
}
async getNonFungibleTokenOwner(
address: string,
tokenId: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
) {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) return ''
// CRYPTOPUNKS
if (isCryptoPunksContractAddress(address)) {
const cryptoPunksContract = this.Contract.getCryptoPunksContract(address, options)
return (await cryptoPunksContract?.methods.punkIndexToAddress(tokenId).call()) ?? ''
}
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
return (await contract?.methods.ownerOf(tokenId).call()) ?? ''
}
async getNonFungibleTokenOwnership(
address: string,
tokenId: string,
owner: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
) {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) {
const contract = this.Contract.getERC1155Contract(address, options)
// the owner has at least 1 token
return isGreaterThan((await contract?.methods.balanceOf(owner, tokenId).call()) ?? 0, 0)
}
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
return isSameAddress(await contract?.methods.ownerOf(tokenId).call(), owner)
}
async getNonFungibleTokenMetadata(
address: string,
tokenId: string | undefined,
schema?: SchemaType,
initial?: EVMConnectionOptions,
) {
const options = this.ConnectionOptions.fill(initial)
const processURI = (uri: string) => {
// e.g,
// address: 0x495f947276749ce646f68ac8c248420045cb7b5e
// token id: 33445046430196205871873533938903624085962860434195770982901962545689408831489
if (uri.startsWith('https://api.opensea.io/') && tokenId) return uri.replace('0x{id}', tokenId)
// add cors header
return resolveCrossOriginURL(resolveIPFS_URL(uri))!
}
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) {
const contract = this.Contract.getERC1155Contract(address, options)
const uri = await contract?.methods.uri(tokenId ?? '').call()
if (!uri) throw new Error('Failed to read metadata uri.')
const response = await fetchJSON<ERC1155Metadata>(processURI(uri))
return createNonFungibleTokenMetadata(
options.chainId,
response.name,
tokenId ?? '',
'',
response.description,
undefined,
resolveIPFS_URL(response.image),
resolveIPFS_URL(response.image),
)
}
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
const uri = await contract?.methods.tokenURI(tokenId ?? '').call()
if (!uri) throw new Error('Failed to read metadata uri.')
const response = await fetchJSON<ERC721Metadata>(processURI(uri))
return createNonFungibleTokenMetadata(
options.chainId,
response.name,
tokenId ?? '',
'',
response.description,
undefined,
resolveIPFS_URL(response.image),
resolveIPFS_URL(response.image),
)
}
async getNonFungibleTokenContract(
address: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<NonFungibleTokenContract<ChainId, SchemaType>> {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) {
const contractERC721 = this.Contract.getERC721Contract(address, options)
const results = await Promise.allSettled([
contractERC721?.methods.name().call() ?? EMPTY_STRING,
contractERC721?.methods.symbol().call() ?? EMPTY_STRING,
])
const [name, symbol] = results.map((result) => (result.status === 'fulfilled' ? result.value : ''))
return createNonFungibleTokenContract(
options.chainId,
SchemaType.ERC1155,
address,
name ?? 'Unknown Token',
symbol ?? 'UNKNOWN',
)
}
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
const results = await Promise.allSettled([
contract?.methods.name().call() ?? EMPTY_STRING,
contract?.methods.symbol().call() ?? EMPTY_STRING,
])
const [name, symbol] = results.map((result) => (result.status === 'fulfilled' ? result.value : ''))
return createNonFungibleTokenContract<ChainId, SchemaType.ERC721>(
options.chainId,
SchemaType.ERC721,
address,
name ?? 'Unknown Token',
symbol ?? 'UNKNOWN',
)
}
async getNonFungibleTokenCollection(
address: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<NonFungibleCollection<ChainId, SchemaType>> {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) throw new Error('Not implemented yet.')
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
const results = await Promise.allSettled([contract?.methods.name().call() ?? EMPTY_STRING])
const [name] = results.map((result) => (result.status === 'fulfilled' ? result.value : ''))
return createNonFungibleTokenCollection(options.chainId, address, name ?? 'Unknown Token', '')
}
createAccount(initial?: BaseConnectionOptions<ChainId, ProviderType, Transaction> | undefined): Account<ChainId> {
const options = this.ConnectionOptions.fill(initial)
const account = createAccount()
return {
account: account.address,
chainId: options.chainId,
privateKey: account.privateKey,
}
}
async switchChain(chainId: ChainId, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
async getNativeTokenBalance(initial?: EVMConnectionOptions): Promise<string> {
const options = this.ConnectionOptions.fill(initial)
if (!isValidAddress(options.account)) return '0'
return this.getBalance(options.account, options)
}
async getFungibleTokenBalance(
address: string,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<string> {
const options = this.ConnectionOptions.fill(initial)
// Native
if (!address || isNativeTokenAddress(address)) return this.getNativeTokenBalance(options)
// ERC20
const contract = this.Contract.getERC20Contract(address, options)
return (await contract?.methods.balanceOf(options.account).call()) ?? '0'
}
async getNonFungibleTokenBalance(
address: string,
tokenId: string | undefined,
schema?: SchemaType,
initial?: EVMConnectionOptions,
): Promise<string> {
const options = this.ConnectionOptions.fill(initial)
const actualSchema = schema ?? (await this.getSchemaType(address, options))
// ERC1155
if (actualSchema === SchemaType.ERC1155) {
const contract = this.Contract.getERC1155Contract(address, options)
return contract?.methods?.balanceOf(options.account, tokenId ?? '').call() ?? '0'
}
// ERC721
const contract = this.Contract.getERC721Contract(address, options)
return contract?.methods.balanceOf(options.account).call() ?? '0'
}
async getFungibleTokensBalance(
listOfAddress: string[],
initial?: EVMConnectionOptions,
): Promise<Record<string, string>> {
if (!listOfAddress.length) return {}
const options = this.ConnectionOptions.fill(initial)
const NATIVE_TOKEN_ADDRESS = getTokenConstant(options.chainId, 'NATIVE_TOKEN_ADDRESS')
const entities: Array<[string, string]> = []
if (listOfAddress.some(isNativeTokenAddress)) {
entities.push([NATIVE_TOKEN_ADDRESS ?? '', await this.getBalance(options.account, options)])
}
const BALANCE_CHECKER_ADDRESS = getEthereumConstant(options.chainId, 'BALANCE_CHECKER_ADDRESS')
if (!BALANCE_CHECKER_ADDRESS) {
if (process.env.NODE_ENV === 'development') {
console.error(
`BALANCE_CHECKER_ADDRESS for chain ${options.chainId} is not provided, do you forget to update packages/web3-constants/evm/ethereum.json ?`,
BALANCE_CHECKER_ADDRESS,
)
}
return Object.fromEntries(entities)
}
const listOfNonNativeAddress = listOfAddress.filter((x) => !isNativeTokenAddress(x))
if (listOfNonNativeAddress.length) {
const contract = this.Contract.getBalanceCheckerContract(BALANCE_CHECKER_ADDRESS, options)
const balances = await contract?.methods.balances([options.account], listOfNonNativeAddress).call({
// cannot check the sender's balance in the same contract
from: undefined,
chainId: web3_utils.numberToHex(options.chainId),
})
listOfNonNativeAddress.forEach((x, i) => {
entities.push([x, balances?.[i] ?? '0'])
})
}
return Object.fromEntries(entities)
}
async getNonFungibleTokensBalance(
listOfAddress: string[],
initial?: EVMConnectionOptions,
): Promise<Record<string, string>> {
if (!listOfAddress.length) return {}
const options = this.ConnectionOptions.fill(initial)
const BALANCE_CHECKER_ADDRESS = getEthereumConstant(options.chainId, 'BALANCE_CHECKER_ADDRESS')
if (!BALANCE_CHECKER_ADDRESS) {
if (process.env.NODE_ENV === 'development') {
console.error(
`BALANCE_CHECKER_ADDRESS for chain ${options.chainId} is not provided, do you forget to update packages/web3-constants/evm/ethereum.json ?`,
BALANCE_CHECKER_ADDRESS,
)
}
return {}
}
const contract = this.Contract.getBalanceCheckerContract(BALANCE_CHECKER_ADDRESS, options)
const result = await contract?.methods.balances([options.account], listOfAddress).call({
// cannot check the sender's balance in the same contract
from: undefined,
chainId: web3_utils.numberToHex(options.chainId),
})
if (result?.length !== listOfAddress.length) return {}
return Object.fromEntries(listOfAddress.map<[string, string]>((x, i) => [x, result[i]]))
}
getNativeToken(initial?: EVMConnectionOptions): Promise<FungibleToken<ChainId, SchemaType>> {
const options = this.ConnectionOptions.fill(initial)
const token = EVMChainResolver.nativeCurrency(options.chainId)
if (!token) throw new Error('Failed to create native token.')
return Promise.resolve(token)
}
async getFungibleToken(
address: string,
initial?: EVMConnectionOptions,
): Promise<FungibleToken<ChainId, SchemaType>> {
const options = this.ConnectionOptions.fill(initial)
// Native
if (!address || isNativeTokenAddress(address)) return this.getNativeToken(options)
// ERC20
const contract = this.Contract.getERC20Contract(address, options)
const bytes32Contract = this.Contract.getERC20Bytes32Contract(address, options)
const results = await queryClient.fetchQuery({
staleTime: 600_000,
queryKey: ['fungibleToken', options.chainId, address],
queryFn: async () => {
return Promise.allSettled([
contract?.methods.name().call() ?? EMPTY_STRING,
bytes32Contract?.methods.name().call() ?? EMPTY_STRING,
contract?.methods.symbol().call() ?? EMPTY_STRING,
bytes32Contract?.methods.symbol().call() ?? EMPTY_STRING,
contract?.methods.decimals().call() ?? ZERO,
])
},
})
const [name, nameBytes32, symbol, symbolBytes32, decimals] = results.map((result) =>
result.status === 'fulfilled' ? result.value : '',
) as string[]
return createERC20Token(
options.chainId,
address,
parseStringOrBytes32(name, nameBytes32, 'Unknown Token'),
parseStringOrBytes32(symbol, symbolBytes32, 'UNKNOWN'),
typeof decimals === 'string' ? Number.parseInt(decimals ? decimals : '0', 10) : decimals,
)
}
async getAccount(initial?: EVMConnectionOptions) {
const options = this.ConnectionOptions.fill(initial)
const accounts = await this.Request.request<string[]>(
{
method: EthereumMethodType.ETH_ACCOUNTS,
params: [],
},
options,
)
return first(accounts) ?? ''
}
async getChainId(initial?: EVMConnectionOptions) {
const options = this.ConnectionOptions.fill(initial)
const chainId = await this.Request.request<string>(
{
method: EthereumMethodType.ETH_CHAIN_ID,
params: [],
},
options,
)
return Number.parseInt(chainId, 16)
}
getBlock(noOrId: number | string, initial?: EVMConnectionOptions) {
return this.Request.request<Block>(
{
method: EthereumMethodType.ETH_GET_BLOCK_BY_NUMBER,
params: [web3_utils.toHex(noOrId), false],
},
initial,
)
}
getBlockNumber(initial?: EVMConnectionOptions) {
return this.Request.request<number>(
{
method: EthereumMethodType.ETH_BLOCK_NUMBER,
params: [],
},
initial,
)
}
async getBlockTimestamp(initial?: EVMConnectionOptions): Promise<number> {
const options = this.ConnectionOptions.fill(initial)
const blockNumber = await this.getBlockNumber(options)
const block = await this.getBlock(blockNumber, options)
return Number.parseInt(block.timestamp, 16)
}
getBalance(address: string, initial?: EVMConnectionOptions) {
return this.Request.request<string>(
{
method: EthereumMethodType.ETH_GET_BALANCE,
params: [address, 'latest'],
},
initial,
)
}
getCode(address: string, initial?: EVMConnectionOptions) {
return this.Request.request<string>(
{
method: EthereumMethodType.ETH_GET_CODE,
params: [address, 'latest'],
},
initial,
)
}
async getTransaction(hash: string, initial?: EVMConnectionOptions) {
return this.Request.request<TransactionDetailed>(
{
method: EthereumMethodType.ETH_GET_TRANSACTION_BY_HASH,
params: [hash],
},
initial,
)
}
async estimateTransaction(transaction: Transaction, fallback = 21000, initial?: EVMConnectionOptions) {
try {
const options = this.ConnectionOptions.fill(initial)
return await this.Request.request<string>(
{
method: EthereumMethodType.ETH_ESTIMATE_GAS,
params: [
new AccountTransaction({
from: options.account,
chainId: options.chainId,
...transaction,
}).fill(omit(options.overrides, ['gas', 'gasPrice', 'maxPriorityFeePerGas', 'maxFeePerGas'])),
],
},
options,
)
} catch {
return web3_utils.toHex(fallback)
}
}
getTransactionReceipt(hash: string, initial?: EVMConnectionOptions) {
return this.Request.request<TransactionReceipt>(
{
method: EthereumMethodType.ETH_GET_TRANSACTION_RECEIPT,
params: [hash],
},
initial,
)
}
async getTransactionStatus(hash: string, initial?: EVMConnectionOptions): Promise<TransactionStatusType> {
const receipt = await this.getTransactionReceipt(hash, initial)
return getTransactionStatusType(receipt)
}
async getTransactionNonce(address: string, initial?: EVMConnectionOptions) {
const nonce = await this.Request.request<number | string>(
{
method: EthereumMethodType.ETH_GET_TRANSACTION_COUNT,
params: [address, 'latest'],
},
initial,
)
return toNumber(nonce)
}
signMessage(
type: 'message' | 'typedData' | Omit<string, 'message' | 'typedData'>,
message: string,
initial?: EVMConnectionOptions,
): Promise<string> {
throw new Error('Method not implemented.')
}
async verifyMessage(
type: string,
message: string,
signature: string,
initial?: EVMConnectionOptions,
): Promise<boolean> {
throw new Error('Method not implemented.')
}
async signTransaction(transaction: Transaction, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
signTransactions(transactions: Transaction[], initial?: EVMConnectionOptions): Promise<string[]> {
throw new Error('Method not implemented.')
}
supportedChainIds(initial?: EVMConnectionOptions): Promise<ChainId[]> {
throw new Error('Method not implemented.')
}
supportedEntryPoints(initial?: EVMConnectionOptions): Promise<string[]> {
throw new Error('Method not implemented.')
}
async callUserOperation(owner: string, operation: UserOperation, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
async sendUserOperation(owner: string, operation: UserOperation, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
async transfer(recipient: string, amount: string, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
async changeOwner(recipient: string, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
async fund(proof: Proof, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
async deploy(owner: string, identifier?: ECKeyIdentifier, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
callTransaction(transaction: Transaction, initial?: EVMConnectionOptions) {
const options = this.ConnectionOptions.fill(initial)
return this.Request.request<string>(
{
method: EthereumMethodType.ETH_CALL,
params: [new AccountTransaction(transaction).fill(options.overrides), 'latest'],
},
options,
)
}
async sendTransaction(transaction: Transaction, initial?: EVMConnectionOptions): Promise<string> {
throw new Error('Method not implemented.')
}
sendSignedTransaction(signature: string, initial?: EVMConnectionOptions) {
return this.Request.request<string>(
{
method: EthereumMethodType.ETH_SEND_RAW_TRANSACTION,
params: [signature],
},
initial,
)
}
async confirmTransaction(hash: string, initial?: EVMConnectionOptions): Promise<TransactionReceipt> {
throw new Error('Method not implemented.')
}
replaceTransaction(hash: string, transaction: Transaction, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
cancelTransaction(hash: string, transaction: Transaction, initial?: EVMConnectionOptions): Promise<void> {
throw new Error('Method not implemented.')
}
}
export const EVMWeb3Readonly = EVMConnectionReadonlyAPI.Default