-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiscoveryAdapter.ts
More file actions
542 lines (411 loc) · 14.6 KB
/
discoveryAdapter.ts
File metadata and controls
542 lines (411 loc) · 14.6 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
import {ITokenDiscoveryAdapter} from "../../../engine-js/src/tokens/ITokenDiscoveryAdapter";
import {ITokenCollection, TokenType} from "@tokenscript/engine-js/src/tokens/ITokenCollection";
import {Web3WalletProvider} from "../components/wallet/Web3WalletProvider";
import {CHAIN_CONFIG, CHAIN_MAP, ChainID, ERC20_ABI_JSON, ERC721_ABI_JSON} from "./constants";
import {ITokenDetail} from "@tokenscript/engine-js/src/tokens/ITokenDetail";
import {dbProvider} from "../providers/databaseProvider";
import {Contract, ethers, Network, ZeroAddress} from "ethers";
import {showToastNotification} from "../components/viewers/util/showToast";
import {TokenScriptEngine} from "@tokenscript/engine-js/src/Engine";
import {getTokenUrlParams} from "../components/viewers/util/getTokenUrlParams";
const COLLECTION_CACHE_TTL = 86400;
const TOKEN_CACHE_TTL = 3600;
export const BASE_TOKEN_DISCOVERY_URL = 'https://api.token-discovery.tokenscript.org';
//'http://localhost:3000';
export class DiscoveryAdapter implements ITokenDiscoveryAdapter {
protected engine: TokenScriptEngine;
constructor(private enableStorage = true) {
}
public setEngine(engine: TokenScriptEngine){
this.engine = engine;
}
async getTokens(initialTokenDetails: ITokenCollection[], refresh: boolean): Promise<ITokenCollection[]> {
const resultTokens: ITokenCollection[] = [];
const walletAddress = await this.getCurrentWalletAddress();
const params = getTokenUrlParams(null, false);
for (const initToken of initialTokenDetails){
try {
let cachedToken = refresh ? false : await this.getCachedTokens(initToken, walletAddress);
if (!cachedToken) {
cachedToken = await this.fetchTokens(initToken, walletAddress);
await this.storeCachedTokens(cachedToken, walletAddress)
}
if (
params.tokenId &&
cachedToken.tokenType !== "erc20" &&
(
params.originId === cachedToken.originId ||
(
params.contract &&
params.contract.toLowerCase() === cachedToken.contractAddress.toLowerCase() &&
params.chain === cachedToken.chainId
)
)
){
// Add the URL specified token ID if it is not owned by the user
if (!cachedToken.tokenDetails.find((token) => token.tokenId === params.tokenId)){
cachedToken.tokenDetails.push((await this.getTokenById({...cachedToken}, params.tokenId)).tokenDetails[0]);
}
}
// Ensure originId from cache isn't used to allow correct sharing of this data across multiple tokenscripts
cachedToken.originId = initToken.originId;
resultTokens.push(cachedToken);
} catch (e){
await showToastNotification("error", "Token Discovery Error", e.message);
}
}
return resultTokens;
}
async getCurrentWalletAddress(){
return this.engine ? await (await this.engine.getWalletAdapter()).getCurrentWalletAddress() : (Web3WalletProvider.isWalletConnected() ? (await Web3WalletProvider.getWallet(true)).address : ZeroAddress);
}
async getCachedTokens(initialTokenDetails: ITokenCollection, ownerAddress: string): Promise<ITokenCollection|false> {
if (!this.enableStorage)
return false;
try {
const token = await dbProvider.tokens2.where({
chainId: initialTokenDetails.chainId,
collectionId: initialTokenDetails.contractAddress.toLowerCase(),
tokenType: initialTokenDetails.tokenType,
ownerAddress: ownerAddress.toLowerCase()
}).first();
if (token && Date.now() < token.dt + (TOKEN_CACHE_TTL * 1000))
return token.data;
} catch (e) {
console.warn(e);
}
return false;
}
async storeCachedTokens(token: ITokenCollection, ownerAddress: string){
if (!this.enableStorage)
return;
try {
await dbProvider.tokens2.put({
chainId: token.chainId,
collectionId: token.contractAddress.toLowerCase(),
tokenType: token.tokenType,
ownerAddress: ownerAddress.toLowerCase(),
data: token,
dt: Date.now()
});
} catch (e) {
console.warn(e);
}
}
async fetchTokens(token: ITokenCollection, ownerAddress: string){
if (!CHAIN_MAP[token.chainId])
throw new Error("Chain ID " + token.chainId + " is not supported for token discovery");
const chain = CHAIN_MAP[token.chainId];
let collectionData = await this.getCollectionMeta(token, chain);
token = {
...token,
...collectionData,
originId: token.originId // Must not be overridden in case two tokenscripts use the same contract
}
if (token.chainId === ChainID.HARDHAT_LOCALHOST){
token = await this.fetchOwnerTokensRpc(token, ownerAddress);
return token;
}
const tokenData = await this.fetchOwnerTokens(token, chain, ownerAddress);
if (token.tokenType !== "erc20") {
const nftTokenDetails: ITokenDetail[] = [];
for (let tokenMeta of tokenData) {
nftTokenDetails.push({
collectionDetails: token,
tokenId: tokenMeta.tokenId,
collectionId: token.contractAddress,
ownerAddress: ownerAddress,
name: tokenMeta.title,
description: tokenMeta.description,
attributes: tokenMeta.attributes ?? [],
image: tokenMeta.image,
balance: tokenMeta.balance ?? tokenMeta.data?.balance,
data: tokenMeta
});
}
token.tokenDetails = nftTokenDetails;
token.balance = nftTokenDetails.length;
token.symbol = collectionData?.symbol;
token.decimals = 0;
// TODO: Rework this. I dunno how it got this bad but I think I was working around some inconsistencies in the discovery API
// Rework so collection data API isn't required for erc20
} else if (tokenData.length > 0) {
token.name = tokenData[0].title;
token.balance = tokenData[0].balance ? BigInt(tokenData[0].balance) : 0;
token.symbol = tokenData[0].symbol;
token.decimals = tokenData[0].decimals;
} else {
token.name = collectionData.title;
token.balance = 0;
token.symbol = collectionData.symbol;
token.decimals = collectionData.decimals;
return token;
}
if (collectionData?.image)
token.image = collectionData.image;
token.symbol = tokenData[0]?.symbol ? tokenData[0]?.symbol : tokenData[0]?.data?.symbol;
return token;
}
public async getTokensByOwner(token: ITokenCollection, ownerAddress: string){
if (token.chainId === ChainID.HARDHAT_LOCALHOST){
token = await this.fetchOwnerTokensRpc(token, ownerAddress);
return token;
}
return await this.fetchOwnerTokens(token, CHAIN_MAP[token.chainId], ownerAddress);
}
public async getTokenById(token: ITokenCollection, tokenId: string){
if (token.chainId === ChainID.HARDHAT_LOCALHOST){
return await this.fetchTokenByIdRpc(token, tokenId);
}
const tokenUrl = `/get-token?chain=${CHAIN_MAP[token.chainId]}&collectionAddress=${token.contractAddress}&tokenId=${tokenId}`;
const response = await fetch(BASE_TOKEN_DISCOVERY_URL + tokenUrl);
if (!(response.status >= 200 && response.status <= 299)) {
throw new Error("Failed to load token details");
}
const tokenMeta = await response.json()
token.tokenDetails = [
{
collectionDetails: token,
attributes: tokenMeta.attributes,
collectionId: tokenMeta.collection,
ownerAddress: tokenMeta.ownerAddress,
description: tokenMeta.description,
image: tokenMeta.image || null,
name: tokenMeta.name ?? tokenMeta.title,
tokenId: tokenMeta.tokenId,
balance: tokenMeta.balance
}
];
return token;
}
public async getCollectionMeta(token: ITokenCollection, chain: string){
let collectionData = await this.getCachedMeta(token);
if (!collectionData){
if (token.chainId === ChainID.HARDHAT_LOCALHOST){
collectionData = await this.fetchTokenMetadataRpc(token);
} else {
collectionData = await this.fetchTokenMetadata(token, chain);
if (collectionData && collectionData.image == "")
collectionData.image = null;
}
await this.storeCachedMeta(token, collectionData);
}
return collectionData;
}
private async getCachedMeta(token: ITokenCollection){
if (!this.enableStorage)
return false
try {
const tokenMeta = await dbProvider.tokenMeta2.where({
chainId: token.chainId,
collectionId: token.contractAddress.toLowerCase(),
tokenType: token.tokenType
}).first();
if (tokenMeta && Date.now() < tokenMeta.dt + (COLLECTION_CACHE_TTL * 1000))
return tokenMeta.data;
} catch (e) {
console.warn(e);
}
return false;
}
private async storeCachedMeta(token: ITokenCollection, data: any){
if (!this.enableStorage)
return;
try {
await dbProvider.tokenMeta2.put({
chainId: token.chainId,
collectionId: token.contractAddress.toLowerCase(),
tokenType: token.tokenType,
data,
dt: Date.now()
});
} catch (e) {
console.warn(e);
}
}
private async fetchTokenMetadata(token: ITokenCollection, chain: string){
const url = token.tokenType === "erc20" ?
`/get-fungible-token?collectionAddress=${token.contractAddress}&chain=${chain}&blockchain=evm` :
`/get-token-collection?smartContract=${token.contractAddress}&chain=${chain}&blockchain=evm`;
return this.fetchRequest(url);
}
private async fetchOwnerTokens(token: ITokenCollection, chain: string, ownerAddress: string){
if (ownerAddress === ZeroAddress)
return [];
const url = token.tokenType === "erc20" ?
`/get-owner-fungible-tokens?collectionAddress=${token.contractAddress}&owner=${ownerAddress}&chain=${chain}&blockchain=evm` :
`/get-owner-tokens?smartContract=${token.contractAddress}&chain=${chain}&owner=${ownerAddress}&blockchain=evm`;
return this.fetchRequest(url);
}
private async fetchTokenMetadataRpc(token: ITokenCollection){
const contract = this.getEthersContractInstance(token.contractAddress, token.chainId, token.tokenType);
let name, symbol, contractUri, description, image, decimals = 1;
try {
name = await contract.name();
} catch (e){
console.log(e);
name = "Unknown Contract";
}
//console.log("Contract name: ", name);
try {
symbol = await contract.symbol();
} catch (e){
console.log(e);
}
//console.log("Contract symbol: ", symbol);
try {
contractUri = await contract.contractURI();
} catch (e){
console.log(e);
}
//console.log("Contract URI: ", contractUri);
if (contractUri){
try {
const contractMeta = await (await fetch(contractUri, {
headers: {
'Accept': 'text/plain'
}
})).json();
if (contractMeta.name || contractMeta.title)
name = contractMeta.name ?? contractMeta.title;
if (contractMeta.description)
description = contractMeta.description;
if (contractMeta.image)
image = contractMeta.image;
} catch (e){
console.error(e);
}
}
if (token.tokenType === "erc20"){
try {
decimals = Number((await contract.decimals()).toString());
} catch (e){
console.log(e);
}
}
return <ITokenCollection>{
name: name ?? "Test collection",
symbol: symbol,
description: description ?? "",
image,
decimals
}
}
private async fetchTokenByIdRpc(token: ITokenCollection, tokenId: string) {
const contract = this.getEthersContractInstance(token.contractAddress, token.chainId, token.tokenType);
try {
const meta = await this.fetchTokenMetaFromId(contract, tokenId);
const ownerAddress = await contract.ownerOf(tokenId);
token.tokenDetails = [
{
collectionId: token.originId,
tokenId: tokenId.toString(),
ownerAddress,
name: meta.name ?? "Test token #" + tokenId,
description: meta.description ?? "",
image: meta.image,
collectionDetails: token
}
];
} catch (e){
console.error(e);
}
return token;
}
private async fetchOwnerTokensRpc(token: ITokenCollection, owner: string) {
const contract = this.getEthersContractInstance(token.contractAddress, token.chainId, token.tokenType);
// TODO: ERC-20 & token metadata
const tokenDetails: ITokenDetail[] = [];
try {
if (token.tokenType === "erc20"){
token.balance = BigInt(await contract.balanceOf(owner));
} else {
let tokenIds;
try {
tokenIds = await this.getTokenIdsLogs(contract, owner);
} catch (e){
tokenIds = await this.getTokenIdsEnumerable(contract, owner);
}
for (const tokenId of tokenIds){
let meta: any = {};
try {
meta = await this.fetchTokenMetaFromId(contract, tokenId);
} catch (e){
console.warn("Failed to load token metadata:", e);
}
const ownerAddress = await contract.ownerOf(tokenId);
tokenDetails.push({
collectionId: token.originId,
tokenId: tokenId.toString(),
ownerAddress,
name: meta.name ?? "Test token #" + tokenId,
description: meta.description ?? "",
image: meta.image ?? "",
collectionDetails: token
});
//console.log("Meta Uri: ", metaUri);
}
token.tokenDetails = tokenDetails;
token.balance = tokenDetails.length;
}
} catch (e){
console.error(e);
}
return token;
}
private async fetchTokenMetaFromId(contract: Contract, tokenId: string){
const metaUri = await contract.tokenURI(tokenId);
return await (await fetch(metaUri, {
headers: {
'Accept': 'text/plain'
}
})).json();
}
private async getTokenIdsEnumerable(contract, owner){
const tokenIds = [];
const balance = BigInt(await contract.balanceOf(owner));
for (let i=0; i<balance; i++) {
tokenIds.push(BigInt(await contract.tokenOfOwnerByIndex(owner, i)));
}
return tokenIds;
}
private async getTokenIdsLogs(contract, owner){
const sentLogs = await contract.queryFilter(
contract.filters.Transfer(owner, null),
);
const receivedLogs = await contract.queryFilter(
contract.filters.Transfer(null, owner),
);
const logs = sentLogs.concat(receivedLogs)
.sort(
(a, b) =>
a.blockNumber - b.blockNumber ||
a.transactionIndex - b.transactionIndex,
);
const tokenIds = new Set();
for (const { args: { from, to, tokenId } } of logs) {
if (this.addressEqual(to, owner)) {
tokenIds.add(tokenId.toString());
} else if (this.addressEqual(from, owner)) {
tokenIds.delete(tokenId.toString());
}
}
return Array.from(tokenIds.values());
}
private addressEqual(a, b) {
return a.toLowerCase() === b.toLowerCase();
}
private getEthersContractInstance(address: string, chainId: number, type: TokenType){
const urls = CHAIN_CONFIG[chainId].rpc;
const provider = new ethers.JsonRpcProvider(typeof urls === "string" ? urls : urls[0], chainId, { staticNetwork: new Network(chainId.toString(), chainId)});
return new Contract(address, type === "erc20" ? ERC20_ABI_JSON : ERC721_ABI_JSON, provider);
}
private async fetchRequest(query: string){
const response = await fetch(BASE_TOKEN_DISCOVERY_URL + query)
const ok = response.status >= 200 && response.status <= 299
if (!ok) {
throw new Error("Failed to load tokens, please try again shortly: " + response.statusText);
}
return response.json();
}
}