forked from snapshot-labs/snapshot-strategies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
102 lines (95 loc) · 2.41 KB
/
utils.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
import fetch from 'cross-fetch';
import _strategies from './strategies';
import snapshot from '@snapshot-labs/snapshot.js';
import { getDelegations } from './utils/delegation';
import { getVp, getDelegations as getCoreDelegations } from './utils/vp';
async function callStrategy(space, network, addresses, strategy, snapshot) {
if (
(snapshot !== 'latest' && strategy.params?.start > snapshot) ||
(strategy.params?.end &&
(snapshot === 'latest' || snapshot > strategy.params?.end))
)
return {};
if (!_strategies.hasOwnProperty(strategy.name)) {
throw new Error(`Invalid strategy: ${strategy.name}`);
}
const score: any = await _strategies[strategy.name].strategy(
space,
network,
getProvider(network),
addresses,
strategy.params,
snapshot
);
const addressesLc = addresses.map((address) => address.toLowerCase());
return Object.fromEntries(
Object.entries(score).filter(
([address, vp]: any[]) =>
vp > 0 && addressesLc.includes(address.toLowerCase())
)
);
}
export async function getScoresDirect(
space: string,
strategies: any[],
network: string,
provider,
addresses: string[],
snapshot: number | string = 'latest'
) {
try {
const networks = strategies.map((s) => s.network || network);
const snapshots = await getSnapshots(network, snapshot, provider, networks);
// @ts-ignore
if (addresses.length === 0) return strategies.map(() => ({}));
return await Promise.all(
strategies.map((strategy) =>
callStrategy(
space,
strategy.network || network,
addresses,
strategy,
snapshots[strategy.network || network]
)
)
);
} catch (e) {
return Promise.reject(e);
}
}
export function customFetch(url, options, timeout = 20000): Promise<any> {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('API request timeout')), timeout)
)
]);
}
export const {
multicall,
Multicaller,
subgraphRequest,
ipfsGet,
call,
getDelegatesBySpace,
getBlockNumber,
getProvider,
getSnapshots,
SNAPSHOT_SUBGRAPH_URL
} = snapshot.utils;
export default {
getScoresDirect,
multicall,
Multicaller,
subgraphRequest,
ipfsGet,
call,
getDelegatesBySpace,
getBlockNumber,
getProvider,
getDelegations,
getSnapshots,
SNAPSHOT_SUBGRAPH_URL,
getVp,
getCoreDelegations
};