forked from MetaMask/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAssetsContractController.ts
More file actions
556 lines (515 loc) · 18 KB
/
AssetsContractController.ts
File metadata and controls
556 lines (515 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import { Contract } from '@ethersproject/contracts';
import { Web3Provider } from '@ethersproject/providers';
import type { BaseConfig, BaseState } from '@metamask/base-controller';
import { BaseControllerV1 } from '@metamask/base-controller';
import { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';
import type {
NetworkClientId,
NetworkState,
NetworkController,
Provider,
} from '@metamask/network-controller';
import type { PreferencesState } from '@metamask/preferences-controller';
import type { Hex } from '@metamask/utils';
import type BN from 'bn.js';
import abiSingleCallBalancesContract from 'single-call-balance-checker-abi';
import { SupportedTokenDetectionNetworks } from './assetsUtil';
import { ERC20Standard } from './Standards/ERC20Standard';
import { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';
import { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';
/**
* Check if token detection is enabled for certain networks
*
* @param chainId - ChainID of network
* @returns Whether the current network supports token detection
*/
export const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string> = {
[SupportedTokenDetectionNetworks.mainnet]:
'0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',
[SupportedTokenDetectionNetworks.bsc]:
'0x2352c63A83f9Fd126af8676146721Fa00924d7e4',
[SupportedTokenDetectionNetworks.polygon]:
'0x2352c63A83f9Fd126af8676146721Fa00924d7e4',
[SupportedTokenDetectionNetworks.avax]:
'0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',
[SupportedTokenDetectionNetworks.aurora]:
'0x1286415D333855237f89Df27D388127181448538',
[SupportedTokenDetectionNetworks.linea_goerli]:
'0x10dAd7Ca3921471f616db788D9300DC97Db01783',
[SupportedTokenDetectionNetworks.linea_mainnet]:
'0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',
[SupportedTokenDetectionNetworks.arbitrum]:
'0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',
[SupportedTokenDetectionNetworks.optimism]:
'0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',
[SupportedTokenDetectionNetworks.base]:
'0x6AA75276052D96696134252587894ef5FFA520af',
[SupportedTokenDetectionNetworks.zksync]:
'0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',
[SupportedTokenDetectionNetworks.cronos]:
'0x768ca200f0fc702ac9ea502498c18f5eff176378',
[SupportedTokenDetectionNetworks.celo]:
'0x6aa75276052d96696134252587894ef5ffa520af',
[SupportedTokenDetectionNetworks.gnosis]:
'0x6aa75276052d96696134252587894ef5ffa520af',
[SupportedTokenDetectionNetworks.fantom]:
'0x6aa75276052d96696134252587894ef5ffa520af',
[SupportedTokenDetectionNetworks.polygon_zkevm]:
'0x6aa75276052d96696134252587894ef5ffa520af',
[SupportedTokenDetectionNetworks.moonbeam]:
'0x6aa75276052d96696134252587894ef5ffa520af',
[SupportedTokenDetectionNetworks.moonriver]:
'0x6aa75276052d96696134252587894ef5ffa520af',
};
export const MISSING_PROVIDER_ERROR =
'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';
/**
* @type AssetsContractConfig
*
* Assets Contract controller configuration
* @property provider - Provider used to create a new web3 instance
*/
// This interface was created before this ESLint rule was added.
// Convert to a `type` in a future major version.
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface AssetsContractConfig extends BaseConfig {
provider: Provider | undefined;
ipfsGateway: string;
chainId: Hex;
}
/**
* @type BalanceMap
*
* Key value object containing the balance for each tokenAddress
* @property [tokenAddress] - Address of the token
*/
// This interface was created before this ESLint rule was added.
// Convert to a `type` in a future major version.
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface BalanceMap {
[tokenAddress: string]: BN;
}
/**
* Controller that interacts with contracts on mainnet through web3
*/
export class AssetsContractController extends BaseControllerV1<
AssetsContractConfig,
BaseState
> {
private _provider?: Provider;
/**
* Name of this controller used during composition
*/
override name = 'AssetsContractController' as const;
private readonly getNetworkClientById: NetworkController['getNetworkClientById'];
/**
* Creates a AssetsContractController instance.
*
* @param options - The controller options.
* @param options.chainId - The chain ID of the current network.
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
* @param options.onNetworkDidChange - Allows subscribing to network controller networkDidChange events.
* @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
chainId: initialChainId,
onPreferencesStateChange,
onNetworkDidChange,
getNetworkClientById,
}: {
chainId: Hex;
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
onNetworkDidChange: (
listener: (networkState: NetworkState) => void,
) => void;
getNetworkClientById: NetworkController['getNetworkClientById'];
},
config?: Partial<AssetsContractConfig>,
state?: Partial<BaseState>,
) {
super(config, state);
this.defaultConfig = {
provider: undefined,
ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,
chainId: initialChainId,
};
this.initialize();
this.getNetworkClientById = getNetworkClientById;
onPreferencesStateChange(({ ipfsGateway }) => {
this.configure({ ipfsGateway });
});
onNetworkDidChange(({ selectedNetworkClientId }) => {
const selectedNetworkClient = getNetworkClientById(
selectedNetworkClientId,
);
const { chainId } = selectedNetworkClient.configuration;
if (this.config.chainId !== chainId) {
this.configure({
chainId: selectedNetworkClient.configuration.chainId,
});
}
});
}
/**
* Sets a new provider.
*
* TODO: Replace this wth a method.
*
* @property provider - Provider used to create a new underlying Web3 instance
*/
set provider(provider: Provider) {
this._provider = provider;
}
get provider() {
throw new Error('Property only used for setting');
}
/**
* Get the relevant provider instance.
*
* @param networkClientId - Network Client ID.
* @returns Web3Provider instance.
*/
getProvider(networkClientId?: NetworkClientId): Web3Provider {
const provider = networkClientId
? this.getNetworkClientById(networkClientId).provider
: this._provider;
if (provider === undefined) {
throw new Error(MISSING_PROVIDER_ERROR);
}
// @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released
return new Web3Provider(provider);
}
/**
* Get the relevant chain ID.
*
* @param networkClientId - Network Client ID used to get the provider.
* @returns Hex chain ID.
*/
getChainId(networkClientId?: NetworkClientId): Hex {
return networkClientId
? this.getNetworkClientById(networkClientId).configuration.chainId
: this.config.chainId;
}
/**
* Get a ERC20Standard instance using the relevant provider instance.
*
* @param networkClientId - Network Client ID used to get the provider.
* @returns ERC20Standard instance.
*/
getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {
const provider = this.getProvider(networkClientId);
return new ERC20Standard(provider);
}
/**
* Get a ERC721Standard instance using the relevant provider instance.
*
* @param networkClientId - Network Client ID used to get the provider.
* @returns ERC721Standard instance.
*/
getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {
const provider = this.getProvider(networkClientId);
return new ERC721Standard(provider);
}
/**
* Get a ERC1155Standard instance using the relevant provider instance.
*
* @param networkClientId - Network Client ID used to get the provider.
* @returns ERC1155Standard instance.
*/
getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {
const provider = this.getProvider(networkClientId);
return new ERC1155Standard(provider);
}
/**
* Get balance or count for current account on specific asset contract.
*
* @param address - Asset ERC20 contract address.
* @param selectedAddress - Current account public address.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to BN object containing balance for current account on specific asset contract.
*/
async getERC20BalanceOf(
address: string,
selectedAddress: string,
networkClientId?: NetworkClientId,
): Promise<BN> {
const erc20Standard = this.getERC20Standard(networkClientId);
return erc20Standard.getBalanceOf(address, selectedAddress);
}
/**
* Query for the decimals for a given ERC20 asset.
*
* @param address - ERC20 asset contract address.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'decimals'.
*/
async getERC20TokenDecimals(
address: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc20Standard = this.getERC20Standard(networkClientId);
return erc20Standard.getTokenDecimals(address);
}
/**
* Query for the name for a given ERC20 asset.
*
* @param address - ERC20 asset contract address.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'decimals'.
*/
async getERC20TokenName(
address: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc20Standard = this.getERC20Standard(networkClientId);
return erc20Standard.getTokenName(address);
}
/**
* Enumerate assets assigned to an owner.
*
* @param address - ERC721 asset contract address.
* @param selectedAddress - Current account public address.
* @param index - An NFT counter less than `balanceOf(selectedAddress)`.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.
*/
getERC721NftTokenId(
address: string,
selectedAddress: string,
index: number,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc721Standard = this.getERC721Standard(networkClientId);
return erc721Standard.getNftTokenId(address, selectedAddress, index);
}
/**
* Enumerate assets assigned to an owner.
*
* @param tokenAddress - ERC721 asset contract address.
* @param userAddress - Current account public address.
* @param tokenId - ERC721 asset identifier.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.
*/
async getTokenStandardAndDetails(
tokenAddress: string,
userAddress?: string,
tokenId?: string,
networkClientId?: NetworkClientId,
): Promise<{
standard: string;
tokenURI?: string | undefined;
symbol?: string | undefined;
name?: string | undefined;
decimals?: string | undefined;
balance?: BN | undefined;
}> {
// Asserts provider is available
this.getProvider(networkClientId);
const { ipfsGateway } = this.config;
// ERC721
try {
const erc721Standard = this.getERC721Standard(networkClientId);
return {
...(await erc721Standard.getDetails(
tokenAddress,
ipfsGateway,
tokenId,
)),
};
} catch {
// Ignore
}
// ERC1155
try {
const erc1155Standard = this.getERC1155Standard(networkClientId);
return {
...(await erc1155Standard.getDetails(
tokenAddress,
ipfsGateway,
tokenId,
)),
};
} catch {
// Ignore
}
// ERC20
try {
const erc20Standard = this.getERC20Standard(networkClientId);
return {
...(await erc20Standard.getDetails(tokenAddress, userAddress)),
};
} catch {
// Ignore
}
throw new Error('Unable to determine contract standard');
}
/**
* Query for tokenURI for a given ERC721 asset.
*
* @param address - ERC721 asset contract address.
* @param tokenId - ERC721 asset identifier.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'tokenURI'.
*/
async getERC721TokenURI(
address: string,
tokenId: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc721Standard = this.getERC721Standard(networkClientId);
return erc721Standard.getTokenURI(address, tokenId);
}
/**
* Query for name for a given asset.
*
* @param address - ERC721 or ERC20 asset contract address.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'name'.
*/
async getERC721AssetName(
address: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc721Standard = this.getERC721Standard(networkClientId);
return erc721Standard.getAssetName(address);
}
/**
* Query for symbol for a given asset.
*
* @param address - ERC721 or ERC20 asset contract address.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'symbol'.
*/
async getERC721AssetSymbol(
address: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc721Standard = this.getERC721Standard(networkClientId);
return erc721Standard.getAssetSymbol(address);
}
/**
* Query for owner for a given ERC721 asset.
*
* @param address - ERC721 asset contract address.
* @param tokenId - ERC721 asset identifier.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the owner address.
*/
async getERC721OwnerOf(
address: string,
tokenId: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc721Standard = this.getERC721Standard(networkClientId);
return erc721Standard.getOwnerOf(address, tokenId);
}
/**
* Query for tokenURI for a given asset.
*
* @param address - ERC1155 asset contract address.
* @param tokenId - ERC1155 asset identifier.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'tokenURI'.
*/
async getERC1155TokenURI(
address: string,
tokenId: string,
networkClientId?: NetworkClientId,
): Promise<string> {
const erc1155Standard = this.getERC1155Standard(networkClientId);
return erc1155Standard.getTokenURI(address, tokenId);
}
/**
* Query for balance of a given ERC 1155 token.
*
* @param userAddress - Wallet public address.
* @param nftAddress - ERC1155 asset contract address.
* @param nftId - ERC1155 asset identifier.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'balanceOf'.
*/
async getERC1155BalanceOf(
userAddress: string,
nftAddress: string,
nftId: string,
networkClientId?: NetworkClientId,
): Promise<BN> {
const erc1155Standard = this.getERC1155Standard(networkClientId);
return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);
}
/**
* Transfer single ERC1155 token.
*
* @param nftAddress - ERC1155 token address.
* @param senderAddress - ERC1155 token sender.
* @param recipientAddress - ERC1155 token recipient.
* @param nftId - ERC1155 token id.
* @param qty - Quantity of tokens to be sent.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns Promise resolving to the 'transferSingle' ERC1155 token.
*/
async transferSingleERC1155(
nftAddress: string,
senderAddress: string,
recipientAddress: string,
nftId: string,
qty: string,
networkClientId?: NetworkClientId,
): Promise<void> {
const erc1155Standard = this.getERC1155Standard(networkClientId);
return erc1155Standard.transferSingle(
nftAddress,
senderAddress,
recipientAddress,
nftId,
qty,
);
}
/**
* Get the token balance for a list of token addresses in a single call. Only non-zero balances
* are returned.
*
* @param selectedAddress - The address to check token balances for.
* @param tokensToDetect - The token addresses to detect balances for.
* @param networkClientId - Network Client ID to fetch the provider with.
* @returns The list of non-zero token balances.
*/
async getBalancesInSingleCall(
selectedAddress: string,
tokensToDetect: string[],
networkClientId?: NetworkClientId,
) {
const chainId = this.getChainId(networkClientId);
const provider = this.getProvider(networkClientId);
if (!(chainId in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {
// Only fetch balance if contract address exists
return {};
}
const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];
const contract = new Contract(
contractAddress,
abiSingleCallBalancesContract,
provider,
);
const result = await contract.balances([selectedAddress], tokensToDetect);
const nonZeroBalances: BalanceMap = {};
/* istanbul ignore else */
if (result.length > 0) {
tokensToDetect.forEach((tokenAddress, index) => {
const balance: BN = result[index];
/* istanbul ignore else */
if (String(balance) !== '0') {
nonZeroBalances[tokenAddress] = balance;
}
});
}
return nonZeroBalances;
}
}
export default AssetsContractController;