-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
76 lines (66 loc) · 1.78 KB
/
index.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
const { dispatch } = require("./plugins");
const ERC721ABI = require("./abis/erc721.abi.json");
function subscribe(web3, contractAddress, ownerAddress, wantMetadata = true) {
const contract = new web3.eth.Contract(ERC721ABI, contractAddress);
const funcs = {};
const onAddCallbacks = [];
const onRemoveCallbacks = [];
const listen = true;
function onAdd(callback) {
onAddCallbacks.push(callback);
return funcs;
}
function onRemove(callback) {
onRemoveCallbacks.push(callback);
return funcs;
}
function unsubscribe() {
listen = false;
}
funcs.onAdd = onAdd;
funcs.onRemove = onRemove;
funcs.unsubscribe = unsubscribe;
setTimeout(async () => {
const { getTokens, getTokenMetadata } = await dispatch(
web3,
contractAddress
);
const promises = await getTokens(web3, contractAddress, ownerAddress);
for (let i = 0; i < promises.length; i++) {
if (wantMetadata) {
promises[i] = promises[i].then(getTokenMetadata.bind(null, contract));
}
promises[i].then(value =>
onAddCallbacks.map(callback => callback(value))
);
}
});
return funcs;
}
async function getTokensOfOwner(
web3,
contractAddress,
ownerAddress,
wantMetadata = true
) {
const contract = new web3.eth.Contract(ERC721ABI, contractAddress);
const total = parseInt(await contract.methods.balanceOf(ownerAddress).call(), 10);
const tokens = [];
return new Promise((resolve, reject) => {
if (total === 0) {
resolve([]);
}
const s = subscribe(web3, contractAddress, ownerAddress, wantMetadata);
s.onAdd(token => {
tokens.push(token);
if (tokens.length === total) {
resolve(tokens);
}
});
});
}
module.exports = {
// hasMetadata,
subscribe,
getTokensOfOwner
};