/
indexNft.ts
83 lines (76 loc) · 2.42 KB
/
indexNft.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
import config from './config';
import { graphqlRequest } from '@subsquid/util-internal-gql-request';
import { Meta } from './meta';
import { BatchState } from './state';
import { MintedPayload, TransferPayload } from './types';
import { IBatchResponse } from './types/batch';
const LIMIT = 200;
export async function indexNft(
programId: string,
fromBlock: number,
toBlock: number,
batchState: BatchState,
nftMeta: Meta,
) {
/* eslint-disable max-len*/
const query = `query {
batch(fromBlock: ${fromBlock}, toBlock: ${toBlock}, limit: ${LIMIT}, includeAllBlocks: false, gearUserMessagesSent: [{program: "${programId}", data: {event: {args: true}}}]){
header {
height
hash
timestamp
}
events
}
}`;
const { batch } = (await graphqlRequest({ url: config.squid.archiveUrl, query })) as IBatchResponse;
if (batch.length === 0) return;
for (const { header, events } of batch) {
for (const {
args: { message },
name,
} of events) {
if (name !== 'Gear.UserMessageSent') continue;
const payload = nftMeta.decodeOut(message.payload);
const variant = Object.keys(payload)[0];
let data: any;
switch (variant) {
case 'minted':
data = payload[variant] as MintedPayload;
await batchState.mintToken({
id: `${message.source}-${data.tokenId}`,
owner: data.owner,
nftContract: message.source,
burnt: false,
isListed: false,
price: null,
transfers: [],
offers: [],
tokenId: data.tokenId,
auction: null,
...data.tokenMetadata,
});
break;
case 'burnt':
data = payload[variant];
await batchState.burnToken({ tokenId: `${message.source}-${data.tokenId}` });
break;
case 'transfer':
data = payload[variant] as TransferPayload;
await batchState.transferToken({
tokenId: `${message.source}-${data.tokenId}`,
id: message.id,
from: data.from,
to: data.to,
timestamp: Date.parse(header.timestamp),
});
break;
}
}
if (batch.length === LIMIT) {
const lastBlock = 0;
batch.forEach(({ header: { height } }) => Math.max(lastBlock, height));
await indexNft(programId, lastBlock, toBlock, batchState, nftMeta);
}
}
}