-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
CollectibleDetectionController.ts
384 lines (355 loc) · 12.5 KB
/
CollectibleDetectionController.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
import { BaseController, BaseConfig, BaseState } from '../BaseController';
import type { NetworkState, NetworkType } from '../network/NetworkController';
import type { PreferencesState } from '../user/PreferencesController';
import { safelyExecute, timeoutFetch, toChecksumHexAddress } from '../util';
import { MAINNET } from '../constants';
import type {
CollectiblesController,
CollectiblesState,
CollectibleMetadata,
} from './CollectiblesController';
const DEFAULT_INTERVAL = 180000;
/**
* @type ApiCollectible
*
* Collectible object coming from OpenSea api
* @property token_id - The collectible identifier
* @property num_sales - Number of sales
* @property background_color - The background color to be displayed with the item
* @property image_url - URI of an image associated with this collectible
* @property image_preview_url - URI of a smaller image associated with this collectible
* @property image_thumbnail_url - URI of a thumbnail image associated with this collectible
* @property image_original_url - URI of the original image associated with this collectible
* @property animation_url - URI of a animation associated with this collectible
* @property animation_original_url - URI of the original animation associated with this collectible
* @property name - The collectible name
* @property description - The collectible description
* @property external_link - External link containing additional information
* @property assetContract - The collectible contract information object
* @property creator - The collectible owner information object
* @property lastSale - When this item was last sold
*/
export interface ApiCollectible {
token_id: string;
num_sales: number | null;
background_color: string | null;
image_url: string | null;
image_preview_url: string | null;
image_thumbnail_url: string | null;
image_original_url: string | null;
animation_url: string | null;
animation_original_url: string | null;
name: string | null;
description: string | null;
external_link: string | null;
asset_contract: ApiCollectibleContract;
creator: ApiCollectibleCreator;
last_sale: ApiCollectibleLastSale | null;
}
/**
* @type ApiCollectibleContract
*
* Collectible contract object coming from OpenSea api
* @property address - Address of the collectible contract
* @property asset_contract_type - The collectible type, it could be `semi-fungible` or `non-fungible`
* @property created_date - Creation date
* @property collection - Object containing the contract name and URI of an image associated
* @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`
* @property symbol - The collectible contract symbol
* @property total_supply - Total supply of collectibles
* @property description - The collectible contract description
* @property external_link - External link containing additional information
*/
export interface ApiCollectibleContract {
address: string;
asset_contract_type: string | null;
created_date: string | null;
schema_name: string | null;
symbol: string | null;
total_supply: string | null;
description: string | null;
external_link: string | null;
collection: {
name: string | null;
image_url?: string | null;
};
}
/**
* @type ApiCollectibleLastSale
*
* Collectible sale object coming from OpenSea api
* @property event_timestamp - Object containing a `username`
* @property total_price - URI of collectible image associated with this owner
* @property transaction - Object containing transaction_hash and block_hash
*/
export interface ApiCollectibleLastSale {
event_timestamp: string;
total_price: string;
transaction: { transaction_hash: string; block_hash: string };
}
/**
* @type ApiCollectibleCreator
*
* Collectible creator object coming from OpenSea api
* @property user - Object containing a `username`
* @property profile_img_url - URI of collectible image associated with this owner
* @property address - The owner address
*/
export interface ApiCollectibleCreator {
user: { username: string };
profile_img_url: string;
address: string;
}
/**
* @type CollectibleDetectionConfig
*
* CollectibleDetection configuration
* @property interval - Polling interval used to fetch new token rates
* @property networkType - Network type ID as per net_version
* @property selectedAddress - Vault selected address
* @property tokens - List of tokens associated with the active vault
*/
export interface CollectibleDetectionConfig extends BaseConfig {
interval: number;
networkType: NetworkType;
chainId: `0x${string}` | `${number}` | number;
selectedAddress: string;
}
/**
* Controller that passively polls on a set interval for Collectibles auto detection
*/
export class CollectibleDetectionController extends BaseController<
CollectibleDetectionConfig,
BaseState
> {
private intervalId?: NodeJS.Timeout;
private getOwnerCollectiblesApi(address: string, offset: number) {
return `https://api.opensea.io/api/v1/assets?owner=${address}&offset=${offset}&limit=50`;
}
private async getOwnerCollectibles(address: string) {
let response: Response;
let collectibles: any = [];
const openSeaApiKey = this.getOpenSeaApiKey();
try {
let offset = 0;
let pagingFinish = false;
/* istanbul ignore if */
do {
const api = this.getOwnerCollectiblesApi(address, offset);
response = await timeoutFetch(
api,
openSeaApiKey ? { headers: { 'X-API-KEY': openSeaApiKey } } : {},
15000,
);
const collectiblesArray = await response.json();
collectiblesArray.assets?.length !== 0
? (collectibles = [...collectibles, ...collectiblesArray.assets])
: (pagingFinish = true);
offset += 50;
} while (!pagingFinish);
} catch (e) {
/* istanbul ignore next */
return [];
}
return collectibles;
}
/**
* Name of this controller used during composition
*/
name = 'CollectibleDetectionController';
private getOpenSeaApiKey: () => string | undefined;
private addCollectible: CollectiblesController['addCollectible'];
private getCollectiblesState: () => CollectiblesState;
/**
* Creates a CollectibleDetectionController instance.
*
* @param options - The controller options.
* @param options.onCollectiblesStateChange - Allows subscribing to assets controller state changes.
* @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
* @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set.
* @param options.addCollectible - Add a collectible.
* @param options.getCollectiblesState - Gets the current state of the Assets controller.
* @param config - Initial options used to configure this controller.
* @param state - Initial state to set on this controller.
*/
constructor(
{
onPreferencesStateChange,
onNetworkStateChange,
getOpenSeaApiKey,
addCollectible,
getCollectiblesState,
}: {
onCollectiblesStateChange: (
listener: (collectiblesState: CollectiblesState) => void,
) => void;
onPreferencesStateChange: (
listener: (preferencesState: PreferencesState) => void,
) => void;
onNetworkStateChange: (
listener: (networkState: NetworkState) => void,
) => void;
getOpenSeaApiKey: () => string | undefined;
addCollectible: CollectiblesController['addCollectible'];
getCollectiblesState: () => CollectiblesState;
},
config?: Partial<CollectibleDetectionConfig>,
state?: Partial<BaseState>,
) {
super(config, state);
this.defaultConfig = {
interval: DEFAULT_INTERVAL,
networkType: MAINNET,
chainId: '1',
selectedAddress: '',
disabled: true,
};
this.initialize();
this.getCollectiblesState = getCollectiblesState;
onPreferencesStateChange(({ selectedAddress, useCollectibleDetection }) => {
const { selectedAddress: previouslySelectedAddress, disabled } =
this.config;
if (
selectedAddress !== previouslySelectedAddress ||
!useCollectibleDetection !== disabled
) {
this.configure({ selectedAddress, disabled: !useCollectibleDetection });
}
if (useCollectibleDetection !== undefined) {
if (useCollectibleDetection) {
this.start();
} else {
this.stop();
}
}
});
onNetworkStateChange(({ provider }) => {
this.configure({
networkType: provider.type,
chainId: provider.chainId as CollectibleDetectionConfig['chainId'],
});
});
this.getOpenSeaApiKey = getOpenSeaApiKey;
this.addCollectible = addCollectible;
}
/**
* Start polling for the currency rate.
*/
async start() {
if (!this.isMainnet() || this.disabled) {
return;
}
await this.startPolling();
}
/**
* Stop polling for the currency rate.
*/
stop() {
this.stopPolling();
}
private stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
/**
* Starts a new polling interval.
*
* @param interval - An interval on which to poll.
*/
private async startPolling(interval?: number): Promise<void> {
interval && this.configure({ interval }, false, false);
this.stopPolling();
await this.detectCollectibles();
this.intervalId = setInterval(async () => {
await this.detectCollectibles();
}, this.config.interval);
}
/**
* Checks whether network is mainnet or not.
*
* @returns Whether current network is mainnet.
*/
isMainnet = (): boolean => this.config.networkType === MAINNET;
/**
* Triggers asset ERC721 token auto detection on mainnet. Any newly detected collectibles are
* added.
*/
async detectCollectibles() {
/* istanbul ignore if */
if (!this.isMainnet() || this.disabled) {
return;
}
const { selectedAddress, chainId } = this.config;
/* istanbul ignore else */
if (!selectedAddress) {
return;
}
await safelyExecute(async () => {
const apiCollectibles = await this.getOwnerCollectibles(selectedAddress);
const addCollectiblesPromises = apiCollectibles.map(
async (collectible: ApiCollectible) => {
const {
token_id,
num_sales,
background_color,
image_url,
image_preview_url,
image_thumbnail_url,
image_original_url,
animation_url,
animation_original_url,
name,
description,
external_link,
creator,
asset_contract: { address, schema_name },
last_sale,
} = collectible;
let ignored;
/* istanbul ignore else */
const { ignoredCollectibles } = this.getCollectiblesState();
if (ignoredCollectibles.length) {
ignored = ignoredCollectibles.find((c) => {
/* istanbul ignore next */
return (
c.address === toChecksumHexAddress(address) &&
c.tokenId === token_id
);
});
}
/* istanbul ignore else */
if (!ignored) {
/* istanbul ignore next */
const collectibleMetadata: CollectibleMetadata = Object.assign(
{},
{ name },
creator && { creator },
description && { description },
image_url && { image: image_url },
num_sales && { numberOfSales: num_sales },
background_color && { backgroundColor: background_color },
image_preview_url && { imagePreview: image_preview_url },
image_thumbnail_url && { imageThumbnail: image_thumbnail_url },
image_original_url && { imageOriginal: image_original_url },
animation_url && { animation: animation_url },
animation_original_url && {
animationOriginal: animation_original_url,
},
schema_name && { standard: schema_name },
external_link && { externalLink: external_link },
last_sale && { lastSale: last_sale },
);
await this.addCollectible(address, token_id, collectibleMetadata, {
userAddress: selectedAddress,
chainId: chainId as string,
});
}
},
);
await Promise.all(addCollectiblesPromises);
});
}
}
export default CollectibleDetectionController;