forked from Vitruveo/graphql-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenumerable.js
128 lines (106 loc) · 4.16 KB
/
enumerable.js
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
const { gql, ApolloClient, InMemoryCache } = require('@apollo/client/core');
class Enumerable {
DEFAULT_SKIP = 1000;
contract;
client;
constructor(contract) {
this.contract = contract;
this.client = new ApolloClient({
uri: 'http://graph.vitruveo.xyz/subgraphs/name/tokens/erc721/',
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: "cache-first"
}
}
});
}
async totalSupply() {
let count = 0;
let newCount = 0;
let skip = 0;
do {
const results = await this.client.query({
query: gql`
query allTokens {
erc721Tokens(
where: {contract: "${this.contract}"}
first: 1000
skip: ${ skip }
) {
identifier
}
}`
});
newCount = results.data.erc721Tokens.length;
count += newCount;
skip += this.DEFAULT_SKIP;
} while(newCount > 0);
return(count);
}
async tokenOfOwnerByIndex(owner, index) {
if (!owner || index < 1) {
return null;
} else {
const results = await this.client.query({
query: gql`
query tokensByOwner {
erc721Tokens(
where: {contract: "${this.contract}", owner: "${owner}"}
first: 1
skip: ${ index - 1}
) {
identifier
}
}`
});
return results.data.erc721Tokens.length > 0 ? Number(results.data.erc721Tokens[0].identifier) : null;
}
}
async tokenByIndex(index) {
if (index < 1) {
return null;
} else {
const results = await this.client.query({
query: gql`
query tokensByOwner {
erc721Tokens(
where: {contract: "${this.contract}"}
first: 1
skip: ${ index - 1}
) {
identifier,
uri
}
}`
});
return results.data.erc721Tokens.length > 0 ? results.data.erc721Tokens[0].uri : null;
}
}
async allTokens() {
let count = 0;
let newCount = 0;
let skip = 0;
let tokens = [];
do {
const results = await this.client.query({
query: gql`
query allTokens {
erc721Tokens(
where: {contract: "${this.contract}"}
first: 1000
skip: ${ skip }
) {
identifier
}
}`
});
newCount = results.data.erc721Tokens.length;
results.data.erc721Tokens.forEach(t => tokens.push(Number(t.identifier)) )
count += newCount;
skip += this.DEFAULT_SKIP;
} while(newCount > 0);
return(tokens);
}
}
module.exports = { Enumerable }