@snapshot-labs/snapshot.js 0.11.38 → 0.11.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,17 +28,6 @@ See the Apache Version 2.0 License for specific language governing permissions
28
28
  and limitations under the License.
29
29
  ***************************************************************************** */
30
30
 
31
- var __assign = function() {
32
- __assign = Object.assign || function __assign(t) {
33
- for (var s, i = 1, n = arguments.length; i < n; i++) {
34
- s = arguments[i];
35
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
36
- }
37
- return t;
38
- };
39
- return __assign.apply(this, arguments);
40
- };
41
-
42
31
  function __rest(s, e) {
43
32
  var t = {};
44
33
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -59,256 +48,205 @@ function __awaiter(thisArg, _arguments, P, generator) {
59
48
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
60
49
  step((generator = generator.apply(thisArg, _arguments || [])).next());
61
50
  });
62
- }
63
-
64
- function __generator(thisArg, body) {
65
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
66
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
67
- function verb(n) { return function (v) { return step([n, v]); }; }
68
- function step(op) {
69
- if (f) throw new TypeError("Generator is already executing.");
70
- while (_) try {
71
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
72
- if (y = 0, t) op = [op[0] & 2, t.value];
73
- switch (op[0]) {
74
- case 0: case 1: t = op; break;
75
- case 4: _.label++; return { value: op[1], done: false };
76
- case 5: _.label++; y = op[1]; op = [0]; continue;
77
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
78
- default:
79
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
80
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
81
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
82
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
83
- if (t[2]) _.ops.pop();
84
- _.trys.pop(); continue;
85
- }
86
- op = body.call(thisArg, _);
87
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
88
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
89
- }
90
- }
91
-
92
- function __read(o, n) {
93
- var m = typeof Symbol === "function" && o[Symbol.iterator];
94
- if (!m) return o;
95
- var i = m.call(o), r, ar = [], e;
96
- try {
97
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
98
- }
99
- catch (error) { e = { error: error }; }
100
- finally {
101
- try {
102
- if (r && !r.done && (m = i["return"])) m.call(i);
103
- }
104
- finally { if (e) throw e.error; }
105
- }
106
- return ar;
107
- }
108
-
109
- function __spread() {
110
- for (var ar = [], i = 0; i < arguments.length; i++)
111
- ar = ar.concat(__read(arguments[i]));
112
- return ar;
113
51
  }
114
52
 
115
- var spaceTypes = {
116
- Space: [
117
- { name: 'from', type: 'address' },
118
- { name: 'space', type: 'string' },
119
- { name: 'timestamp', type: 'uint64' },
120
- { name: 'settings', type: 'string' }
121
- ]
122
- };
123
- var proposalTypes = {
124
- Proposal: [
125
- { name: 'from', type: 'address' },
126
- { name: 'space', type: 'string' },
127
- { name: 'timestamp', type: 'uint64' },
128
- { name: 'type', type: 'string' },
129
- { name: 'title', type: 'string' },
130
- { name: 'body', type: 'string' },
131
- { name: 'discussion', type: 'string' },
132
- { name: 'choices', type: 'string[]' },
133
- { name: 'start', type: 'uint64' },
134
- { name: 'end', type: 'uint64' },
135
- { name: 'snapshot', type: 'uint64' },
136
- { name: 'plugins', type: 'string' },
137
- { name: 'app', type: 'string' }
138
- ]
139
- };
140
- var updateProposalTypes = {
141
- UpdateProposal: [
142
- { name: 'proposal', type: 'string' },
143
- { name: 'from', type: 'address' },
144
- { name: 'space', type: 'string' },
145
- { name: 'timestamp', type: 'uint64' },
146
- { name: 'type', type: 'string' },
147
- { name: 'title', type: 'string' },
148
- { name: 'body', type: 'string' },
149
- { name: 'discussion', type: 'string' },
150
- { name: 'choices', type: 'string[]' },
151
- { name: 'plugins', type: 'string' }
152
- ]
153
- };
154
- var flagProposalTypes = {
155
- FlagProposal: [
156
- { name: 'from', type: 'address' },
157
- { name: 'space', type: 'string' },
158
- { name: 'proposal', type: 'string' },
159
- { name: 'timestamp', type: 'uint64' }
160
- ]
161
- };
162
- var cancelProposalTypes = {
163
- CancelProposal: [
164
- { name: 'from', type: 'address' },
165
- { name: 'space', type: 'string' },
166
- { name: 'timestamp', type: 'uint64' },
167
- { name: 'proposal', type: 'string' }
168
- ]
169
- };
170
- var cancelProposal2Types = {
171
- CancelProposal: [
172
- { name: 'from', type: 'address' },
173
- { name: 'space', type: 'string' },
174
- { name: 'timestamp', type: 'uint64' },
175
- { name: 'proposal', type: 'bytes32' }
176
- ]
177
- };
178
- var voteTypes = {
179
- Vote: [
180
- { name: 'from', type: 'address' },
181
- { name: 'space', type: 'string' },
182
- { name: 'timestamp', type: 'uint64' },
183
- { name: 'proposal', type: 'string' },
184
- { name: 'choice', type: 'uint32' },
185
- { name: 'reason', type: 'string' },
186
- { name: 'app', type: 'string' },
187
- { name: 'metadata', type: 'string' }
188
- ]
189
- };
190
- var voteArrayTypes = {
191
- Vote: [
192
- { name: 'from', type: 'address' },
193
- { name: 'space', type: 'string' },
194
- { name: 'timestamp', type: 'uint64' },
195
- { name: 'proposal', type: 'string' },
196
- { name: 'choice', type: 'uint32[]' },
197
- { name: 'reason', type: 'string' },
198
- { name: 'app', type: 'string' },
199
- { name: 'metadata', type: 'string' }
200
- ]
201
- };
202
- var voteStringTypes = {
203
- Vote: [
204
- { name: 'from', type: 'address' },
205
- { name: 'space', type: 'string' },
206
- { name: 'timestamp', type: 'uint64' },
207
- { name: 'proposal', type: 'string' },
208
- { name: 'choice', type: 'string' },
209
- { name: 'reason', type: 'string' },
210
- { name: 'app', type: 'string' },
211
- { name: 'metadata', type: 'string' }
212
- ]
213
- };
214
- var vote2Types = {
215
- Vote: [
216
- { name: 'from', type: 'address' },
217
- { name: 'space', type: 'string' },
218
- { name: 'timestamp', type: 'uint64' },
219
- { name: 'proposal', type: 'bytes32' },
220
- { name: 'choice', type: 'uint32' },
221
- { name: 'reason', type: 'string' },
222
- { name: 'app', type: 'string' },
223
- { name: 'metadata', type: 'string' }
224
- ]
225
- };
226
- var voteArray2Types = {
227
- Vote: [
228
- { name: 'from', type: 'address' },
229
- { name: 'space', type: 'string' },
230
- { name: 'timestamp', type: 'uint64' },
231
- { name: 'proposal', type: 'bytes32' },
232
- { name: 'choice', type: 'uint32[]' },
233
- { name: 'reason', type: 'string' },
234
- { name: 'app', type: 'string' },
235
- { name: 'metadata', type: 'string' }
236
- ]
237
- };
238
- var voteString2Types = {
239
- Vote: [
240
- { name: 'from', type: 'address' },
241
- { name: 'space', type: 'string' },
242
- { name: 'timestamp', type: 'uint64' },
243
- { name: 'proposal', type: 'bytes32' },
244
- { name: 'choice', type: 'string' },
245
- { name: 'reason', type: 'string' },
246
- { name: 'app', type: 'string' },
247
- { name: 'metadata', type: 'string' }
248
- ]
249
- };
250
- var followTypes = {
251
- Follow: [
252
- { name: 'from', type: 'address' },
253
- { name: 'network', type: 'string' },
254
- { name: 'space', type: 'string' },
255
- { name: 'timestamp', type: 'uint64' }
256
- ]
257
- };
258
- var unfollowTypes = {
259
- Unfollow: [
260
- { name: 'from', type: 'address' },
261
- { name: 'network', type: 'string' },
262
- { name: 'space', type: 'string' },
263
- { name: 'timestamp', type: 'uint64' }
264
- ]
265
- };
266
- var subscribeTypes = {
267
- Subscribe: [
268
- { name: 'from', type: 'address' },
269
- { name: 'space', type: 'string' },
270
- { name: 'timestamp', type: 'uint64' }
271
- ]
272
- };
273
- var unsubscribeTypes = {
274
- Unsubscribe: [
275
- { name: 'from', type: 'address' },
276
- { name: 'space', type: 'string' },
277
- { name: 'timestamp', type: 'uint64' }
278
- ]
279
- };
280
- var profileTypes = {
281
- Profile: [
282
- { name: 'from', type: 'address' },
283
- { name: 'timestamp', type: 'uint64' },
284
- { name: 'profile', type: 'string' }
285
- ]
286
- };
287
- var statementTypes = {
288
- Statement: [
289
- { name: 'from', type: 'address' },
290
- { name: 'timestamp', type: 'uint64' },
291
- { name: 'space', type: 'string' },
292
- { name: 'about', type: 'string' },
293
- { name: 'statement', type: 'string' },
294
- { name: 'discourse', type: 'string' },
295
- { name: 'status', type: 'string' },
296
- { name: 'network', type: 'string' }
297
- ]
298
- };
299
- var aliasTypes = {
300
- Alias: [
301
- { name: 'from', type: 'address' },
302
- { name: 'alias', type: 'address' },
303
- { name: 'timestamp', type: 'uint64' }
304
- ]
305
- };
306
- var deleteSpaceType = {
307
- DeleteSpace: [
308
- { name: 'from', type: 'address' },
309
- { name: 'space', type: 'string' },
310
- { name: 'timestamp', type: 'uint64' }
311
- ]
53
+ const spaceTypes = {
54
+ Space: [
55
+ { name: 'from', type: 'address' },
56
+ { name: 'space', type: 'string' },
57
+ { name: 'timestamp', type: 'uint64' },
58
+ { name: 'settings', type: 'string' }
59
+ ]
60
+ };
61
+ const proposalTypes = {
62
+ Proposal: [
63
+ { name: 'from', type: 'address' },
64
+ { name: 'space', type: 'string' },
65
+ { name: 'timestamp', type: 'uint64' },
66
+ { name: 'type', type: 'string' },
67
+ { name: 'title', type: 'string' },
68
+ { name: 'body', type: 'string' },
69
+ { name: 'discussion', type: 'string' },
70
+ { name: 'choices', type: 'string[]' },
71
+ { name: 'start', type: 'uint64' },
72
+ { name: 'end', type: 'uint64' },
73
+ { name: 'snapshot', type: 'uint64' },
74
+ { name: 'plugins', type: 'string' },
75
+ { name: 'app', type: 'string' }
76
+ ]
77
+ };
78
+ const updateProposalTypes = {
79
+ UpdateProposal: [
80
+ { name: 'proposal', type: 'string' },
81
+ { name: 'from', type: 'address' },
82
+ { name: 'space', type: 'string' },
83
+ { name: 'timestamp', type: 'uint64' },
84
+ { name: 'type', type: 'string' },
85
+ { name: 'title', type: 'string' },
86
+ { name: 'body', type: 'string' },
87
+ { name: 'discussion', type: 'string' },
88
+ { name: 'choices', type: 'string[]' },
89
+ { name: 'plugins', type: 'string' }
90
+ ]
91
+ };
92
+ const flagProposalTypes = {
93
+ FlagProposal: [
94
+ { name: 'from', type: 'address' },
95
+ { name: 'space', type: 'string' },
96
+ { name: 'proposal', type: 'string' },
97
+ { name: 'timestamp', type: 'uint64' }
98
+ ]
99
+ };
100
+ const cancelProposalTypes = {
101
+ CancelProposal: [
102
+ { name: 'from', type: 'address' },
103
+ { name: 'space', type: 'string' },
104
+ { name: 'timestamp', type: 'uint64' },
105
+ { name: 'proposal', type: 'string' }
106
+ ]
107
+ };
108
+ const cancelProposal2Types = {
109
+ CancelProposal: [
110
+ { name: 'from', type: 'address' },
111
+ { name: 'space', type: 'string' },
112
+ { name: 'timestamp', type: 'uint64' },
113
+ { name: 'proposal', type: 'bytes32' }
114
+ ]
115
+ };
116
+ const voteTypes = {
117
+ Vote: [
118
+ { name: 'from', type: 'address' },
119
+ { name: 'space', type: 'string' },
120
+ { name: 'timestamp', type: 'uint64' },
121
+ { name: 'proposal', type: 'string' },
122
+ { name: 'choice', type: 'uint32' },
123
+ { name: 'reason', type: 'string' },
124
+ { name: 'app', type: 'string' },
125
+ { name: 'metadata', type: 'string' }
126
+ ]
127
+ };
128
+ const voteArrayTypes = {
129
+ Vote: [
130
+ { name: 'from', type: 'address' },
131
+ { name: 'space', type: 'string' },
132
+ { name: 'timestamp', type: 'uint64' },
133
+ { name: 'proposal', type: 'string' },
134
+ { name: 'choice', type: 'uint32[]' },
135
+ { name: 'reason', type: 'string' },
136
+ { name: 'app', type: 'string' },
137
+ { name: 'metadata', type: 'string' }
138
+ ]
139
+ };
140
+ const voteStringTypes = {
141
+ Vote: [
142
+ { name: 'from', type: 'address' },
143
+ { name: 'space', type: 'string' },
144
+ { name: 'timestamp', type: 'uint64' },
145
+ { name: 'proposal', type: 'string' },
146
+ { name: 'choice', type: 'string' },
147
+ { name: 'reason', type: 'string' },
148
+ { name: 'app', type: 'string' },
149
+ { name: 'metadata', type: 'string' }
150
+ ]
151
+ };
152
+ const vote2Types = {
153
+ Vote: [
154
+ { name: 'from', type: 'address' },
155
+ { name: 'space', type: 'string' },
156
+ { name: 'timestamp', type: 'uint64' },
157
+ { name: 'proposal', type: 'bytes32' },
158
+ { name: 'choice', type: 'uint32' },
159
+ { name: 'reason', type: 'string' },
160
+ { name: 'app', type: 'string' },
161
+ { name: 'metadata', type: 'string' }
162
+ ]
163
+ };
164
+ const voteArray2Types = {
165
+ Vote: [
166
+ { name: 'from', type: 'address' },
167
+ { name: 'space', type: 'string' },
168
+ { name: 'timestamp', type: 'uint64' },
169
+ { name: 'proposal', type: 'bytes32' },
170
+ { name: 'choice', type: 'uint32[]' },
171
+ { name: 'reason', type: 'string' },
172
+ { name: 'app', type: 'string' },
173
+ { name: 'metadata', type: 'string' }
174
+ ]
175
+ };
176
+ const voteString2Types = {
177
+ Vote: [
178
+ { name: 'from', type: 'address' },
179
+ { name: 'space', type: 'string' },
180
+ { name: 'timestamp', type: 'uint64' },
181
+ { name: 'proposal', type: 'bytes32' },
182
+ { name: 'choice', type: 'string' },
183
+ { name: 'reason', type: 'string' },
184
+ { name: 'app', type: 'string' },
185
+ { name: 'metadata', type: 'string' }
186
+ ]
187
+ };
188
+ const followTypes = {
189
+ Follow: [
190
+ { name: 'from', type: 'address' },
191
+ { name: 'network', type: 'string' },
192
+ { name: 'space', type: 'string' },
193
+ { name: 'timestamp', type: 'uint64' }
194
+ ]
195
+ };
196
+ const unfollowTypes = {
197
+ Unfollow: [
198
+ { name: 'from', type: 'address' },
199
+ { name: 'network', type: 'string' },
200
+ { name: 'space', type: 'string' },
201
+ { name: 'timestamp', type: 'uint64' }
202
+ ]
203
+ };
204
+ const subscribeTypes = {
205
+ Subscribe: [
206
+ { name: 'from', type: 'address' },
207
+ { name: 'space', type: 'string' },
208
+ { name: 'timestamp', type: 'uint64' }
209
+ ]
210
+ };
211
+ const unsubscribeTypes = {
212
+ Unsubscribe: [
213
+ { name: 'from', type: 'address' },
214
+ { name: 'space', type: 'string' },
215
+ { name: 'timestamp', type: 'uint64' }
216
+ ]
217
+ };
218
+ const profileTypes = {
219
+ Profile: [
220
+ { name: 'from', type: 'address' },
221
+ { name: 'timestamp', type: 'uint64' },
222
+ { name: 'profile', type: 'string' }
223
+ ]
224
+ };
225
+ const statementTypes = {
226
+ Statement: [
227
+ { name: 'from', type: 'address' },
228
+ { name: 'timestamp', type: 'uint64' },
229
+ { name: 'space', type: 'string' },
230
+ { name: 'about', type: 'string' },
231
+ { name: 'statement', type: 'string' },
232
+ { name: 'discourse', type: 'string' },
233
+ { name: 'status', type: 'string' },
234
+ { name: 'network', type: 'string' }
235
+ ]
236
+ };
237
+ const aliasTypes = {
238
+ Alias: [
239
+ { name: 'from', type: 'address' },
240
+ { name: 'alias', type: 'address' },
241
+ { name: 'timestamp', type: 'uint64' }
242
+ ]
243
+ };
244
+ const deleteSpaceType = {
245
+ DeleteSpace: [
246
+ { name: 'from', type: 'address' },
247
+ { name: 'space', type: 'string' },
248
+ { name: 'timestamp', type: 'uint64' }
249
+ ]
312
250
  };
313
251
 
314
252
  var livenet = {
@@ -329,255 +267,163 @@ var constants = {
329
267
  local: local
330
268
  };
331
269
 
332
- var NAME = 'snapshot';
333
- var VERSION = '0.1.4';
334
- var domain = {
335
- name: NAME,
336
- version: VERSION
337
- // chainId: 1
338
- };
339
- var Client = /** @class */ (function () {
340
- function Client(address, options) {
341
- if (address === void 0) { address = constants.livenet.sequencer; }
342
- if (options === void 0) { options = {}; }
343
- address = address.replace(constants.livenet.hub, constants.livenet.sequencer);
344
- address = address.replace(constants.testnet.hub, constants.testnet.sequencer);
345
- address = address.replace(constants.local.hub, constants.local.sequencer);
346
- this.address = address;
347
- this.options = options;
348
- }
349
- Client.prototype.sign = function (web3, address, message, types) {
350
- var _a;
351
- return __awaiter(this, void 0, void 0, function () {
352
- var signer, checksumAddress, domainData, _b, data, sig;
353
- return __generator(this, function (_c) {
354
- switch (_c.label) {
355
- case 0:
356
- signer = (web3 === null || web3 === void 0 ? void 0 : web3.getSigner) ? web3.getSigner() : web3;
357
- checksumAddress = getAddress(address);
358
- message.from = message.from ? getAddress(message.from) : checksumAddress;
359
- if (!message.timestamp)
360
- message.timestamp = parseInt((Date.now() / 1e3).toFixed());
361
- domainData = __assign({}, domain);
362
- if (!(typeof window !== 'undefined' && ((_a = window.ethereum) === null || _a === void 0 ? void 0 : _a.isTrust))) return [3 /*break*/, 2];
363
- _b = domainData;
364
- return [4 /*yield*/, signer.provider.getNetwork()];
365
- case 1:
366
- _b.chainId = (_c.sent()).chainId;
367
- _c.label = 2;
368
- case 2:
369
- data = { domain: domainData, types: types, message: message };
370
- return [4 /*yield*/, signer._signTypedData(domainData, data.types, message)];
371
- case 3:
372
- sig = _c.sent();
373
- return [4 /*yield*/, this.send({ address: checksumAddress, sig: sig, data: data })];
374
- case 4: return [2 /*return*/, _c.sent()];
375
- }
376
- });
377
- });
378
- };
379
- Client.prototype.send = function (envelop) {
380
- return __awaiter(this, void 0, void 0, function () {
381
- var address, init;
382
- return __generator(this, function (_a) {
383
- address = this.address;
384
- if (envelop.sig === '0x' && this.options.relayerURL)
385
- address = this.options.relayerURL;
386
- init = {
387
- method: 'POST',
388
- headers: {
389
- Accept: 'application/json',
390
- 'Content-Type': 'application/json'
391
- },
392
- body: JSON.stringify(envelop)
393
- };
394
- return [2 /*return*/, new Promise(function (resolve, reject) {
395
- fetch(address, init)
396
- .then(function (res) {
397
- var _a;
398
- if (res.ok)
399
- return resolve(res.json());
400
- if ((_a = res.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json'))
401
- return res.json().then(reject).catch(reject);
402
- throw res;
403
- })
404
- .catch(reject);
405
- })];
406
- });
407
- });
408
- };
409
- Client.prototype.space = function (web3, address, message) {
410
- return __awaiter(this, void 0, void 0, function () {
411
- return __generator(this, function (_a) {
412
- switch (_a.label) {
413
- case 0: return [4 /*yield*/, this.sign(web3, address, message, spaceTypes)];
414
- case 1: return [2 /*return*/, _a.sent()];
415
- }
416
- });
417
- });
418
- };
419
- Client.prototype.proposal = function (web3, address, message) {
420
- return __awaiter(this, void 0, void 0, function () {
421
- return __generator(this, function (_a) {
422
- switch (_a.label) {
423
- case 0:
424
- if (!message.discussion)
425
- message.discussion = '';
426
- if (!message.app)
427
- message.app = '';
428
- return [4 /*yield*/, this.sign(web3, address, message, proposalTypes)];
429
- case 1: return [2 /*return*/, _a.sent()];
430
- }
431
- });
432
- });
433
- };
434
- Client.prototype.updateProposal = function (web3, address, message) {
435
- return __awaiter(this, void 0, void 0, function () {
436
- return __generator(this, function (_a) {
437
- switch (_a.label) {
438
- case 0: return [4 /*yield*/, this.sign(web3, address, message, updateProposalTypes)];
439
- case 1: return [2 /*return*/, _a.sent()];
440
- }
441
- });
442
- });
443
- };
444
- Client.prototype.flagProposal = function (web3, address, message) {
445
- return __awaiter(this, void 0, void 0, function () {
446
- return __generator(this, function (_a) {
447
- switch (_a.label) {
448
- case 0: return [4 /*yield*/, this.sign(web3, address, message, flagProposalTypes)];
449
- case 1: return [2 /*return*/, _a.sent()];
450
- }
451
- });
452
- });
453
- };
454
- Client.prototype.cancelProposal = function (web3, address, message) {
455
- return __awaiter(this, void 0, void 0, function () {
456
- var type2;
457
- return __generator(this, function (_a) {
458
- switch (_a.label) {
459
- case 0:
460
- type2 = message.proposal.startsWith('0x');
461
- return [4 /*yield*/, this.sign(web3, address, message, type2 ? cancelProposal2Types : cancelProposalTypes)];
462
- case 1: return [2 /*return*/, _a.sent()];
463
- }
464
- });
465
- });
466
- };
467
- Client.prototype.vote = function (web3, address, message) {
468
- return __awaiter(this, void 0, void 0, function () {
469
- var isShutter, type2, type;
470
- return __generator(this, function (_a) {
471
- switch (_a.label) {
472
- case 0:
473
- isShutter = (message === null || message === void 0 ? void 0 : message.privacy) === 'shutter';
474
- if (!message.reason)
475
- message.reason = '';
476
- if (!message.app)
477
- message.app = '';
478
- if (!message.metadata)
479
- message.metadata = '{}';
480
- type2 = message.proposal.startsWith('0x');
481
- type = type2 ? vote2Types : voteTypes;
482
- if (['approval', 'ranked-choice'].includes(message.type))
483
- type = type2 ? voteArray2Types : voteArrayTypes;
484
- if (!isShutter && ['quadratic', 'weighted'].includes(message.type)) {
485
- type = type2 ? voteString2Types : voteStringTypes;
486
- message.choice = JSON.stringify(message.choice);
487
- }
488
- if (isShutter)
489
- type = type2 ? voteString2Types : voteStringTypes;
490
- delete message.privacy;
491
- // @ts-ignore
492
- delete message.type;
493
- return [4 /*yield*/, this.sign(web3, address, message, type)];
494
- case 1: return [2 /*return*/, _a.sent()];
495
- }
496
- });
497
- });
498
- };
499
- Client.prototype.follow = function (web3, address, message) {
500
- return __awaiter(this, void 0, void 0, function () {
501
- return __generator(this, function (_a) {
502
- switch (_a.label) {
503
- case 0: return [4 /*yield*/, this.sign(web3, address, message, followTypes)];
504
- case 1: return [2 /*return*/, _a.sent()];
505
- }
506
- });
507
- });
508
- };
509
- Client.prototype.unfollow = function (web3, address, message) {
510
- return __awaiter(this, void 0, void 0, function () {
511
- return __generator(this, function (_a) {
512
- switch (_a.label) {
513
- case 0: return [4 /*yield*/, this.sign(web3, address, message, unfollowTypes)];
514
- case 1: return [2 /*return*/, _a.sent()];
515
- }
516
- });
517
- });
518
- };
519
- Client.prototype.subscribe = function (web3, address, message) {
520
- return __awaiter(this, void 0, void 0, function () {
521
- return __generator(this, function (_a) {
522
- switch (_a.label) {
523
- case 0: return [4 /*yield*/, this.sign(web3, address, message, subscribeTypes)];
524
- case 1: return [2 /*return*/, _a.sent()];
525
- }
526
- });
527
- });
528
- };
529
- Client.prototype.unsubscribe = function (web3, address, message) {
530
- return __awaiter(this, void 0, void 0, function () {
531
- return __generator(this, function (_a) {
532
- switch (_a.label) {
533
- case 0: return [4 /*yield*/, this.sign(web3, address, message, unsubscribeTypes)];
534
- case 1: return [2 /*return*/, _a.sent()];
535
- }
536
- });
537
- });
538
- };
539
- Client.prototype.profile = function (web3, address, message) {
540
- return __awaiter(this, void 0, void 0, function () {
541
- return __generator(this, function (_a) {
542
- switch (_a.label) {
543
- case 0: return [4 /*yield*/, this.sign(web3, address, message, profileTypes)];
544
- case 1: return [2 /*return*/, _a.sent()];
545
- }
546
- });
547
- });
548
- };
549
- Client.prototype.statement = function (web3, address, message) {
550
- return __awaiter(this, void 0, void 0, function () {
551
- return __generator(this, function (_a) {
552
- switch (_a.label) {
553
- case 0: return [4 /*yield*/, this.sign(web3, address, message, statementTypes)];
554
- case 1: return [2 /*return*/, _a.sent()];
555
- }
556
- });
557
- });
558
- };
559
- Client.prototype.alias = function (web3, address, message) {
560
- return __awaiter(this, void 0, void 0, function () {
561
- return __generator(this, function (_a) {
562
- switch (_a.label) {
563
- case 0: return [4 /*yield*/, this.sign(web3, address, message, aliasTypes)];
564
- case 1: return [2 /*return*/, _a.sent()];
565
- }
566
- });
567
- });
568
- };
569
- Client.prototype.deleteSpace = function (web3, address, message) {
570
- return __awaiter(this, void 0, void 0, function () {
571
- return __generator(this, function (_a) {
572
- switch (_a.label) {
573
- case 0: return [4 /*yield*/, this.sign(web3, address, message, deleteSpaceType)];
574
- case 1: return [2 /*return*/, _a.sent()];
575
- }
576
- });
577
- });
578
- };
579
- return Client;
580
- }());
270
+ const NAME = 'snapshot';
271
+ const VERSION = '0.1.4';
272
+ const domain = {
273
+ name: NAME,
274
+ version: VERSION
275
+ // chainId: 1
276
+ };
277
+ class Client {
278
+ constructor(address = constants.livenet.sequencer, options = {}) {
279
+ address = address.replace(constants.livenet.hub, constants.livenet.sequencer);
280
+ address = address.replace(constants.testnet.hub, constants.testnet.sequencer);
281
+ address = address.replace(constants.local.hub, constants.local.sequencer);
282
+ this.address = address;
283
+ this.options = options;
284
+ }
285
+ sign(web3, address, message, types) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ var _a;
288
+ // @ts-ignore
289
+ const signer = (web3 === null || web3 === void 0 ? void 0 : web3.getSigner) ? web3.getSigner() : web3;
290
+ const checksumAddress = getAddress(address);
291
+ message.from = message.from ? getAddress(message.from) : checksumAddress;
292
+ if (!message.timestamp)
293
+ message.timestamp = parseInt((Date.now() / 1e3).toFixed());
294
+ const domainData = Object.assign({}, domain);
295
+ // @ts-ignore
296
+ if (typeof window !== 'undefined' && ((_a = window.ethereum) === null || _a === void 0 ? void 0 : _a.isTrust)) {
297
+ domainData.chainId = (yield signer.provider.getNetwork()).chainId;
298
+ }
299
+ const data = { domain: domainData, types, message };
300
+ const sig = yield signer._signTypedData(domainData, data.types, message);
301
+ return yield this.send({ address: checksumAddress, sig, data });
302
+ });
303
+ }
304
+ send(envelop) {
305
+ return __awaiter(this, void 0, void 0, function* () {
306
+ let address = this.address;
307
+ if (envelop.sig === '0x' && this.options.relayerURL)
308
+ address = this.options.relayerURL;
309
+ const init = {
310
+ method: 'POST',
311
+ headers: {
312
+ Accept: 'application/json',
313
+ 'Content-Type': 'application/json'
314
+ },
315
+ body: JSON.stringify(envelop)
316
+ };
317
+ return new Promise((resolve, reject) => {
318
+ fetch(address, init)
319
+ .then((res) => {
320
+ var _a;
321
+ if (res.ok)
322
+ return resolve(res.json());
323
+ if ((_a = res.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json'))
324
+ return res.json().then(reject).catch(reject);
325
+ throw res;
326
+ })
327
+ .catch(reject);
328
+ });
329
+ });
330
+ }
331
+ space(web3, address, message) {
332
+ return __awaiter(this, void 0, void 0, function* () {
333
+ return yield this.sign(web3, address, message, spaceTypes);
334
+ });
335
+ }
336
+ proposal(web3, address, message) {
337
+ return __awaiter(this, void 0, void 0, function* () {
338
+ if (!message.discussion)
339
+ message.discussion = '';
340
+ if (!message.app)
341
+ message.app = '';
342
+ return yield this.sign(web3, address, message, proposalTypes);
343
+ });
344
+ }
345
+ updateProposal(web3, address, message) {
346
+ return __awaiter(this, void 0, void 0, function* () {
347
+ return yield this.sign(web3, address, message, updateProposalTypes);
348
+ });
349
+ }
350
+ flagProposal(web3, address, message) {
351
+ return __awaiter(this, void 0, void 0, function* () {
352
+ return yield this.sign(web3, address, message, flagProposalTypes);
353
+ });
354
+ }
355
+ cancelProposal(web3, address, message) {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ const type2 = message.proposal.startsWith('0x');
358
+ return yield this.sign(web3, address, message, type2 ? cancelProposal2Types : cancelProposalTypes);
359
+ });
360
+ }
361
+ vote(web3, address, message) {
362
+ return __awaiter(this, void 0, void 0, function* () {
363
+ const isShutter = (message === null || message === void 0 ? void 0 : message.privacy) === 'shutter';
364
+ if (!message.reason)
365
+ message.reason = '';
366
+ if (!message.app)
367
+ message.app = '';
368
+ if (!message.metadata)
369
+ message.metadata = '{}';
370
+ const type2 = message.proposal.startsWith('0x');
371
+ let type = type2 ? vote2Types : voteTypes;
372
+ if (['approval', 'ranked-choice'].includes(message.type))
373
+ type = type2 ? voteArray2Types : voteArrayTypes;
374
+ if (!isShutter && ['quadratic', 'weighted'].includes(message.type)) {
375
+ type = type2 ? voteString2Types : voteStringTypes;
376
+ message.choice = JSON.stringify(message.choice);
377
+ }
378
+ if (isShutter)
379
+ type = type2 ? voteString2Types : voteStringTypes;
380
+ delete message.privacy;
381
+ // @ts-ignore
382
+ delete message.type;
383
+ return yield this.sign(web3, address, message, type);
384
+ });
385
+ }
386
+ follow(web3, address, message) {
387
+ return __awaiter(this, void 0, void 0, function* () {
388
+ return yield this.sign(web3, address, message, followTypes);
389
+ });
390
+ }
391
+ unfollow(web3, address, message) {
392
+ return __awaiter(this, void 0, void 0, function* () {
393
+ return yield this.sign(web3, address, message, unfollowTypes);
394
+ });
395
+ }
396
+ subscribe(web3, address, message) {
397
+ return __awaiter(this, void 0, void 0, function* () {
398
+ return yield this.sign(web3, address, message, subscribeTypes);
399
+ });
400
+ }
401
+ unsubscribe(web3, address, message) {
402
+ return __awaiter(this, void 0, void 0, function* () {
403
+ return yield this.sign(web3, address, message, unsubscribeTypes);
404
+ });
405
+ }
406
+ profile(web3, address, message) {
407
+ return __awaiter(this, void 0, void 0, function* () {
408
+ return yield this.sign(web3, address, message, profileTypes);
409
+ });
410
+ }
411
+ statement(web3, address, message) {
412
+ return __awaiter(this, void 0, void 0, function* () {
413
+ return yield this.sign(web3, address, message, statementTypes);
414
+ });
415
+ }
416
+ alias(web3, address, message) {
417
+ return __awaiter(this, void 0, void 0, function* () {
418
+ return yield this.sign(web3, address, message, aliasTypes);
419
+ });
420
+ }
421
+ deleteSpace(web3, address, message) {
422
+ return __awaiter(this, void 0, void 0, function* () {
423
+ return yield this.sign(web3, address, message, deleteSpaceType);
424
+ });
425
+ }
426
+ }
581
427
 
582
428
  var $schema = "http://json-schema.org/draft-07/schema#";
583
429
  var $ref = "#/definitions/Space";
@@ -1426,250 +1272,178 @@ var alias = {
1426
1272
  definitions: definitions$7
1427
1273
  };
1428
1274
 
1429
- var schemas = {
1430
- space: space.definitions.Space,
1431
- proposal: proposal.definitions.Proposal,
1432
- updateProposal: updateProposal.definitions.UpdateProposal,
1433
- vote: vote.definitions.Vote,
1434
- profile: profile.definitions.Profile,
1435
- statement: statement.definitions.Statement,
1436
- zodiac: zodiac.definitions.Zodiac,
1437
- alias: alias.definitions.Alias
1275
+ var schemas = {
1276
+ space: space.definitions.Space,
1277
+ proposal: proposal.definitions.Proposal,
1278
+ updateProposal: updateProposal.definitions.UpdateProposal,
1279
+ vote: vote.definitions.Vote,
1280
+ profile: profile.definitions.Profile,
1281
+ statement: statement.definitions.Statement,
1282
+ zodiac: zodiac.definitions.Zodiac,
1283
+ alias: alias.definitions.Alias
1438
1284
  };
1439
1285
 
1440
- var Multicaller = /** @class */ (function () {
1441
- function Multicaller(network, provider, abi, options) {
1442
- this.options = {};
1443
- this.calls = [];
1444
- this.paths = [];
1445
- this.network = network;
1446
- this.provider = provider;
1447
- this.abi = abi;
1448
- this.options = options || {};
1449
- }
1450
- Multicaller.prototype.call = function (path, address, fn, params) {
1451
- this.calls.push([address, fn, params]);
1452
- this.paths.push(path);
1453
- return this;
1454
- };
1455
- Multicaller.prototype.execute = function (from) {
1456
- return __awaiter(this, void 0, void 0, function () {
1457
- var obj, result;
1458
- var _this = this;
1459
- return __generator(this, function (_a) {
1460
- switch (_a.label) {
1461
- case 0:
1462
- obj = from || {};
1463
- return [4 /*yield*/, multicall(this.network, this.provider, this.abi, this.calls, this.options)];
1464
- case 1:
1465
- result = _a.sent();
1466
- result.forEach(function (r, i) { return set(obj, _this.paths[i], r.length > 1 ? r : r[0]); });
1467
- this.calls = [];
1468
- this.paths = [];
1469
- return [2 /*return*/, obj];
1470
- }
1471
- });
1472
- });
1473
- };
1474
- return Multicaller;
1475
- }());
1286
+ class Multicaller {
1287
+ constructor(network, provider, abi, options) {
1288
+ this.options = {};
1289
+ this.calls = [];
1290
+ this.paths = [];
1291
+ this.network = network;
1292
+ this.provider = provider;
1293
+ this.abi = abi;
1294
+ this.options = options || {};
1295
+ }
1296
+ call(path, address, fn, params) {
1297
+ this.calls.push([address, fn, params]);
1298
+ this.paths.push(path);
1299
+ return this;
1300
+ }
1301
+ execute(from) {
1302
+ return __awaiter(this, void 0, void 0, function* () {
1303
+ const obj = from || {};
1304
+ const result = yield multicall(this.network, this.provider, this.abi, this.calls, this.options);
1305
+ result.forEach((r, i) => set(obj, this.paths[i], r.length > 1 ? r : r[0]));
1306
+ this.calls = [];
1307
+ this.paths = [];
1308
+ return obj;
1309
+ });
1310
+ }
1311
+ }
1476
1312
 
1477
- var cache = {};
1478
- var expirationTime = 0;
1479
- function getSnapshots(network, snapshot, provider, networks, options) {
1480
- if (options === void 0) { options = {}; }
1481
- return __awaiter(this, void 0, void 0, function () {
1482
- var snapshots, cacheKey, cachedEntry, now, networkIn, block, query, url, data;
1483
- return __generator(this, function (_a) {
1484
- switch (_a.label) {
1485
- case 0:
1486
- snapshots = {};
1487
- networks.forEach(function (n) { return (snapshots[n] = 'latest'); });
1488
- if (snapshot === 'latest')
1489
- return [2 /*return*/, snapshots];
1490
- cacheKey = network + "-" + snapshot + "-" + networks.join('-');
1491
- cachedEntry = cache[cacheKey];
1492
- now = Date.now();
1493
- if (cachedEntry && expirationTime > now) {
1494
- return [2 /*return*/, cachedEntry];
1495
- }
1496
- // Reset cache every hour
1497
- if (expirationTime < now) {
1498
- cache = {};
1499
- // Set expiration time to next hour
1500
- expirationTime = now + 60 * 60 * 1000 - (now % (60 * 60 * 1000));
1501
- }
1502
- snapshots[network] = snapshot;
1503
- networkIn = Object.keys(snapshots).filter(function (s) { return network !== s; });
1504
- if (networkIn.length === 0)
1505
- return [2 /*return*/, snapshots];
1506
- return [4 /*yield*/, provider.getBlock(snapshot)];
1507
- case 1:
1508
- block = _a.sent();
1509
- query = {
1510
- blocks: {
1511
- __args: {
1512
- where: {
1513
- ts: block.timestamp,
1514
- network_in: networkIn
1515
- }
1516
- },
1517
- network: true,
1518
- number: true
1519
- }
1520
- };
1521
- url = options.blockFinderUrl || 'https://blockfinder.snapshot.org';
1522
- return [4 /*yield*/, subgraphRequest(url, query)];
1523
- case 2:
1524
- data = _a.sent();
1525
- data.blocks.forEach(function (block) { return (snapshots[block.network] = block.number); });
1526
- cache[cacheKey] = snapshots;
1527
- return [2 /*return*/, snapshots];
1528
- }
1529
- });
1530
- });
1313
+ let cache = {};
1314
+ let expirationTime = 0;
1315
+ function getSnapshots(network_1, snapshot_1, provider_1, networks_1) {
1316
+ return __awaiter(this, arguments, void 0, function* (network, snapshot, provider, networks, options = {}) {
1317
+ // If snapshot is latest, return all latest
1318
+ const snapshots = {};
1319
+ networks.forEach((n) => (snapshots[n] = 'latest'));
1320
+ if (snapshot === 'latest')
1321
+ return snapshots;
1322
+ // Check if cache is valid
1323
+ const cacheKey = `${network}-${snapshot}-${networks.join('-')}`;
1324
+ const cachedEntry = cache[cacheKey];
1325
+ const now = Date.now();
1326
+ if (cachedEntry && expirationTime > now) {
1327
+ return cachedEntry;
1328
+ }
1329
+ // Reset cache every hour
1330
+ if (expirationTime < now) {
1331
+ cache = {};
1332
+ // Set expiration time to next hour
1333
+ expirationTime = now + 60 * 60 * 1000 - (now % (60 * 60 * 1000));
1334
+ }
1335
+ snapshots[network] = snapshot;
1336
+ const networkIn = Object.keys(snapshots).filter((s) => network !== s);
1337
+ if (networkIn.length === 0)
1338
+ return snapshots;
1339
+ const block = yield provider.getBlock(snapshot);
1340
+ const query = {
1341
+ blocks: {
1342
+ __args: {
1343
+ where: {
1344
+ ts: block.timestamp,
1345
+ network_in: networkIn
1346
+ }
1347
+ },
1348
+ network: true,
1349
+ number: true
1350
+ }
1351
+ };
1352
+ const url = options.blockFinderUrl || 'https://blockfinder.snapshot.org';
1353
+ const data = yield subgraphRequest(url, query);
1354
+ data.blocks.forEach((block) => (snapshots[block.network] = block.number));
1355
+ cache[cacheKey] = snapshots;
1356
+ return snapshots;
1357
+ });
1531
1358
  }
1532
1359
 
1533
- var providers = {};
1534
- function getProvider(network, _a) {
1535
- var _b = (_a === void 0 ? {} : _a).broviderUrl, broviderUrl = _b === void 0 ? 'https://rpc.snapshot.org' : _b;
1536
- var url = broviderUrl + "/" + network;
1537
- if (!providers[network])
1538
- providers[network] = new StaticJsonRpcProvider({
1539
- url: url,
1540
- timeout: 25000,
1541
- allowGzip: true
1542
- }, Number(network));
1543
- return providers[network];
1360
+ const providers = {};
1361
+ function getProvider(network, { broviderUrl = 'https://rpc.snapshot.org' } = {}) {
1362
+ const url = `${broviderUrl}/${network}`;
1363
+ if (!providers[network])
1364
+ providers[network] = new StaticJsonRpcProvider({
1365
+ url,
1366
+ timeout: 25000,
1367
+ allowGzip: true
1368
+ }, Number(network));
1369
+ return providers[network];
1544
1370
  }
1545
1371
 
1546
- function signMessage(web3, msg, address) {
1547
- return __awaiter(this, void 0, void 0, function () {
1548
- return __generator(this, function (_a) {
1549
- switch (_a.label) {
1550
- case 0:
1551
- msg = hexlify(new Buffer(msg, 'utf8'));
1552
- return [4 /*yield*/, web3.send('personal_sign', [msg, address])];
1553
- case 1: return [2 /*return*/, _a.sent()];
1554
- }
1555
- });
1556
- });
1557
- }
1558
- function getBlockNumber(provider) {
1559
- return __awaiter(this, void 0, void 0, function () {
1560
- var blockNumber, e_1;
1561
- return __generator(this, function (_a) {
1562
- switch (_a.label) {
1563
- case 0:
1564
- _a.trys.push([0, 2, , 3]);
1565
- return [4 /*yield*/, provider.getBlockNumber()];
1566
- case 1:
1567
- blockNumber = _a.sent();
1568
- return [2 /*return*/, parseInt(blockNumber)];
1569
- case 2:
1570
- e_1 = _a.sent();
1571
- return [2 /*return*/, Promise.reject()];
1572
- case 3: return [2 /*return*/];
1573
- }
1574
- });
1575
- });
1372
+ function signMessage(web3, msg, address) {
1373
+ return __awaiter(this, void 0, void 0, function* () {
1374
+ msg = hexlify(new Buffer(msg, 'utf8'));
1375
+ return yield web3.send('personal_sign', [msg, address]);
1376
+ });
1377
+ }
1378
+ function getBlockNumber(provider) {
1379
+ return __awaiter(this, void 0, void 0, function* () {
1380
+ try {
1381
+ const blockNumber = yield provider.getBlockNumber();
1382
+ return parseInt(blockNumber);
1383
+ }
1384
+ catch (e) {
1385
+ return Promise.reject();
1386
+ }
1387
+ });
1576
1388
  }
1577
1389
 
1578
- function verifyDefault(address, sig, hash, provider) {
1579
- return __awaiter(this, void 0, void 0, function () {
1580
- var returnValue, magicValue, abi, e_1;
1581
- return __generator(this, function (_a) {
1582
- switch (_a.label) {
1583
- case 0:
1584
- magicValue = '0x1626ba7e';
1585
- abi = 'function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue)';
1586
- _a.label = 1;
1587
- case 1:
1588
- _a.trys.push([1, 3, , 4]);
1589
- return [4 /*yield*/, call(provider, [abi], [address, 'isValidSignature', [arrayify(hash), sig]])];
1590
- case 2:
1591
- returnValue = _a.sent();
1592
- return [3 /*break*/, 4];
1593
- case 3:
1594
- e_1 = _a.sent();
1595
- // @ts-ignore
1596
- if (e_1.message.startsWith('missing revert data in call exception')) {
1597
- return [2 /*return*/, false];
1598
- }
1599
- throw e_1;
1600
- case 4: return [2 /*return*/, returnValue.toLowerCase() === magicValue.toLowerCase()];
1601
- }
1602
- });
1603
- });
1604
- }
1605
- function verifyOldVersion(address, sig, hash, provider) {
1606
- return __awaiter(this, void 0, void 0, function () {
1607
- var magicValue, abi, returnValue;
1608
- return __generator(this, function (_a) {
1609
- switch (_a.label) {
1610
- case 0:
1611
- magicValue = '0x20c13b0b';
1612
- abi = 'function isValidSignature(bytes _hash, bytes memory _signature) public view returns (bytes4 magicValue)';
1613
- return [4 /*yield*/, call(provider, [abi], [address, 'isValidSignature', [arrayify(hash), sig]])];
1614
- case 1:
1615
- returnValue = _a.sent();
1616
- return [2 /*return*/, returnValue.toLowerCase() === magicValue.toLowerCase()];
1617
- }
1618
- });
1619
- });
1620
- }
1621
- function verify(address, sig, hash, network, options) {
1622
- if (network === void 0) { network = '1'; }
1623
- if (options === void 0) { options = {}; }
1624
- return __awaiter(this, void 0, void 0, function () {
1625
- var provider;
1626
- return __generator(this, function (_a) {
1627
- switch (_a.label) {
1628
- case 0:
1629
- provider = getProvider(network, options);
1630
- return [4 /*yield*/, verifyDefault(address, sig, hash, provider)];
1631
- case 1:
1632
- if (_a.sent())
1633
- return [2 /*return*/, true];
1634
- return [4 /*yield*/, verifyOldVersion(address, sig, hash, provider)];
1635
- case 2: return [2 /*return*/, _a.sent()];
1636
- }
1637
- });
1638
- });
1390
+ function verifyDefault(address, sig, hash, provider) {
1391
+ return __awaiter(this, void 0, void 0, function* () {
1392
+ let returnValue;
1393
+ const magicValue = '0x1626ba7e';
1394
+ const abi = 'function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue)';
1395
+ try {
1396
+ returnValue = yield call(provider, [abi], [address, 'isValidSignature', [arrayify(hash), sig]]);
1397
+ }
1398
+ catch (e) {
1399
+ // @ts-ignore
1400
+ if (e.message.startsWith('missing revert data in call exception')) {
1401
+ return false;
1402
+ }
1403
+ throw e;
1404
+ }
1405
+ return returnValue.toLowerCase() === magicValue.toLowerCase();
1406
+ });
1407
+ }
1408
+ function verifyOldVersion(address, sig, hash, provider) {
1409
+ return __awaiter(this, void 0, void 0, function* () {
1410
+ const magicValue = '0x20c13b0b';
1411
+ const abi = 'function isValidSignature(bytes _hash, bytes memory _signature) public view returns (bytes4 magicValue)';
1412
+ const returnValue = yield call(provider, [abi], [address, 'isValidSignature', [arrayify(hash), sig]]);
1413
+ return returnValue.toLowerCase() === magicValue.toLowerCase();
1414
+ });
1415
+ }
1416
+ function verify(address_1, sig_1, hash_1) {
1417
+ return __awaiter(this, arguments, void 0, function* (address, sig, hash, network = '1', options = {}) {
1418
+ const provider = getProvider(network, options);
1419
+ if (yield verifyDefault(address, sig, hash, provider))
1420
+ return true;
1421
+ return yield verifyOldVersion(address, sig, hash, provider);
1422
+ });
1639
1423
  }
1640
1424
 
1641
- function getHash(data) {
1642
- var domain = data.domain, types = data.types, message = data.message;
1643
- return _TypedDataEncoder.hash(domain, types, message);
1644
- }
1645
- function verify$1(address, sig, data, network, options) {
1646
- if (network === void 0) { network = '1'; }
1647
- if (options === void 0) { options = {}; }
1648
- return __awaiter(this, void 0, void 0, function () {
1649
- var domain, types, message, hash, recoverAddress;
1650
- return __generator(this, function (_a) {
1651
- switch (_a.label) {
1652
- case 0:
1653
- domain = data.domain, types = data.types, message = data.message;
1654
- hash = getHash(data);
1655
- // console.log('Hash', hash);
1656
- // console.log('Address', address);
1657
- try {
1658
- recoverAddress = verifyTypedData(domain, types, message, sig);
1659
- // console.log('Recover address', recoverAddress);
1660
- if (address === recoverAddress)
1661
- return [2 /*return*/, true];
1662
- }
1663
- catch (e) {
1664
- // console.log('Could not recoverAddress:' + e.message);
1665
- }
1666
- return [4 /*yield*/, verify(address, sig, hash, network, options)];
1667
- case 1:
1668
- // console.log('Check EIP1271 signature');
1669
- return [2 /*return*/, _a.sent()];
1670
- }
1671
- });
1672
- });
1425
+ function getHash(data) {
1426
+ const { domain, types, message } = data;
1427
+ return _TypedDataEncoder.hash(domain, types, message);
1428
+ }
1429
+ function verify$1(address_1, sig_1, data_1) {
1430
+ return __awaiter(this, arguments, void 0, function* (address, sig, data, network = '1', options = {}) {
1431
+ const { domain, types, message } = data;
1432
+ const hash = getHash(data);
1433
+ // console.log('Hash', hash);
1434
+ // console.log('Address', address);
1435
+ try {
1436
+ const recoverAddress = verifyTypedData(domain, types, message, sig);
1437
+ // console.log('Recover address', recoverAddress);
1438
+ if (address === recoverAddress)
1439
+ return true;
1440
+ }
1441
+ catch (e) {
1442
+ // console.log('Could not recoverAddress:' + e.message);
1443
+ }
1444
+ // console.log('Check EIP1271 signature');
1445
+ return yield verify(address, sig, hash, network, options);
1446
+ });
1673
1447
  }
1674
1448
 
1675
1449
  var gateways = [
@@ -1834,7 +1608,7 @@ var networks = {
1834
1608
  },
1835
1609
  "56": {
1836
1610
  key: "56",
1837
- name: "Binance Smart Chain",
1611
+ name: "BNB Smart Chain",
1838
1612
  shortName: "BSC",
1839
1613
  chainId: 56,
1840
1614
  network: "mainnet",
@@ -1938,7 +1712,7 @@ var networks = {
1938
1712
  },
1939
1713
  "97": {
1940
1714
  key: "97",
1941
- name: "Binance Smart Chain Testnet",
1715
+ name: "BNB Smart Chain Testnet",
1942
1716
  shortName: "BSC Testnet",
1943
1717
  chainId: 97,
1944
1718
  network: "testnet",
@@ -3340,415 +3114,345 @@ var networks = {
3340
3114
  }
3341
3115
  };
3342
3116
 
3343
- var SingleChoiceVoting = /** @class */ (function () {
3344
- function SingleChoiceVoting(proposal, votes, strategies, selected) {
3345
- this.proposal = proposal;
3346
- this.votes = votes;
3347
- this.strategies = strategies;
3348
- this.selected = selected;
3349
- }
3350
- SingleChoiceVoting.isValidChoice = function (voteChoice, proposalChoices) {
3351
- return (typeof voteChoice === 'number' &&
3352
- (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[voteChoice - 1]) !== undefined);
3353
- };
3354
- SingleChoiceVoting.prototype.getValidVotes = function () {
3355
- var _this = this;
3356
- return this.votes.filter(function (vote) {
3357
- return SingleChoiceVoting.isValidChoice(vote.choice, _this.proposal.choices);
3358
- });
3359
- };
3360
- SingleChoiceVoting.prototype.getScores = function () {
3361
- var _this = this;
3362
- return this.proposal.choices.map(function (choice, i) {
3363
- var votes = _this.getValidVotes().filter(function (vote) { return vote.choice === i + 1; });
3364
- var balanceSum = votes.reduce(function (a, b) { return a + b.balance; }, 0);
3365
- return balanceSum;
3366
- });
3367
- };
3368
- SingleChoiceVoting.prototype.getScoresByStrategy = function () {
3369
- var _this = this;
3370
- return this.proposal.choices.map(function (choice, i) {
3371
- var scores = _this.strategies.map(function (strategy, sI) {
3372
- var votes = _this.getValidVotes().filter(function (vote) { return vote.choice === i + 1; });
3373
- var scoreSum = votes.reduce(function (a, b) { return a + b.scores[sI]; }, 0);
3374
- return scoreSum;
3375
- });
3376
- return scores;
3377
- });
3378
- };
3379
- SingleChoiceVoting.prototype.getScoresTotal = function () {
3380
- return this.votes.reduce(function (a, b) { return a + b.balance; }, 0);
3381
- };
3382
- SingleChoiceVoting.prototype.getChoiceString = function () {
3383
- return this.proposal.choices[this.selected - 1];
3384
- };
3385
- return SingleChoiceVoting;
3386
- }());
3117
+ class SingleChoiceVoting {
3118
+ constructor(proposal, votes, strategies, selected) {
3119
+ this.proposal = proposal;
3120
+ this.votes = votes;
3121
+ this.strategies = strategies;
3122
+ this.selected = selected;
3123
+ }
3124
+ static isValidChoice(voteChoice, proposalChoices) {
3125
+ return (typeof voteChoice === 'number' &&
3126
+ (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[voteChoice - 1]) !== undefined);
3127
+ }
3128
+ getValidVotes() {
3129
+ return this.votes.filter((vote) => SingleChoiceVoting.isValidChoice(vote.choice, this.proposal.choices));
3130
+ }
3131
+ getScores() {
3132
+ return this.proposal.choices.map((choice, i) => {
3133
+ const votes = this.getValidVotes().filter((vote) => vote.choice === i + 1);
3134
+ const balanceSum = votes.reduce((a, b) => a + b.balance, 0);
3135
+ return balanceSum;
3136
+ });
3137
+ }
3138
+ getScoresByStrategy() {
3139
+ return this.proposal.choices.map((choice, i) => {
3140
+ const scores = this.strategies.map((strategy, sI) => {
3141
+ const votes = this.getValidVotes().filter((vote) => vote.choice === i + 1);
3142
+ const scoreSum = votes.reduce((a, b) => a + b.scores[sI], 0);
3143
+ return scoreSum;
3144
+ });
3145
+ return scores;
3146
+ });
3147
+ }
3148
+ getScoresTotal() {
3149
+ return this.votes.reduce((a, b) => a + b.balance, 0);
3150
+ }
3151
+ getChoiceString() {
3152
+ return this.proposal.choices[this.selected - 1];
3153
+ }
3154
+ }
3387
3155
 
3388
- var ApprovalVoting = /** @class */ (function () {
3389
- function ApprovalVoting(proposal, votes, strategies, selected) {
3390
- this.proposal = proposal;
3391
- this.votes = votes;
3392
- this.strategies = strategies;
3393
- this.selected = selected;
3394
- }
3395
- ApprovalVoting.isValidChoice = function (voteChoice, proposalChoices) {
3396
- return (Array.isArray(voteChoice) &&
3397
- // If voteChoice index is not in proposalChoices, return false
3398
- voteChoice.every(function (choice) { return (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[choice - 1]) !== undefined; }) &&
3399
- // If any voteChoice is duplicated, return false
3400
- voteChoice.length === new Set(voteChoice).size);
3401
- };
3402
- ApprovalVoting.prototype.getValidVotes = function () {
3403
- var _this = this;
3404
- return this.votes.filter(function (vote) {
3405
- return ApprovalVoting.isValidChoice(vote.choice, _this.proposal.choices);
3406
- });
3407
- };
3408
- ApprovalVoting.prototype.getScores = function () {
3409
- var _this = this;
3410
- return this.proposal.choices.map(function (choice, i) {
3411
- return _this.getValidVotes()
3412
- .filter(function (vote) { return vote.choice.includes(i + 1); })
3413
- .reduce(function (a, b) { return a + b.balance; }, 0);
3414
- });
3415
- };
3416
- ApprovalVoting.prototype.getScoresByStrategy = function () {
3417
- var _this = this;
3418
- return this.proposal.choices.map(function (choice, i) {
3419
- return _this.strategies.map(function (strategy, sI) {
3420
- return _this.getValidVotes()
3421
- .filter(function (vote) { return vote.choice.includes(i + 1); })
3422
- .reduce(function (a, b) { return a + b.scores[sI]; }, 0);
3423
- });
3424
- });
3425
- };
3426
- ApprovalVoting.prototype.getScoresTotal = function () {
3427
- return this.votes.reduce(function (a, b) { return a + b.balance; }, 0);
3428
- };
3429
- ApprovalVoting.prototype.getChoiceString = function () {
3430
- var _this = this;
3431
- if (!this.selected)
3432
- return '';
3433
- return this.proposal.choices
3434
- .filter(function (choice, i) { return _this.selected.includes(i + 1); })
3435
- .join(', ');
3436
- };
3437
- return ApprovalVoting;
3438
- }());
3156
+ class ApprovalVoting {
3157
+ constructor(proposal, votes, strategies, selected) {
3158
+ this.proposal = proposal;
3159
+ this.votes = votes;
3160
+ this.strategies = strategies;
3161
+ this.selected = selected;
3162
+ }
3163
+ static isValidChoice(voteChoice, proposalChoices) {
3164
+ return (Array.isArray(voteChoice) &&
3165
+ // If voteChoice index is not in proposalChoices, return false
3166
+ voteChoice.every((choice) => (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[choice - 1]) !== undefined) &&
3167
+ // If any voteChoice is duplicated, return false
3168
+ voteChoice.length === new Set(voteChoice).size);
3169
+ }
3170
+ getValidVotes() {
3171
+ return this.votes.filter((vote) => ApprovalVoting.isValidChoice(vote.choice, this.proposal.choices));
3172
+ }
3173
+ getScores() {
3174
+ return this.proposal.choices.map((choice, i) => this.getValidVotes()
3175
+ .filter((vote) => vote.choice.includes(i + 1))
3176
+ .reduce((a, b) => a + b.balance, 0));
3177
+ }
3178
+ getScoresByStrategy() {
3179
+ return this.proposal.choices.map((choice, i) => this.strategies.map((strategy, sI) => this.getValidVotes()
3180
+ .filter((vote) => vote.choice.includes(i + 1))
3181
+ .reduce((a, b) => a + b.scores[sI], 0)));
3182
+ }
3183
+ getScoresTotal() {
3184
+ return this.votes.reduce((a, b) => a + b.balance, 0);
3185
+ }
3186
+ getChoiceString() {
3187
+ if (!this.selected)
3188
+ return '';
3189
+ return this.proposal.choices
3190
+ .filter((choice, i) => this.selected.includes(i + 1))
3191
+ .join(', ');
3192
+ }
3193
+ }
3439
3194
 
3440
- function calcPercentageOfSum(part, wholeArray) {
3441
- var whole = wholeArray.reduce(function (a, b) { return a + b; }, 0);
3442
- var percent = part / whole;
3443
- return isNaN(percent) ? 0 : percent;
3444
- }
3445
- function calcSqrt(percentageWeight, votingPower) {
3446
- return Math.sqrt(percentageWeight * votingPower);
3447
- }
3448
- function calcSquare(num) {
3449
- return num * num;
3450
- }
3451
- function calcReducedQuadraticScores(percentages, scoresTotal) {
3452
- // Reduce each quadratic score so that the sum of quadratic scores matches
3453
- // the total scores.
3454
- // This is done to unsure that features like quorum still work as expected.
3455
- return percentages.map(function (p) { return scoresTotal * p; });
3456
- }
3457
- var QuadraticVoting = /** @class */ (function () {
3458
- function QuadraticVoting(proposal, votes, strategies, selected) {
3459
- this.proposal = proposal;
3460
- this.votes = votes;
3461
- this.strategies = strategies;
3462
- this.selected = selected;
3463
- }
3464
- QuadraticVoting.isValidChoice = function (voteChoice, proposalChoices) {
3465
- return (typeof voteChoice === 'object' &&
3466
- !Array.isArray(voteChoice) &&
3467
- voteChoice !== null &&
3468
- // If voteChoice object keys are not in choices, return false
3469
- Object.keys(voteChoice).every(function (key) { return (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[Number(key) - 1]) !== undefined; }) &&
3470
- // If voteChoice object is empty, return false
3471
- Object.keys(voteChoice).length > 0 &&
3472
- // If voteChoice object values have a negative number, return false
3473
- Object.values(voteChoice).every(function (value) { return typeof value === 'number' && value >= 0; }) &&
3474
- // If voteChoice doesn't have any positive value, return false
3475
- Object.values(voteChoice).some(function (value) { return typeof value === 'number' && value > 0; }));
3476
- };
3477
- QuadraticVoting.prototype.getValidVotes = function () {
3478
- var _this = this;
3479
- return this.votes.filter(function (vote) {
3480
- return QuadraticVoting.isValidChoice(vote.choice, _this.proposal.choices);
3481
- });
3482
- };
3483
- QuadraticVoting.prototype.getScores = function () {
3484
- var validVotes = this.getValidVotes();
3485
- var scoresTotal = this.getValidVotes().reduce(function (a, b) { return a + b.balance; }, 0);
3486
- var quadraticScores = this.proposal.choices.map(function (_, i) {
3487
- var votingPowerSqrt = validVotes
3488
- .map(function (vote) {
3489
- var choiceWeightPercent = calcPercentageOfSum(vote.choice[i + 1], Object.values(vote.choice));
3490
- return calcSqrt(choiceWeightPercent, vote.balance);
3491
- })
3492
- .reduce(function (a, b) { return a + b; }, 0);
3493
- return calcSquare(votingPowerSqrt);
3494
- });
3495
- var percentagesOfScores = quadraticScores.map(function (_, i) {
3496
- return calcPercentageOfSum(quadraticScores[i], quadraticScores);
3497
- });
3498
- return calcReducedQuadraticScores(percentagesOfScores, scoresTotal);
3499
- };
3500
- QuadraticVoting.prototype.getScoresByStrategy = function () {
3501
- var _this = this;
3502
- var validVotes = this.getValidVotes();
3503
- var scoresTotal = this.getValidVotes().reduce(function (a, b) { return a + b.balance; }, 0);
3504
- var quadraticScoresByStrategy = this.proposal.choices
3505
- .map(function (_, i) {
3506
- return _this.strategies.map(function (_, sI) {
3507
- return validVotes
3508
- .map(function (vote) {
3509
- var choiceWeightPercentByStrategy = calcPercentageOfSum(vote.choice[i + 1], Object.values(vote.choice));
3510
- return calcSqrt(choiceWeightPercentByStrategy, vote.scores[sI]);
3511
- })
3512
- .reduce(function (a, b) { return a + b; }, 0);
3513
- });
3514
- })
3515
- .map(function (arr) { return arr.map(function (num) { return [calcSquare(num)]; }); });
3516
- var reducedQuadraticScores = quadraticScoresByStrategy.map(function (_, i) {
3517
- var percentagesOfScores = _this.strategies.map(function (_, sI) {
3518
- return calcPercentageOfSum(quadraticScoresByStrategy[i][sI][0], quadraticScoresByStrategy.flat(2));
3519
- });
3520
- return calcReducedQuadraticScores(percentagesOfScores, scoresTotal);
3521
- });
3522
- return reducedQuadraticScores;
3523
- };
3524
- QuadraticVoting.prototype.getScoresTotal = function () {
3525
- return this.votes.reduce(function (a, b) { return a + b.balance; }, 0);
3526
- };
3527
- QuadraticVoting.prototype.getChoiceString = function () {
3528
- var _this = this;
3529
- return this.proposal.choices
3530
- .map(function (choice, i) {
3531
- if (_this.selected[i + 1]) {
3532
- var percent = calcPercentageOfSum(_this.selected[i + 1], Object.values(_this.selected));
3533
- return Math.round(percent * 1000) / 10 + "% for " + choice;
3534
- }
3535
- })
3536
- .filter(function (el) { return el != null; })
3537
- .join(', ');
3538
- };
3539
- return QuadraticVoting;
3540
- }());
3195
+ function calcPercentageOfSum(part, wholeArray) {
3196
+ const whole = wholeArray.reduce((a, b) => a + b, 0);
3197
+ const percent = part / whole;
3198
+ return isNaN(percent) ? 0 : percent;
3199
+ }
3200
+ function calcSqrt(percentageWeight, votingPower) {
3201
+ return Math.sqrt(percentageWeight * votingPower);
3202
+ }
3203
+ function calcSquare(num) {
3204
+ return num * num;
3205
+ }
3206
+ function calcReducedQuadraticScores(percentages, scoresTotal) {
3207
+ // Reduce each quadratic score so that the sum of quadratic scores matches
3208
+ // the total scores.
3209
+ // This is done to unsure that features like quorum still work as expected.
3210
+ return percentages.map((p) => scoresTotal * p);
3211
+ }
3212
+ class QuadraticVoting {
3213
+ constructor(proposal, votes, strategies, selected) {
3214
+ this.proposal = proposal;
3215
+ this.votes = votes;
3216
+ this.strategies = strategies;
3217
+ this.selected = selected;
3218
+ }
3219
+ static isValidChoice(voteChoice, proposalChoices) {
3220
+ return (typeof voteChoice === 'object' &&
3221
+ !Array.isArray(voteChoice) &&
3222
+ voteChoice !== null &&
3223
+ // If voteChoice object keys are not in choices, return false
3224
+ Object.keys(voteChoice).every((key) => (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[Number(key) - 1]) !== undefined) &&
3225
+ // If voteChoice object is empty, return false
3226
+ Object.keys(voteChoice).length > 0 &&
3227
+ // If voteChoice object values have a negative number, return false
3228
+ Object.values(voteChoice).every((value) => typeof value === 'number' && value >= 0) &&
3229
+ // If voteChoice doesn't have any positive value, return false
3230
+ Object.values(voteChoice).some((value) => typeof value === 'number' && value > 0));
3231
+ }
3232
+ getValidVotes() {
3233
+ return this.votes.filter((vote) => QuadraticVoting.isValidChoice(vote.choice, this.proposal.choices));
3234
+ }
3235
+ getScores() {
3236
+ const validVotes = this.getValidVotes();
3237
+ const scoresTotal = this.getValidVotes().reduce((a, b) => a + b.balance, 0);
3238
+ const quadraticScores = this.proposal.choices.map((_, i) => {
3239
+ const votingPowerSqrt = validVotes
3240
+ .map((vote) => {
3241
+ const choiceWeightPercent = calcPercentageOfSum(vote.choice[i + 1], Object.values(vote.choice));
3242
+ return calcSqrt(choiceWeightPercent, vote.balance);
3243
+ })
3244
+ .reduce((a, b) => a + b, 0);
3245
+ return calcSquare(votingPowerSqrt);
3246
+ });
3247
+ const percentagesOfScores = quadraticScores.map((_, i) => calcPercentageOfSum(quadraticScores[i], quadraticScores));
3248
+ return calcReducedQuadraticScores(percentagesOfScores, scoresTotal);
3249
+ }
3250
+ getScoresByStrategy() {
3251
+ const validVotes = this.getValidVotes();
3252
+ const scoresTotal = this.getValidVotes().reduce((a, b) => a + b.balance, 0);
3253
+ const quadraticScoresByStrategy = this.proposal.choices
3254
+ .map((_, i) => this.strategies.map((_, sI) => validVotes
3255
+ .map((vote) => {
3256
+ const choiceWeightPercentByStrategy = calcPercentageOfSum(vote.choice[i + 1], Object.values(vote.choice));
3257
+ return calcSqrt(choiceWeightPercentByStrategy, vote.scores[sI]);
3258
+ })
3259
+ .reduce((a, b) => a + b, 0)))
3260
+ .map((arr) => arr.map((num) => [calcSquare(num)]));
3261
+ const reducedQuadraticScores = quadraticScoresByStrategy.map((_, i) => {
3262
+ const percentagesOfScores = this.strategies.map((_, sI) => calcPercentageOfSum(quadraticScoresByStrategy[i][sI][0], quadraticScoresByStrategy.flat(2)));
3263
+ return calcReducedQuadraticScores(percentagesOfScores, scoresTotal);
3264
+ });
3265
+ return reducedQuadraticScores;
3266
+ }
3267
+ getScoresTotal() {
3268
+ return this.votes.reduce((a, b) => a + b.balance, 0);
3269
+ }
3270
+ getChoiceString() {
3271
+ return this.proposal.choices
3272
+ .map((choice, i) => {
3273
+ if (this.selected[i + 1]) {
3274
+ const percent = calcPercentageOfSum(this.selected[i + 1], Object.values(this.selected));
3275
+ return `${Math.round(percent * 1000) / 10}% for ${choice}`;
3276
+ }
3277
+ })
3278
+ .filter((el) => el != null)
3279
+ .join(', ');
3280
+ }
3281
+ }
3541
3282
 
3542
- function irv(ballots, rounds) {
3543
- var candidates = __spread(new Set(ballots.map(function (vote) { return vote[0]; }).flat()));
3544
- var votes = Object.entries(ballots.reduce(function (votes, _a, i, src) {
3545
- var _b = __read(_a, 1), v = _b[0];
3546
- var balance = src[i][1];
3547
- votes[v[0]][0] += balance;
3548
- var score = src[i][2];
3549
- if (score.length > 1) {
3550
- votes[v[0]][1] = score.map(function (s, sI) { return s + votes[v[0]][1][sI] || s; });
3551
- }
3552
- else
3553
- votes[v[0]][1] = [
3554
- votes[v[0]][1].concat(score).reduce(function (a, b) { return a + b; }, 0)
3555
- ];
3556
- return votes;
3557
- }, Object.assign.apply(Object, __spread([{}], candidates.map(function (c) {
3558
- var _a;
3559
- return (_a = {}, _a[c] = [0, []], _a);
3560
- })))));
3561
- var votesWithoutScore = votes.map(function (vote) { return [vote[0], vote[1][0]]; });
3562
- /* eslint-disable @typescript-eslint/no-unused-vars */
3563
- var _a = __read(votesWithoutScore.reduce(function (_a, _b) {
3564
- var _c = __read(_a, 2), n = _c[0], m = _c[1];
3565
- var _d = __read(_b, 2), v = _d[0], c = _d[1];
3566
- return (c > m ? [v, c] : [n, m]);
3567
- }, ['?', -Infinity]), 2), topCand = _a[0], topCount = _a[1];
3568
- var _b = __read(votesWithoutScore.reduce(function (_a, _b) {
3569
- var _c = __read(_a, 2), n = _c[0], m = _c[1];
3570
- var _d = __read(_b, 2), v = _d[0], c = _d[1];
3571
- return (c < m ? [v, c] : [n, m]);
3572
- }, ['?', Infinity]), 2), bottomCand = _b[0], bottomCount = _b[1];
3573
- /* eslint-enable @typescript-eslint/no-unused-vars */
3574
- var sortedByHighest = votes.sort(function (a, b) { return b[1][0] - a[1][0]; });
3575
- var totalPowerOfVotes = ballots
3576
- .map(function (bal) { return bal[1]; })
3577
- .reduce(function (a, b) { return a + b; }, 0);
3578
- rounds.push({
3579
- round: rounds.length + 1,
3580
- sortedByHighest: sortedByHighest
3581
- });
3582
- return topCount > totalPowerOfVotes / 2 ||
3583
- sortedByHighest.length < 3
3584
- ? rounds
3585
- : irv(ballots
3586
- .map(function (ballot) { return [
3587
- ballot[0].filter(function (c) { return c != bottomCand; }),
3588
- ballot[1],
3589
- ballot[2]
3590
- ]; })
3591
- .filter(function (ballot) { return ballot[0].length > 0; }), rounds);
3592
- }
3593
- function getFinalRound(votes) {
3594
- var rounds = irv(votes.map(function (vote) { return [vote.choice, vote.balance, vote.scores]; }), []);
3595
- var finalRound = rounds[rounds.length - 1];
3596
- return finalRound.sortedByHighest;
3597
- }
3598
- function getScoresMethod(votes, proposal) {
3599
- var finalRound = getFinalRound(votes);
3600
- return proposal.choices.map(function (choice, i) {
3601
- return finalRound
3602
- .filter(function (res) { return Number(res[0]) === i + 1; })
3603
- .reduce(function (a, b) { return a + b[1][0]; }, 0);
3604
- });
3605
- }
3606
- var RankedChoiceVoting = /** @class */ (function () {
3607
- function RankedChoiceVoting(proposal, votes, strategies, selected) {
3608
- this.proposal = proposal;
3609
- this.votes = votes;
3610
- this.strategies = strategies;
3611
- this.selected = selected;
3612
- }
3613
- RankedChoiceVoting.isValidChoice = function (voteChoice, proposalChoices) {
3614
- return (Array.isArray(voteChoice) &&
3615
- // If voteChoice index is not in choices, return false
3616
- voteChoice.every(function (voteChoice) { return (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[voteChoice - 1]) !== undefined; }) &&
3617
- // If any voteChoice is duplicated, return false
3618
- voteChoice.length === new Set(voteChoice).size &&
3619
- // If voteChoice is empty, return false
3620
- voteChoice.length > 0 &&
3621
- // If not all proposalChoices are selected, return false
3622
- // TODO: We should add support for pacial bailout in the future
3623
- voteChoice.length === proposalChoices.length);
3624
- };
3625
- RankedChoiceVoting.prototype.getValidVotes = function () {
3626
- var _this = this;
3627
- return this.votes.filter(function (vote) {
3628
- return RankedChoiceVoting.isValidChoice(vote.choice, _this.proposal.choices);
3629
- });
3630
- };
3631
- RankedChoiceVoting.prototype.getScores = function () {
3632
- return getScoresMethod(this.getValidVotes(), this.proposal);
3633
- };
3634
- RankedChoiceVoting.prototype.getScoresByStrategy = function () {
3635
- var _this = this;
3636
- var finalRound = getFinalRound(this.getValidVotes());
3637
- return this.proposal.choices.map(function (choice, i) {
3638
- return _this.strategies.map(function (strategy, sI) {
3639
- return finalRound
3640
- .filter(function (res) { return Number(res[0]) === i + 1; })
3641
- .reduce(function (a, b) { return a + b[1][1][sI]; }, 0);
3642
- });
3643
- });
3644
- };
3645
- RankedChoiceVoting.prototype.getScoresTotal = function () {
3646
- return this.votes.reduce(function (a, b) { return a + b.balance; }, 0);
3647
- };
3648
- RankedChoiceVoting.prototype.getChoiceString = function () {
3649
- var _this = this;
3650
- return this.selected
3651
- .map(function (choice) {
3652
- if (_this.proposal.choices[choice - 1])
3653
- return _this.proposal.choices[choice - 1];
3654
- })
3655
- .map(function (el, i) { return "(" + getNumberWithOrdinal(i + 1) + ") " + el; })
3656
- .join(', ');
3657
- };
3658
- return RankedChoiceVoting;
3659
- }());
3283
+ function irv(ballots, rounds) {
3284
+ const candidates = [
3285
+ ...new Set(ballots.map((vote) => vote[0]).flat())
3286
+ ];
3287
+ const votes = Object.entries(ballots.reduce((votes, [v], i, src) => {
3288
+ const balance = src[i][1];
3289
+ votes[v[0]][0] += balance;
3290
+ const score = src[i][2];
3291
+ if (score.length > 1) {
3292
+ votes[v[0]][1] = score.map((s, sI) => s + votes[v[0]][1][sI] || s);
3293
+ }
3294
+ else
3295
+ votes[v[0]][1] = [
3296
+ votes[v[0]][1].concat(score).reduce((a, b) => a + b, 0)
3297
+ ];
3298
+ return votes;
3299
+ }, Object.assign({}, ...candidates.map((c) => ({ [c]: [0, []] })))));
3300
+ const votesWithoutScore = votes.map((vote) => [vote[0], vote[1][0]]);
3301
+ /* eslint-disable @typescript-eslint/no-unused-vars */
3302
+ const [topCand, topCount] = votesWithoutScore.reduce(([n, m], [v, c]) => (c > m ? [v, c] : [n, m]), ['?', -Infinity]);
3303
+ const [bottomCand, bottomCount] = votesWithoutScore.reduce(([n, m], [v, c]) => (c < m ? [v, c] : [n, m]), ['?', Infinity]);
3304
+ /* eslint-enable @typescript-eslint/no-unused-vars */
3305
+ const sortedByHighest = votes.sort((a, b) => b[1][0] - a[1][0]);
3306
+ const totalPowerOfVotes = ballots
3307
+ .map((bal) => bal[1])
3308
+ .reduce((a, b) => a + b, 0);
3309
+ rounds.push({
3310
+ round: rounds.length + 1,
3311
+ sortedByHighest
3312
+ });
3313
+ return topCount > totalPowerOfVotes / 2 ||
3314
+ sortedByHighest.length < 3
3315
+ ? rounds
3316
+ : irv(ballots
3317
+ .map((ballot) => [
3318
+ ballot[0].filter((c) => c != bottomCand),
3319
+ ballot[1],
3320
+ ballot[2]
3321
+ ])
3322
+ .filter((ballot) => ballot[0].length > 0), rounds);
3323
+ }
3324
+ function getFinalRound(votes) {
3325
+ const rounds = irv(votes.map((vote) => [vote.choice, vote.balance, vote.scores]), []);
3326
+ const finalRound = rounds[rounds.length - 1];
3327
+ return finalRound.sortedByHighest;
3328
+ }
3329
+ function getScoresMethod(votes, proposal) {
3330
+ const finalRound = getFinalRound(votes);
3331
+ return proposal.choices.map((choice, i) => finalRound
3332
+ .filter((res) => Number(res[0]) === i + 1)
3333
+ .reduce((a, b) => a + b[1][0], 0));
3334
+ }
3335
+ class RankedChoiceVoting {
3336
+ constructor(proposal, votes, strategies, selected) {
3337
+ this.proposal = proposal;
3338
+ this.votes = votes;
3339
+ this.strategies = strategies;
3340
+ this.selected = selected;
3341
+ }
3342
+ static isValidChoice(voteChoice, proposalChoices) {
3343
+ return (Array.isArray(voteChoice) &&
3344
+ // If voteChoice index is not in choices, return false
3345
+ voteChoice.every((voteChoice) => (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[voteChoice - 1]) !== undefined) &&
3346
+ // If any voteChoice is duplicated, return false
3347
+ voteChoice.length === new Set(voteChoice).size &&
3348
+ // If voteChoice is empty, return false
3349
+ voteChoice.length > 0 &&
3350
+ // If not all proposalChoices are selected, return false
3351
+ // TODO: We should add support for pacial bailout in the future
3352
+ voteChoice.length === proposalChoices.length);
3353
+ }
3354
+ getValidVotes() {
3355
+ return this.votes.filter((vote) => RankedChoiceVoting.isValidChoice(vote.choice, this.proposal.choices));
3356
+ }
3357
+ getScores() {
3358
+ return getScoresMethod(this.getValidVotes(), this.proposal);
3359
+ }
3360
+ getScoresByStrategy() {
3361
+ const finalRound = getFinalRound(this.getValidVotes());
3362
+ return this.proposal.choices.map((choice, i) => this.strategies.map((strategy, sI) => {
3363
+ return finalRound
3364
+ .filter((res) => Number(res[0]) === i + 1)
3365
+ .reduce((a, b) => a + b[1][1][sI], 0);
3366
+ }));
3367
+ }
3368
+ getScoresTotal() {
3369
+ return this.votes.reduce((a, b) => a + b.balance, 0);
3370
+ }
3371
+ getChoiceString() {
3372
+ return this.selected
3373
+ .map((choice) => {
3374
+ if (this.proposal.choices[choice - 1])
3375
+ return this.proposal.choices[choice - 1];
3376
+ })
3377
+ .map((el, i) => `(${getNumberWithOrdinal(i + 1)}) ${el}`)
3378
+ .join(', ');
3379
+ }
3380
+ }
3660
3381
 
3661
- function percentageOfTotal(i, values, total) {
3662
- var reducedTotal = total.reduce(function (a, b) { return a + b; }, 0);
3663
- var percent = (values[i] / reducedTotal) * 100;
3664
- return isNaN(percent) ? 0 : percent;
3665
- }
3666
- function weightedPower(i, choice, balance) {
3667
- return ((percentageOfTotal(i + 1, choice, Object.values(choice)) / 100) * balance);
3668
- }
3669
- var WeightedVoting = /** @class */ (function () {
3670
- function WeightedVoting(proposal, votes, strategies, selected) {
3671
- this.proposal = proposal;
3672
- this.votes = votes;
3673
- this.strategies = strategies;
3674
- this.selected = selected;
3675
- }
3676
- WeightedVoting.isValidChoice = function (voteChoice, proposalChoices) {
3677
- return (typeof voteChoice === 'object' &&
3678
- !Array.isArray(voteChoice) &&
3679
- voteChoice !== null &&
3680
- // If voteChoice object keys are not in choices, return false
3681
- Object.keys(voteChoice).every(function (key) { return (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[Number(key) - 1]) !== undefined; }) &&
3682
- // If voteChoice object is empty, return false
3683
- Object.keys(voteChoice).length > 0 &&
3684
- // If voteChoice object values have a negative number, return false
3685
- Object.values(voteChoice).every(function (value) { return typeof value === 'number' && value >= 0; }) &&
3686
- // If voteChoice doesn't have any positive value, return false
3687
- Object.values(voteChoice).some(function (value) { return typeof value === 'number' && value > 0; }));
3688
- };
3689
- WeightedVoting.prototype.getValidVotes = function () {
3690
- var _this = this;
3691
- return this.votes.filter(function (vote) {
3692
- return WeightedVoting.isValidChoice(vote.choice, _this.proposal.choices);
3693
- });
3694
- };
3695
- WeightedVoting.prototype.getScores = function () {
3696
- var _this = this;
3697
- var results = this.proposal.choices.map(function (choice, i) {
3698
- return _this.getValidVotes()
3699
- .map(function (vote) { return weightedPower(i, vote.choice, vote.balance); })
3700
- .reduce(function (a, b) { return a + b; }, 0);
3701
- });
3702
- var validScoresTotal = this.getValidVotes().reduce(function (a, b) { return a + b.balance; }, 0);
3703
- return results
3704
- .map(function (res, i) { return percentageOfTotal(i, results, results); })
3705
- .map(function (p) { return (validScoresTotal / 100) * p; });
3706
- };
3707
- WeightedVoting.prototype.getScoresByStrategy = function () {
3708
- var _this = this;
3709
- var results = this.proposal.choices
3710
- .map(function (choice, i) {
3711
- return _this.strategies.map(function (strategy, sI) {
3712
- return _this.getValidVotes()
3713
- .map(function (vote) { return weightedPower(i, vote.choice, vote.scores[sI]); })
3714
- .reduce(function (a, b) { return a + b; }, 0);
3715
- });
3716
- })
3717
- .map(function (arr) { return arr.map(function (pwr) { return [pwr]; }); });
3718
- var validScoresTotal = this.getValidVotes().reduce(function (a, b) { return a + b.balance; }, 0);
3719
- return results.map(function (res, i) {
3720
- return _this.strategies
3721
- .map(function (strategy, sI) {
3722
- return percentageOfTotal(0, results[i][sI], results.flat(2));
3723
- })
3724
- .map(function (p) { return [(validScoresTotal / 100) * p]; })
3725
- .flat();
3726
- });
3727
- };
3728
- WeightedVoting.prototype.getScoresTotal = function () {
3729
- return this.votes.reduce(function (a, b) { return a + b.balance; }, 0);
3730
- };
3731
- WeightedVoting.prototype.getChoiceString = function () {
3732
- var _this = this;
3733
- return this.proposal.choices
3734
- .map(function (choice, i) {
3735
- if (_this.selected[i + 1]) {
3736
- return Math.round(percentageOfTotal(i + 1, _this.selected, Object.values(_this.selected)) * 10) / 10 + "% for " + choice;
3737
- }
3738
- })
3739
- .filter(function (el) { return el != null; })
3740
- .join(', ');
3741
- };
3742
- return WeightedVoting;
3743
- }());
3382
+ function percentageOfTotal(i, values, total) {
3383
+ const reducedTotal = total.reduce((a, b) => a + b, 0);
3384
+ const percent = (values[i] / reducedTotal) * 100;
3385
+ return isNaN(percent) ? 0 : percent;
3386
+ }
3387
+ function weightedPower(i, choice, balance) {
3388
+ return ((percentageOfTotal(i + 1, choice, Object.values(choice)) / 100) * balance);
3389
+ }
3390
+ class WeightedVoting {
3391
+ constructor(proposal, votes, strategies, selected) {
3392
+ this.proposal = proposal;
3393
+ this.votes = votes;
3394
+ this.strategies = strategies;
3395
+ this.selected = selected;
3396
+ }
3397
+ static isValidChoice(voteChoice, proposalChoices) {
3398
+ return (typeof voteChoice === 'object' &&
3399
+ !Array.isArray(voteChoice) &&
3400
+ voteChoice !== null &&
3401
+ // If voteChoice object keys are not in choices, return false
3402
+ Object.keys(voteChoice).every((key) => (proposalChoices === null || proposalChoices === void 0 ? void 0 : proposalChoices[Number(key) - 1]) !== undefined) &&
3403
+ // If voteChoice object is empty, return false
3404
+ Object.keys(voteChoice).length > 0 &&
3405
+ // If voteChoice object values have a negative number, return false
3406
+ Object.values(voteChoice).every((value) => typeof value === 'number' && value >= 0) &&
3407
+ // If voteChoice doesn't have any positive value, return false
3408
+ Object.values(voteChoice).some((value) => typeof value === 'number' && value > 0));
3409
+ }
3410
+ getValidVotes() {
3411
+ return this.votes.filter((vote) => WeightedVoting.isValidChoice(vote.choice, this.proposal.choices));
3412
+ }
3413
+ getScores() {
3414
+ const results = this.proposal.choices.map((choice, i) => this.getValidVotes()
3415
+ .map((vote) => weightedPower(i, vote.choice, vote.balance))
3416
+ .reduce((a, b) => a + b, 0));
3417
+ const validScoresTotal = this.getValidVotes().reduce((a, b) => a + b.balance, 0);
3418
+ return results
3419
+ .map((res, i) => percentageOfTotal(i, results, results))
3420
+ .map((p) => (validScoresTotal / 100) * p);
3421
+ }
3422
+ getScoresByStrategy() {
3423
+ const results = this.proposal.choices
3424
+ .map((choice, i) => this.strategies.map((strategy, sI) => this.getValidVotes()
3425
+ .map((vote) => weightedPower(i, vote.choice, vote.scores[sI]))
3426
+ .reduce((a, b) => a + b, 0)))
3427
+ .map((arr) => arr.map((pwr) => [pwr]));
3428
+ const validScoresTotal = this.getValidVotes().reduce((a, b) => a + b.balance, 0);
3429
+ return results.map((res, i) => this.strategies
3430
+ .map((strategy, sI) => percentageOfTotal(0, results[i][sI], results.flat(2)))
3431
+ .map((p) => [(validScoresTotal / 100) * p])
3432
+ .flat());
3433
+ }
3434
+ getScoresTotal() {
3435
+ return this.votes.reduce((a, b) => a + b.balance, 0);
3436
+ }
3437
+ getChoiceString() {
3438
+ return this.proposal.choices
3439
+ .map((choice, i) => {
3440
+ if (this.selected[i + 1]) {
3441
+ return `${Math.round(percentageOfTotal(i + 1, this.selected, Object.values(this.selected)) * 10) / 10}% for ${choice}`;
3442
+ }
3443
+ })
3444
+ .filter((el) => el != null)
3445
+ .join(', ');
3446
+ }
3447
+ }
3744
3448
 
3745
- var voting = {
3746
- 'single-choice': SingleChoiceVoting,
3747
- approval: ApprovalVoting,
3748
- quadratic: QuadraticVoting,
3749
- 'ranked-choice': RankedChoiceVoting,
3750
- weighted: WeightedVoting,
3751
- basic: SingleChoiceVoting
3449
+ var voting = {
3450
+ 'single-choice': SingleChoiceVoting,
3451
+ approval: ApprovalVoting,
3452
+ quadratic: QuadraticVoting,
3453
+ 'ranked-choice': RankedChoiceVoting,
3454
+ weighted: WeightedVoting,
3455
+ basic: SingleChoiceVoting
3752
3456
  };
3753
3457
 
3754
3458
  var delegationSubgraphs = {
@@ -3762,771 +3466,618 @@ var delegationSubgraphs = {
3762
3466
  "11155111": "https://subgrapher.snapshot.org/delegation/11155111"
3763
3467
  };
3764
3468
 
3765
- var SNAPSHOT_SUBGRAPH_URL = delegationSubgraphs;
3766
- var PAGE_SIZE = 1000;
3767
- function getDelegatesBySpace(network, space, snapshot, options) {
3768
- if (snapshot === void 0) { snapshot = 'latest'; }
3769
- if (options === void 0) { options = {}; }
3770
- return __awaiter(this, void 0, void 0, function () {
3771
- var subgraphUrl, pivot, result, spaceIn, newResults;
3772
- return __generator(this, function (_a) {
3773
- switch (_a.label) {
3774
- case 0:
3775
- subgraphUrl = options.subgraphUrl || SNAPSHOT_SUBGRAPH_URL[network];
3776
- if (!subgraphUrl) {
3777
- return [2 /*return*/, Promise.reject("Delegation subgraph not available for network " + network)];
3778
- }
3779
- pivot = 0;
3780
- result = new Map();
3781
- spaceIn = buildSpaceIn(space);
3782
- _a.label = 1;
3783
- case 1:
3784
- return [4 /*yield*/, fetchData({
3785
- url: subgraphUrl,
3786
- spaces: spaceIn,
3787
- pivot: pivot,
3788
- snapshot: snapshot
3789
- })];
3790
- case 2:
3791
- newResults = _a.sent();
3792
- if (checkAllDuplicates(newResults)) {
3793
- throw new Error('Unable to paginate delegation');
3794
- }
3795
- newResults.forEach(function (delegation) {
3796
- concatUniqueDelegation(result, delegation);
3797
- pivot = delegation.timestamp;
3798
- });
3799
- if (newResults.length < PAGE_SIZE)
3800
- return [3 /*break*/, 3];
3801
- return [3 /*break*/, 1];
3802
- case 3: return [2 /*return*/, __spread(result.values())];
3803
- }
3804
- });
3805
- });
3806
- }
3807
- function checkAllDuplicates(delegations) {
3808
- return (delegations.length === PAGE_SIZE &&
3809
- delegations[0].timestamp === delegations[delegations.length - 1].timestamp);
3810
- }
3811
- function delegationKey(delegation) {
3812
- return delegation.delegator + "-" + delegation.delegate + "-" + delegation.space;
3813
- }
3814
- function concatUniqueDelegation(result, delegation) {
3815
- var key = delegationKey(delegation);
3816
- if (!result.has(key)) {
3817
- result.set(key, delegation);
3818
- }
3819
- }
3820
- function buildSpaceIn(space) {
3821
- var spaces = ['', space];
3822
- if (space.includes('.eth'))
3823
- spaces.push(space.replace('.eth', ''));
3824
- return spaces;
3825
- }
3826
- function fetchData(_a) {
3827
- var url = _a.url, spaces = _a.spaces, pivot = _a.pivot, snapshot = _a.snapshot;
3828
- return __awaiter(this, void 0, void 0, function () {
3829
- var params;
3830
- return __generator(this, function (_b) {
3831
- switch (_b.label) {
3832
- case 0:
3833
- params = {
3834
- delegations: {
3835
- __args: {
3836
- where: {
3837
- space_in: spaces,
3838
- timestamp_gte: pivot
3839
- },
3840
- first: PAGE_SIZE,
3841
- skip: 0,
3842
- orderBy: 'timestamp',
3843
- orderDirection: 'asc'
3844
- },
3845
- delegator: true,
3846
- space: true,
3847
- delegate: true,
3848
- timestamp: true
3849
- }
3850
- };
3851
- if (snapshot !== 'latest') {
3852
- params.delegations.__args.block = { number: snapshot };
3853
- }
3854
- return [4 /*yield*/, subgraphRequest(url, params)];
3855
- case 1: return [2 /*return*/, (_b.sent()).delegations || []];
3856
- }
3857
- });
3858
- });
3469
+ const SNAPSHOT_SUBGRAPH_URL = delegationSubgraphs;
3470
+ const PAGE_SIZE = 1000;
3471
+ function getDelegatesBySpace(network_1, space_1) {
3472
+ return __awaiter(this, arguments, void 0, function* (network, space, snapshot = 'latest', options = {}) {
3473
+ const subgraphUrl = options.subgraphUrl || SNAPSHOT_SUBGRAPH_URL[network];
3474
+ if (!subgraphUrl) {
3475
+ return Promise.reject(`Delegation subgraph not available for network ${network}`);
3476
+ }
3477
+ let pivot = 0;
3478
+ const result = new Map();
3479
+ const spaceIn = buildSpaceIn(space);
3480
+ while (true) {
3481
+ const newResults = yield fetchData({
3482
+ url: subgraphUrl,
3483
+ spaces: spaceIn,
3484
+ pivot,
3485
+ snapshot
3486
+ });
3487
+ if (checkAllDuplicates(newResults)) {
3488
+ throw new Error('Unable to paginate delegation');
3489
+ }
3490
+ newResults.forEach((delegation) => {
3491
+ concatUniqueDelegation(result, delegation);
3492
+ pivot = delegation.timestamp;
3493
+ });
3494
+ if (newResults.length < PAGE_SIZE)
3495
+ break;
3496
+ }
3497
+ return [...result.values()];
3498
+ });
3499
+ }
3500
+ function checkAllDuplicates(delegations) {
3501
+ return (delegations.length === PAGE_SIZE &&
3502
+ delegations[0].timestamp === delegations[delegations.length - 1].timestamp);
3503
+ }
3504
+ function delegationKey(delegation) {
3505
+ return `${delegation.delegator}-${delegation.delegate}-${delegation.space}`;
3506
+ }
3507
+ function concatUniqueDelegation(result, delegation) {
3508
+ const key = delegationKey(delegation);
3509
+ if (!result.has(key)) {
3510
+ result.set(key, delegation);
3511
+ }
3512
+ }
3513
+ function buildSpaceIn(space) {
3514
+ const spaces = ['', space];
3515
+ if (space.includes('.eth'))
3516
+ spaces.push(space.replace('.eth', ''));
3517
+ return spaces;
3518
+ }
3519
+ function fetchData(_a) {
3520
+ return __awaiter(this, arguments, void 0, function* ({ url, spaces, pivot, snapshot }) {
3521
+ const params = {
3522
+ delegations: {
3523
+ __args: {
3524
+ where: {
3525
+ space_in: spaces,
3526
+ timestamp_gte: pivot
3527
+ },
3528
+ first: PAGE_SIZE,
3529
+ skip: 0,
3530
+ orderBy: 'timestamp',
3531
+ orderDirection: 'asc'
3532
+ },
3533
+ delegator: true,
3534
+ space: true,
3535
+ delegate: true,
3536
+ timestamp: true
3537
+ }
3538
+ };
3539
+ if (snapshot !== 'latest') {
3540
+ params.delegations.__args.block = { number: snapshot };
3541
+ }
3542
+ return (yield subgraphRequest(url, params)).delegations || [];
3543
+ });
3859
3544
  }
3860
3545
 
3861
- var ENS_RESOLVER_ABI = [
3862
- 'function text(bytes32 node, string calldata key) external view returns (string memory)'
3863
- ];
3864
- var EMPTY_ADDRESS = '0x0000000000000000000000000000000000000000';
3865
- var scoreApiHeaders = {
3866
- Accept: 'application/json',
3867
- 'Content-Type': 'application/json'
3868
- };
3869
- var DEFAULT_SCORE_API_URL = 'https://score.snapshot.org';
3870
- function formatScoreAPIUrl(url, options) {
3871
- if (url === void 0) { url = DEFAULT_SCORE_API_URL; }
3872
- if (options === void 0) { options = {
3873
- path: ''
3874
- }; }
3875
- var scoreURL = new URL(url);
3876
- if (options.path)
3877
- scoreURL.pathname = options.path;
3878
- var apiKey = scoreURL.searchParams.get('apiKey');
3879
- var headers = __assign({}, scoreApiHeaders);
3880
- if (apiKey) {
3881
- scoreURL.searchParams.delete('apiKey');
3882
- headers = __assign(__assign({}, scoreApiHeaders), { 'X-API-KEY': apiKey });
3883
- }
3884
- return {
3885
- url: scoreURL.toString(),
3886
- headers: headers
3887
- };
3888
- }
3889
- function parseScoreAPIResponse(res) {
3890
- return __awaiter(this, void 0, void 0, function () {
3891
- var data;
3892
- return __generator(this, function (_a) {
3893
- switch (_a.label) {
3894
- case 0: return [4 /*yield*/, res.text()];
3895
- case 1:
3896
- data = _a.sent();
3897
- try {
3898
- data = JSON.parse(data);
3899
- }
3900
- catch (e) {
3901
- return [2 /*return*/, Promise.reject({
3902
- code: res.status || 500,
3903
- message: 'Failed to parse response from score API',
3904
- data: data
3905
- })];
3906
- }
3907
- if (data.error)
3908
- return [2 /*return*/, Promise.reject(data.error)];
3909
- return [2 /*return*/, data];
3910
- }
3911
- });
3912
- });
3913
- }
3914
- var ajv = new Ajv({
3915
- allErrors: true,
3916
- allowUnionTypes: true,
3917
- $data: true,
3918
- passContext: true
3919
- });
3920
- // @ts-ignore
3921
- addFormats(ajv);
3922
- addErrors(ajv);
3923
- ajv.addFormat('address', {
3924
- validate: function (value) {
3925
- try {
3926
- return isAddress(value);
3927
- }
3928
- catch (err) {
3929
- return false;
3930
- }
3931
- }
3932
- });
3933
- ajv.addFormat('evmOrStarknetAddress', {
3934
- validate: function (value) {
3935
- try {
3936
- return isAddress(value) || /^0x[0-9a-fA-F]{62,64}$/.test(value);
3937
- }
3938
- catch (err) {
3939
- return false;
3940
- }
3941
- }
3942
- });
3943
- ajv.addFormat('long', {
3944
- validate: function () { return true; }
3945
- });
3946
- ajv.addFormat('ethValue', {
3947
- validate: function (value) {
3948
- if (!value.match(/^([0-9]|[1-9][0-9]+)(\.[0-9]+)?$/))
3949
- return false;
3950
- try {
3951
- parseUnits(value, 18);
3952
- return true;
3953
- }
3954
- catch (_a) {
3955
- return false;
3956
- }
3957
- }
3958
- });
3959
- var networksIds = Object.keys(networks);
3960
- var mainnetNetworkIds = Object.keys(networks).filter(function (id) { return !networks[id].testnet; });
3961
- ajv.addKeyword({
3962
- keyword: 'snapshotNetwork',
3963
- validate: function (schema, data) {
3964
- // @ts-ignore
3965
- var snapshotEnv = this.snapshotEnv || 'default';
3966
- if (snapshotEnv === 'mainnet')
3967
- return mainnetNetworkIds.includes(data);
3968
- return networksIds.includes(data);
3969
- },
3970
- error: {
3971
- message: 'network not allowed'
3972
- }
3973
- });
3974
- ajv.addKeyword({
3975
- keyword: 'maxLengthWithSpaceType',
3976
- validate: function validate(schema, data) {
3977
- // @ts-ignore
3978
- var spaceType = this.spaceType || 'default';
3979
- var isValid = data.length <= schema[spaceType];
3980
- if (!isValid) {
3981
- // @ts-ignore
3982
- validate.errors = [
3983
- {
3984
- keyword: 'maxLengthWithSpaceType',
3985
- message: "must NOT have more than " + schema[spaceType] + " characters",
3986
- params: { limit: schema[spaceType] }
3987
- }
3988
- ];
3989
- }
3990
- return isValid;
3991
- },
3992
- errors: true
3993
- });
3994
- ajv.addKeyword({
3995
- keyword: 'maxItemsWithSpaceType',
3996
- validate: function validate(schema, data) {
3997
- // @ts-ignore
3998
- var spaceType = this.spaceType || 'default';
3999
- var isValid = data.length <= schema[spaceType];
4000
- if (!isValid) {
4001
- // @ts-ignore
4002
- validate.errors = [
4003
- {
4004
- keyword: 'maxItemsWithSpaceType',
4005
- message: "must NOT have more than " + schema[spaceType] + " items",
4006
- params: { limit: schema[spaceType] }
4007
- }
4008
- ];
4009
- }
4010
- return isValid;
4011
- },
4012
- errors: true
4013
- });
4014
- // Custom URL format to allow empty string values
4015
- // https://github.com/snapshot-labs/snapshot.js/pull/541/files
4016
- ajv.addFormat('customUrl', {
4017
- type: 'string',
4018
- validate: function (str) {
4019
- if (!str.length)
4020
- return true;
4021
- return (str.startsWith('http://') ||
4022
- str.startsWith('https://') ||
4023
- str.startsWith('ipfs://') ||
4024
- str.startsWith('ipns://') ||
4025
- str.startsWith('snapshot://'));
4026
- }
4027
- });
4028
- function call(provider, abi, call, options) {
4029
- return __awaiter(this, void 0, void 0, function () {
4030
- var contract, params, e_1;
4031
- return __generator(this, function (_a) {
4032
- switch (_a.label) {
4033
- case 0:
4034
- contract = new Contract(call[0], abi, provider);
4035
- _a.label = 1;
4036
- case 1:
4037
- _a.trys.push([1, 3, , 4]);
4038
- params = call[2] || [];
4039
- return [4 /*yield*/, contract[call[1]].apply(contract, __spread(params, [options || {}]))];
4040
- case 2: return [2 /*return*/, _a.sent()];
4041
- case 3:
4042
- e_1 = _a.sent();
4043
- return [2 /*return*/, Promise.reject(e_1)];
4044
- case 4: return [2 /*return*/];
4045
- }
4046
- });
4047
- });
4048
- }
4049
- function multicall(network, provider, abi, calls, options) {
4050
- return __awaiter(this, void 0, void 0, function () {
4051
- var multicallAbi, multicallAddress, multi, itf, max_1, pages, promises_1, results, e_2;
4052
- return __generator(this, function (_a) {
4053
- switch (_a.label) {
4054
- case 0:
4055
- multicallAbi = [
4056
- 'function aggregate(tuple(address target, bytes callData)[] calls) view returns (uint256 blockNumber, bytes[] returnData)'
4057
- ];
4058
- multicallAddress = (options === null || options === void 0 ? void 0 : options.multicallAddress) || networks[network].multicall;
4059
- multi = new Contract(multicallAddress, multicallAbi, provider);
4060
- itf = new Interface(abi);
4061
- _a.label = 1;
4062
- case 1:
4063
- _a.trys.push([1, 3, , 4]);
4064
- max_1 = (options === null || options === void 0 ? void 0 : options.limit) || 500;
4065
- if (options === null || options === void 0 ? void 0 : options.limit)
4066
- delete options.limit;
4067
- pages = Math.ceil(calls.length / max_1);
4068
- promises_1 = [];
4069
- Array.from(Array(pages)).forEach(function (x, i) {
4070
- var callsInPage = calls.slice(max_1 * i, max_1 * (i + 1));
4071
- promises_1.push(multi.aggregate(callsInPage.map(function (call) { return [
4072
- call[0].toLowerCase(),
4073
- itf.encodeFunctionData(call[1], call[2])
4074
- ]; }), options || {}));
4075
- });
4076
- return [4 /*yield*/, Promise.all(promises_1)];
4077
- case 2:
4078
- results = _a.sent();
4079
- results = results.reduce(function (prev, _a) {
4080
- var _b = __read(_a, 2), res = _b[1];
4081
- return prev.concat(res);
4082
- }, []);
4083
- return [2 /*return*/, results.map(function (call, i) {
4084
- return itf.decodeFunctionResult(calls[i][1], call);
4085
- })];
4086
- case 3:
4087
- e_2 = _a.sent();
4088
- return [2 /*return*/, Promise.reject(e_2)];
4089
- case 4: return [2 /*return*/];
4090
- }
4091
- });
4092
- });
4093
- }
4094
- function subgraphRequest(url, query, options) {
4095
- if (options === void 0) { options = {}; }
4096
- return __awaiter(this, void 0, void 0, function () {
4097
- var res, responseData, data;
4098
- return __generator(this, function (_a) {
4099
- switch (_a.label) {
4100
- case 0: return [4 /*yield*/, fetch(url, {
4101
- method: 'POST',
4102
- headers: __assign({ Accept: 'application/json', 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers),
4103
- body: JSON.stringify({ query: jsonToGraphQLQuery({ query: query }) })
4104
- })];
4105
- case 1:
4106
- res = _a.sent();
4107
- return [4 /*yield*/, res.text()];
4108
- case 2:
4109
- responseData = _a.sent();
4110
- try {
4111
- responseData = JSON.parse(responseData);
4112
- }
4113
- catch (e) {
4114
- throw new Error("Errors found in subgraphRequest: URL: " + url + ", Status: " + res.status + ", Response: " + responseData.substring(0, 400));
4115
- }
4116
- if (responseData.errors) {
4117
- throw new Error("Errors found in subgraphRequest: URL: " + url + ", Status: " + res.status + ", Response: " + JSON.stringify(responseData.errors).substring(0, 400));
4118
- }
4119
- data = responseData.data;
4120
- return [2 /*return*/, data || {}];
4121
- }
4122
- });
4123
- });
4124
- }
4125
- function getUrl(uri, gateway) {
4126
- if (gateway === void 0) { gateway = gateways[0]; }
4127
- var ipfsGateway = "https://" + gateway;
4128
- if (!uri)
4129
- return null;
4130
- if (!uri.startsWith('ipfs://') &&
4131
- !uri.startsWith('ipns://') &&
4132
- !uri.startsWith('https://') &&
4133
- !uri.startsWith('http://'))
4134
- return ipfsGateway + "/ipfs/" + uri;
4135
- var uriScheme = uri.split('://')[0];
4136
- if (uriScheme === 'ipfs')
4137
- return uri.replace('ipfs://', ipfsGateway + "/ipfs/");
4138
- if (uriScheme === 'ipns')
4139
- return uri.replace('ipns://', ipfsGateway + "/ipns/");
4140
- return uri;
4141
- }
4142
- function getJSON(uri, options) {
4143
- if (options === void 0) { options = {}; }
4144
- return __awaiter(this, void 0, void 0, function () {
4145
- var url;
4146
- return __generator(this, function (_a) {
4147
- url = getUrl(uri, options.gateways);
4148
- return [2 /*return*/, fetch(url).then(function (res) { return res.json(); })];
4149
- });
4150
- });
4151
- }
4152
- function ipfsGet(gateway, ipfsHash, protocolType) {
4153
- if (protocolType === void 0) { protocolType = 'ipfs'; }
4154
- return __awaiter(this, void 0, void 0, function () {
4155
- var url;
4156
- return __generator(this, function (_a) {
4157
- url = "https://" + gateway + "/" + protocolType + "/" + ipfsHash;
4158
- return [2 /*return*/, fetch(url).then(function (res) { return res.json(); })];
4159
- });
4160
- });
4161
- }
4162
- function sendTransaction(web3, contractAddress, abi, action, params, overrides) {
4163
- if (overrides === void 0) { overrides = {}; }
4164
- return __awaiter(this, void 0, void 0, function () {
4165
- var signer, contract, contractWithSigner;
4166
- return __generator(this, function (_a) {
4167
- switch (_a.label) {
4168
- case 0:
4169
- signer = web3.getSigner();
4170
- contract = new Contract(contractAddress, abi, web3);
4171
- contractWithSigner = contract.connect(signer);
4172
- return [4 /*yield*/, contractWithSigner[action].apply(contractWithSigner, __spread(params, [overrides]))];
4173
- case 1:
4174
- // overrides.gasLimit = 12e6;
4175
- return [2 /*return*/, _a.sent()];
4176
- }
4177
- });
4178
- });
4179
- }
4180
- function getScores(space, strategies, network, addresses, snapshot, scoreApiUrl, options) {
4181
- if (snapshot === void 0) { snapshot = 'latest'; }
4182
- if (scoreApiUrl === void 0) { scoreApiUrl = DEFAULT_SCORE_API_URL; }
4183
- if (options === void 0) { options = {}; }
4184
- return __awaiter(this, void 0, void 0, function () {
4185
- var invalidAddress, invalidStrategy, urlObject, _a, url, headers, params, res, response, e_3;
4186
- return __generator(this, function (_b) {
4187
- switch (_b.label) {
4188
- case 0:
4189
- if (!Array.isArray(addresses)) {
4190
- return [2 /*return*/, inputError('addresses should be an array of addresses')];
4191
- }
4192
- if (addresses.length === 0) {
4193
- return [2 /*return*/, inputError('addresses can not be empty')];
4194
- }
4195
- invalidAddress = addresses.find(function (address) { return !isValidAddress(address); });
4196
- if (invalidAddress) {
4197
- return [2 /*return*/, inputError("Invalid address: " + invalidAddress)];
4198
- }
4199
- if (!isValidNetwork(network)) {
4200
- return [2 /*return*/, inputError("Invalid network: " + network)];
4201
- }
4202
- invalidStrategy = strategies.find(function (strategy) { return strategy.network && !isValidNetwork(strategy.network); });
4203
- if (invalidStrategy) {
4204
- return [2 /*return*/, inputError("Invalid network (" + invalidStrategy.network + ") in strategy " + invalidStrategy.name)];
4205
- }
4206
- if (!isValidSnapshot(snapshot, network)) {
4207
- return [2 /*return*/, inputError("Snapshot (" + snapshot + ") must be 'latest' or greater than network start block (" + networks[network].start + ")")];
4208
- }
4209
- urlObject = new URL(scoreApiUrl);
4210
- urlObject.pathname = '/api/scores';
4211
- _a = formatScoreAPIUrl(scoreApiUrl, {
4212
- path: '/api/scores'
4213
- }), url = _a.url, headers = _a.headers;
4214
- _b.label = 1;
4215
- case 1:
4216
- _b.trys.push([1, 4, , 5]);
4217
- params = {
4218
- space: space,
4219
- network: network,
4220
- snapshot: snapshot,
4221
- strategies: strategies,
4222
- addresses: addresses
4223
- };
4224
- return [4 /*yield*/, fetch(url, {
4225
- method: 'POST',
4226
- headers: headers,
4227
- body: JSON.stringify({ params: params })
4228
- })];
4229
- case 2:
4230
- res = _b.sent();
4231
- return [4 /*yield*/, parseScoreAPIResponse(res)];
4232
- case 3:
4233
- response = _b.sent();
4234
- return [2 /*return*/, options.returnValue === 'all'
4235
- ? response.result
4236
- : response.result[options.returnValue || 'scores']];
4237
- case 4:
4238
- e_3 = _b.sent();
4239
- if (e_3.errno) {
4240
- return [2 /*return*/, Promise.reject({ code: e_3.errno, message: e_3.toString(), data: '' })];
4241
- }
4242
- return [2 /*return*/, Promise.reject(e_3)];
4243
- case 5: return [2 /*return*/];
4244
- }
4245
- });
4246
- });
4247
- }
4248
- function getVp(address, network, strategies, snapshot, space, delegation, options) {
4249
- return __awaiter(this, void 0, void 0, function () {
4250
- var _a, url, headers, invalidStrategy, init, res, response, e_4;
4251
- return __generator(this, function (_b) {
4252
- switch (_b.label) {
4253
- case 0:
4254
- _a = formatScoreAPIUrl(options === null || options === void 0 ? void 0 : options.url), url = _a.url, headers = _a.headers;
4255
- if (!isValidAddress(address)) {
4256
- return [2 /*return*/, inputError("Invalid voter address: " + address)];
4257
- }
4258
- if (!isValidNetwork(network)) {
4259
- return [2 /*return*/, inputError("Invalid network: " + network)];
4260
- }
4261
- invalidStrategy = strategies.find(function (strategy) { return strategy.network && !isValidNetwork(strategy.network); });
4262
- if (invalidStrategy) {
4263
- return [2 /*return*/, inputError("Invalid network (" + invalidStrategy.network + ") in strategy " + invalidStrategy.name)];
4264
- }
4265
- if (!isValidSnapshot(snapshot, network)) {
4266
- return [2 /*return*/, inputError("Snapshot (" + snapshot + ") must be 'latest' or greater than network start block (" + networks[network].start + ")")];
4267
- }
4268
- init = {
4269
- method: 'POST',
4270
- headers: headers,
4271
- body: JSON.stringify({
4272
- jsonrpc: '2.0',
4273
- method: 'get_vp',
4274
- params: {
4275
- address: address,
4276
- network: network,
4277
- strategies: strategies,
4278
- snapshot: snapshot,
4279
- space: space,
4280
- delegation: delegation
4281
- }
4282
- })
4283
- };
4284
- _b.label = 1;
4285
- case 1:
4286
- _b.trys.push([1, 4, , 5]);
4287
- return [4 /*yield*/, fetch(url, init)];
4288
- case 2:
4289
- res = _b.sent();
4290
- return [4 /*yield*/, parseScoreAPIResponse(res)];
4291
- case 3:
4292
- response = _b.sent();
4293
- return [2 /*return*/, response.result];
4294
- case 4:
4295
- e_4 = _b.sent();
4296
- if (e_4.errno) {
4297
- return [2 /*return*/, Promise.reject({ code: e_4.errno, message: e_4.toString(), data: '' })];
4298
- }
4299
- return [2 /*return*/, Promise.reject(e_4)];
4300
- case 5: return [2 /*return*/];
4301
- }
4302
- });
4303
- });
4304
- }
4305
- function validate(validation, author, space, network, snapshot, params, options) {
4306
- return __awaiter(this, void 0, void 0, function () {
4307
- var _a, url, headers, init, res, response, e_5;
4308
- return __generator(this, function (_b) {
4309
- switch (_b.label) {
4310
- case 0:
4311
- if (!isValidAddress(author)) {
4312
- return [2 /*return*/, inputError("Invalid author: " + author)];
4313
- }
4314
- if (!isValidNetwork(network)) {
4315
- return [2 /*return*/, inputError("Invalid network: " + network)];
4316
- }
4317
- if (!isValidSnapshot(snapshot, network)) {
4318
- return [2 /*return*/, inputError("Snapshot (" + snapshot + ") must be 'latest' or greater than network start block (" + networks[network].start + ")")];
4319
- }
4320
- if (!options)
4321
- options = {};
4322
- _a = formatScoreAPIUrl(options.url), url = _a.url, headers = _a.headers;
4323
- init = {
4324
- method: 'POST',
4325
- headers: headers,
4326
- body: JSON.stringify({
4327
- jsonrpc: '2.0',
4328
- method: 'validate',
4329
- params: {
4330
- validation: validation,
4331
- author: author,
4332
- space: space,
4333
- network: network,
4334
- snapshot: snapshot,
4335
- params: params
4336
- }
4337
- })
4338
- };
4339
- _b.label = 1;
4340
- case 1:
4341
- _b.trys.push([1, 4, , 5]);
4342
- return [4 /*yield*/, fetch(url, init)];
4343
- case 2:
4344
- res = _b.sent();
4345
- return [4 /*yield*/, parseScoreAPIResponse(res)];
4346
- case 3:
4347
- response = _b.sent();
4348
- return [2 /*return*/, response.result];
4349
- case 4:
4350
- e_5 = _b.sent();
4351
- if (e_5.errno) {
4352
- return [2 /*return*/, Promise.reject({ code: e_5.errno, message: e_5.toString(), data: '' })];
4353
- }
4354
- return [2 /*return*/, Promise.reject(e_5)];
4355
- case 5: return [2 /*return*/];
4356
- }
4357
- });
4358
- });
4359
- }
4360
- function validateSchema(schema, data, options) {
4361
- if (options === void 0) { options = {
4362
- snapshotEnv: 'default',
4363
- spaceType: 'default'
4364
- }; }
4365
- var ajvValidate = ajv.compile(schema);
4366
- var valid = ajvValidate.call(options, data);
4367
- return valid ? valid : ajvValidate.errors;
4368
- }
4369
- function getEnsTextRecord(ens, record, network, options) {
4370
- if (network === void 0) { network = '1'; }
4371
- if (options === void 0) { options = {}; }
4372
- return __awaiter(this, void 0, void 0, function () {
4373
- var ensResolversOpt, broviderUrl, multicallOptions, ensResolvers, ensHash, provider, result;
4374
- return __generator(this, function (_a) {
4375
- switch (_a.label) {
4376
- case 0:
4377
- ensResolversOpt = options.ensResolvers, broviderUrl = options.broviderUrl, multicallOptions = __rest(options, ["ensResolvers", "broviderUrl"]);
4378
- ensResolvers = ensResolversOpt ||
4379
- networks[network].ensResolvers ||
4380
- networks['1'].ensResolvers;
4381
- ensHash = namehash(ensNormalize(ens));
4382
- provider = getProvider(network, { broviderUrl: broviderUrl });
4383
- return [4 /*yield*/, multicall(network, provider, ENS_RESOLVER_ABI, ensResolvers.map(function (address) { return [address, 'text', [ensHash, record]]; }), multicallOptions)];
4384
- case 1:
4385
- result = _a.sent();
4386
- return [2 /*return*/, result.flat().find(function (r) { return r; }) || ''];
4387
- }
4388
- });
4389
- });
4390
- }
4391
- function getSpaceUri(id, network, options) {
4392
- if (network === void 0) { network = '1'; }
4393
- if (options === void 0) { options = {}; }
4394
- return __awaiter(this, void 0, void 0, function () {
4395
- var e_6;
4396
- return __generator(this, function (_a) {
4397
- switch (_a.label) {
4398
- case 0:
4399
- _a.trys.push([0, 2, , 3]);
4400
- return [4 /*yield*/, getEnsTextRecord(id, 'snapshot', network, options)];
4401
- case 1: return [2 /*return*/, _a.sent()];
4402
- case 2:
4403
- e_6 = _a.sent();
4404
- console.log(e_6);
4405
- return [2 /*return*/, null];
4406
- case 3: return [2 /*return*/];
4407
- }
4408
- });
4409
- });
4410
- }
4411
- function getEnsOwner(ens, network, options) {
4412
- if (network === void 0) { network = '1'; }
4413
- if (options === void 0) { options = {}; }
4414
- return __awaiter(this, void 0, void 0, function () {
4415
- var registryAddress, provider, ensRegistry, ensNameWrapper, ensHash, owner, ensNameWrapperContract;
4416
- return __generator(this, function (_a) {
4417
- switch (_a.label) {
4418
- case 0:
4419
- registryAddress = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e';
4420
- provider = getProvider(network, options);
4421
- ensRegistry = new Contract(registryAddress, ['function owner(bytes32) view returns (address)'], provider);
4422
- ensNameWrapper = options.ensNameWrapper || networks[network].ensNameWrapper;
4423
- ensHash = namehash(ensNormalize(ens));
4424
- return [4 /*yield*/, ensRegistry.owner(ensHash)];
4425
- case 1:
4426
- owner = _a.sent();
4427
- if (!(owner === ensNameWrapper)) return [3 /*break*/, 3];
4428
- ensNameWrapperContract = new Contract(ensNameWrapper, ['function ownerOf(uint256) view returns (address)'], provider);
4429
- return [4 /*yield*/, ensNameWrapperContract.ownerOf(ensHash)];
4430
- case 2:
4431
- owner = _a.sent();
4432
- _a.label = 3;
4433
- case 3: return [2 /*return*/, owner];
4434
- }
4435
- });
4436
- });
4437
- }
4438
- function getSpaceController(id, network, options) {
4439
- if (network === void 0) { network = '1'; }
4440
- if (options === void 0) { options = {}; }
4441
- return __awaiter(this, void 0, void 0, function () {
4442
- var spaceUri, isUriAddress, uriParts, position, address;
4443
- return __generator(this, function (_a) {
4444
- switch (_a.label) {
4445
- case 0: return [4 /*yield*/, getSpaceUri(id, network, options)];
4446
- case 1:
4447
- spaceUri = _a.sent();
4448
- if (spaceUri) {
4449
- isUriAddress = isAddress(spaceUri);
4450
- if (isUriAddress)
4451
- return [2 /*return*/, spaceUri];
4452
- uriParts = spaceUri.split('/');
4453
- position = uriParts.includes('testnet') ? 5 : 4;
4454
- address = uriParts[position];
4455
- isUriAddress = isAddress(address);
4456
- if (isUriAddress)
4457
- return [2 /*return*/, address];
4458
- }
4459
- return [4 /*yield*/, getEnsOwner(id, network, options)];
4460
- case 2: return [2 /*return*/, _a.sent()];
4461
- }
4462
- });
4463
- });
4464
- }
4465
- function clone(item) {
4466
- return JSON.parse(JSON.stringify(item));
4467
- }
4468
- function sleep(time) {
4469
- return __awaiter(this, void 0, void 0, function () {
4470
- return __generator(this, function (_a) {
4471
- return [2 /*return*/, new Promise(function (resolve) {
4472
- setTimeout(resolve, time);
4473
- })];
4474
- });
4475
- });
4476
- }
4477
- function getNumberWithOrdinal(n) {
4478
- var s = ['th', 'st', 'nd', 'rd'], v = n % 100;
4479
- return n + (s[(v - 20) % 10] || s[v] || s[0]);
4480
- }
4481
- function isValidNetwork(network) {
4482
- return !!networks[network];
4483
- }
4484
- function isValidAddress(address) {
4485
- return isAddress(address) && address !== EMPTY_ADDRESS;
4486
- }
4487
- function isValidSnapshot(snapshot, network) {
4488
- return (snapshot === 'latest' ||
4489
- (typeof snapshot === 'number' && snapshot >= networks[network].start));
4490
- }
4491
- function inputError(message) {
4492
- return Promise.reject(new Error(message));
4493
- }
4494
- var utils = {
4495
- call: call,
4496
- multicall: multicall,
4497
- subgraphRequest: subgraphRequest,
4498
- ipfsGet: ipfsGet,
4499
- getUrl: getUrl,
4500
- getJSON: getJSON,
4501
- sendTransaction: sendTransaction,
4502
- getScores: getScores,
4503
- getVp: getVp,
4504
- validateSchema: validateSchema,
4505
- getEnsTextRecord: getEnsTextRecord,
4506
- getSpaceUri: getSpaceUri,
4507
- getEnsOwner: getEnsOwner,
4508
- getSpaceController: getSpaceController,
4509
- getDelegatesBySpace: getDelegatesBySpace,
4510
- clone: clone,
4511
- sleep: sleep,
4512
- getNumberWithOrdinal: getNumberWithOrdinal,
4513
- voting: voting,
4514
- getProvider: getProvider,
4515
- signMessage: signMessage,
4516
- getBlockNumber: getBlockNumber,
4517
- Multicaller: Multicaller,
4518
- getSnapshots: getSnapshots,
4519
- getHash: getHash,
4520
- verify: verify$1,
4521
- validate: validate,
4522
- SNAPSHOT_SUBGRAPH_URL: SNAPSHOT_SUBGRAPH_URL
3546
+ const ENS_REGISTRY = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e';
3547
+ const ENS_ABI = [
3548
+ 'function text(bytes32 node, string calldata key) external view returns (string memory)',
3549
+ 'function resolver(bytes32 node) view returns (address)' // ENS registry ABI
3550
+ ];
3551
+ const EMPTY_ADDRESS = '0x0000000000000000000000000000000000000000';
3552
+ const scoreApiHeaders = {
3553
+ Accept: 'application/json',
3554
+ 'Content-Type': 'application/json'
3555
+ };
3556
+ const DEFAULT_SCORE_API_URL = 'https://score.snapshot.org';
3557
+ function formatScoreAPIUrl(url = DEFAULT_SCORE_API_URL, options = {
3558
+ path: ''
3559
+ }) {
3560
+ const scoreURL = new URL(url);
3561
+ if (options.path)
3562
+ scoreURL.pathname = options.path;
3563
+ const apiKey = scoreURL.searchParams.get('apiKey');
3564
+ let headers = Object.assign({}, scoreApiHeaders);
3565
+ if (apiKey) {
3566
+ scoreURL.searchParams.delete('apiKey');
3567
+ headers = Object.assign(Object.assign({}, scoreApiHeaders), { 'X-API-KEY': apiKey });
3568
+ }
3569
+ return {
3570
+ url: scoreURL.toString(),
3571
+ headers
3572
+ };
3573
+ }
3574
+ function parseScoreAPIResponse(res) {
3575
+ return __awaiter(this, void 0, void 0, function* () {
3576
+ let data = yield res.text();
3577
+ try {
3578
+ data = JSON.parse(data);
3579
+ }
3580
+ catch (e) {
3581
+ return Promise.reject({
3582
+ code: res.status || 500,
3583
+ message: 'Failed to parse response from score API',
3584
+ data
3585
+ });
3586
+ }
3587
+ if (data.error)
3588
+ return Promise.reject(data.error);
3589
+ return data;
3590
+ });
3591
+ }
3592
+ const ajv = new Ajv({
3593
+ allErrors: true,
3594
+ allowUnionTypes: true,
3595
+ $data: true,
3596
+ passContext: true
3597
+ });
3598
+ // @ts-ignore
3599
+ addFormats(ajv);
3600
+ addErrors(ajv);
3601
+ ajv.addFormat('address', {
3602
+ validate: (value) => {
3603
+ try {
3604
+ return isAddress(value);
3605
+ }
3606
+ catch (err) {
3607
+ return false;
3608
+ }
3609
+ }
3610
+ });
3611
+ ajv.addFormat('evmOrStarknetAddress', {
3612
+ validate: (value) => {
3613
+ try {
3614
+ return isAddress(value) || /^0x[0-9a-fA-F]{62,64}$/.test(value);
3615
+ }
3616
+ catch (err) {
3617
+ return false;
3618
+ }
3619
+ }
3620
+ });
3621
+ ajv.addFormat('long', {
3622
+ validate: () => true
3623
+ });
3624
+ ajv.addFormat('ethValue', {
3625
+ validate: (value) => {
3626
+ if (!value.match(/^([0-9]|[1-9][0-9]+)(\.[0-9]+)?$/))
3627
+ return false;
3628
+ try {
3629
+ parseUnits(value, 18);
3630
+ return true;
3631
+ }
3632
+ catch (_a) {
3633
+ return false;
3634
+ }
3635
+ }
3636
+ });
3637
+ const networksIds = Object.keys(networks);
3638
+ const mainnetNetworkIds = Object.keys(networks).filter((id) => !networks[id].testnet);
3639
+ ajv.addKeyword({
3640
+ keyword: 'snapshotNetwork',
3641
+ validate: function (schema, data) {
3642
+ // @ts-ignore
3643
+ const snapshotEnv = this.snapshotEnv || 'default';
3644
+ if (snapshotEnv === 'mainnet')
3645
+ return mainnetNetworkIds.includes(data);
3646
+ return networksIds.includes(data);
3647
+ },
3648
+ error: {
3649
+ message: 'network not allowed'
3650
+ }
3651
+ });
3652
+ ajv.addKeyword({
3653
+ keyword: 'maxLengthWithSpaceType',
3654
+ validate: function validate(schema, data) {
3655
+ // @ts-ignore
3656
+ const spaceType = this.spaceType || 'default';
3657
+ const isValid = data.length <= schema[spaceType];
3658
+ if (!isValid) {
3659
+ // @ts-ignore
3660
+ validate.errors = [
3661
+ {
3662
+ keyword: 'maxLengthWithSpaceType',
3663
+ message: `must NOT have more than ${schema[spaceType]} characters`,
3664
+ params: { limit: schema[spaceType] }
3665
+ }
3666
+ ];
3667
+ }
3668
+ return isValid;
3669
+ },
3670
+ errors: true
3671
+ });
3672
+ ajv.addKeyword({
3673
+ keyword: 'maxItemsWithSpaceType',
3674
+ validate: function validate(schema, data) {
3675
+ // @ts-ignore
3676
+ const spaceType = this.spaceType || 'default';
3677
+ const isValid = data.length <= schema[spaceType];
3678
+ if (!isValid) {
3679
+ // @ts-ignore
3680
+ validate.errors = [
3681
+ {
3682
+ keyword: 'maxItemsWithSpaceType',
3683
+ message: `must NOT have more than ${schema[spaceType]} items`,
3684
+ params: { limit: schema[spaceType] }
3685
+ }
3686
+ ];
3687
+ }
3688
+ return isValid;
3689
+ },
3690
+ errors: true
3691
+ });
3692
+ // Custom URL format to allow empty string values
3693
+ // https://github.com/snapshot-labs/snapshot.js/pull/541/files
3694
+ ajv.addFormat('customUrl', {
3695
+ type: 'string',
3696
+ validate: (str) => {
3697
+ if (!str.length)
3698
+ return true;
3699
+ return (str.startsWith('http://') ||
3700
+ str.startsWith('https://') ||
3701
+ str.startsWith('ipfs://') ||
3702
+ str.startsWith('ipns://') ||
3703
+ str.startsWith('snapshot://'));
3704
+ }
3705
+ });
3706
+ function call(provider, abi, call, options) {
3707
+ return __awaiter(this, void 0, void 0, function* () {
3708
+ const contract = new Contract(call[0], abi, provider);
3709
+ try {
3710
+ const params = call[2] || [];
3711
+ return yield contract[call[1]](...params, options || {});
3712
+ }
3713
+ catch (e) {
3714
+ return Promise.reject(e);
3715
+ }
3716
+ });
3717
+ }
3718
+ function multicall(network, provider, abi, calls, options) {
3719
+ return __awaiter(this, void 0, void 0, function* () {
3720
+ const multicallAbi = [
3721
+ 'function aggregate(tuple(address target, bytes callData)[] calls) view returns (uint256 blockNumber, bytes[] returnData)'
3722
+ ];
3723
+ const multicallAddress = (options === null || options === void 0 ? void 0 : options.multicallAddress) || networks[network].multicall;
3724
+ const multi = new Contract(multicallAddress, multicallAbi, provider);
3725
+ const itf = new Interface(abi);
3726
+ try {
3727
+ const max = (options === null || options === void 0 ? void 0 : options.limit) || 500;
3728
+ if (options === null || options === void 0 ? void 0 : options.limit)
3729
+ delete options.limit;
3730
+ const pages = Math.ceil(calls.length / max);
3731
+ const promises = [];
3732
+ Array.from(Array(pages)).forEach((x, i) => {
3733
+ const callsInPage = calls.slice(max * i, max * (i + 1));
3734
+ promises.push(multi.aggregate(callsInPage.map((call) => [
3735
+ call[0].toLowerCase(),
3736
+ itf.encodeFunctionData(call[1], call[2])
3737
+ ]), options || {}));
3738
+ });
3739
+ let results = yield Promise.all(promises);
3740
+ results = results.reduce((prev, [, res]) => prev.concat(res), []);
3741
+ return results.map((call, i) => itf.decodeFunctionResult(calls[i][1], call));
3742
+ }
3743
+ catch (e) {
3744
+ return Promise.reject(e);
3745
+ }
3746
+ });
3747
+ }
3748
+ function subgraphRequest(url_1, query_1) {
3749
+ return __awaiter(this, arguments, void 0, function* (url, query, options = {}) {
3750
+ const res = yield fetch(url, {
3751
+ method: 'POST',
3752
+ headers: Object.assign({ Accept: 'application/json', 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers),
3753
+ body: JSON.stringify({ query: jsonToGraphQLQuery({ query }) })
3754
+ });
3755
+ let responseData = yield res.text();
3756
+ try {
3757
+ responseData = JSON.parse(responseData);
3758
+ }
3759
+ catch (e) {
3760
+ throw new Error(`Errors found in subgraphRequest: URL: ${url}, Status: ${res.status}, Response: ${responseData.substring(0, 400)}`);
3761
+ }
3762
+ if (responseData.errors) {
3763
+ throw new Error(`Errors found in subgraphRequest: URL: ${url}, Status: ${res.status}, Response: ${JSON.stringify(responseData.errors).substring(0, 400)}`);
3764
+ }
3765
+ const { data } = responseData;
3766
+ return data || {};
3767
+ });
3768
+ }
3769
+ function getUrl(uri, gateway = gateways[0]) {
3770
+ const ipfsGateway = `https://${gateway}`;
3771
+ if (!uri)
3772
+ return null;
3773
+ if (!uri.startsWith('ipfs://') &&
3774
+ !uri.startsWith('ipns://') &&
3775
+ !uri.startsWith('https://') &&
3776
+ !uri.startsWith('http://'))
3777
+ return `${ipfsGateway}/ipfs/${uri}`;
3778
+ const uriScheme = uri.split('://')[0];
3779
+ if (uriScheme === 'ipfs')
3780
+ return uri.replace('ipfs://', `${ipfsGateway}/ipfs/`);
3781
+ if (uriScheme === 'ipns')
3782
+ return uri.replace('ipns://', `${ipfsGateway}/ipns/`);
3783
+ return uri;
3784
+ }
3785
+ function getJSON(uri_1) {
3786
+ return __awaiter(this, arguments, void 0, function* (uri, options = {}) {
3787
+ const url = getUrl(uri, options.gateways);
3788
+ return fetch(url).then((res) => res.json());
3789
+ });
3790
+ }
3791
+ function ipfsGet(gateway_1, ipfsHash_1) {
3792
+ return __awaiter(this, arguments, void 0, function* (gateway, ipfsHash, protocolType = 'ipfs') {
3793
+ const url = `https://${gateway}/${protocolType}/${ipfsHash}`;
3794
+ return fetch(url).then((res) => res.json());
3795
+ });
3796
+ }
3797
+ function sendTransaction(web3_1, contractAddress_1, abi_1, action_1, params_1) {
3798
+ return __awaiter(this, arguments, void 0, function* (web3, contractAddress, abi, action, params, overrides = {}) {
3799
+ const signer = web3.getSigner();
3800
+ const contract = new Contract(contractAddress, abi, web3);
3801
+ const contractWithSigner = contract.connect(signer);
3802
+ // overrides.gasLimit = 12e6;
3803
+ return yield contractWithSigner[action](...params, overrides);
3804
+ });
3805
+ }
3806
+ function getScores(space_1, strategies_1, network_1, addresses_1) {
3807
+ return __awaiter(this, arguments, void 0, function* (space, strategies, network, addresses, snapshot = 'latest', scoreApiUrl = DEFAULT_SCORE_API_URL, options = {}) {
3808
+ if (!Array.isArray(addresses)) {
3809
+ return inputError('addresses should be an array of addresses');
3810
+ }
3811
+ if (addresses.length === 0) {
3812
+ return inputError('addresses can not be empty');
3813
+ }
3814
+ const invalidAddress = addresses.find((address) => !isValidAddress(address));
3815
+ if (invalidAddress) {
3816
+ return inputError(`Invalid address: ${invalidAddress}`);
3817
+ }
3818
+ if (!isValidNetwork(network)) {
3819
+ return inputError(`Invalid network: ${network}`);
3820
+ }
3821
+ const invalidStrategy = strategies.find((strategy) => strategy.network && !isValidNetwork(strategy.network));
3822
+ if (invalidStrategy) {
3823
+ return inputError(`Invalid network (${invalidStrategy.network}) in strategy ${invalidStrategy.name}`);
3824
+ }
3825
+ if (!isValidSnapshot(snapshot, network)) {
3826
+ return inputError(`Snapshot (${snapshot}) must be 'latest' or greater than network start block (${networks[network].start})`);
3827
+ }
3828
+ const urlObject = new URL(scoreApiUrl);
3829
+ urlObject.pathname = '/api/scores';
3830
+ const { url, headers } = formatScoreAPIUrl(scoreApiUrl, {
3831
+ path: '/api/scores'
3832
+ });
3833
+ try {
3834
+ const params = {
3835
+ space,
3836
+ network,
3837
+ snapshot,
3838
+ strategies,
3839
+ addresses
3840
+ };
3841
+ const res = yield fetch(url, {
3842
+ method: 'POST',
3843
+ headers,
3844
+ body: JSON.stringify({ params })
3845
+ });
3846
+ const response = yield parseScoreAPIResponse(res);
3847
+ return options.returnValue === 'all'
3848
+ ? response.result
3849
+ : response.result[options.returnValue || 'scores'];
3850
+ }
3851
+ catch (e) {
3852
+ if (e.errno) {
3853
+ return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
3854
+ }
3855
+ return Promise.reject(e);
3856
+ }
3857
+ });
3858
+ }
3859
+ function getVp(address, network, strategies, snapshot, space, delegation, options) {
3860
+ return __awaiter(this, void 0, void 0, function* () {
3861
+ const { url, headers } = formatScoreAPIUrl(options === null || options === void 0 ? void 0 : options.url);
3862
+ if (!isValidAddress(address)) {
3863
+ return inputError(`Invalid voter address: ${address}`);
3864
+ }
3865
+ if (!isValidNetwork(network)) {
3866
+ return inputError(`Invalid network: ${network}`);
3867
+ }
3868
+ const invalidStrategy = strategies.find((strategy) => strategy.network && !isValidNetwork(strategy.network));
3869
+ if (invalidStrategy) {
3870
+ return inputError(`Invalid network (${invalidStrategy.network}) in strategy ${invalidStrategy.name}`);
3871
+ }
3872
+ if (!isValidSnapshot(snapshot, network)) {
3873
+ return inputError(`Snapshot (${snapshot}) must be 'latest' or greater than network start block (${networks[network].start})`);
3874
+ }
3875
+ const init = {
3876
+ method: 'POST',
3877
+ headers,
3878
+ body: JSON.stringify({
3879
+ jsonrpc: '2.0',
3880
+ method: 'get_vp',
3881
+ params: {
3882
+ address,
3883
+ network,
3884
+ strategies,
3885
+ snapshot,
3886
+ space,
3887
+ delegation
3888
+ }
3889
+ })
3890
+ };
3891
+ try {
3892
+ const res = yield fetch(url, init);
3893
+ const response = yield parseScoreAPIResponse(res);
3894
+ return response.result;
3895
+ }
3896
+ catch (e) {
3897
+ if (e.errno) {
3898
+ return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
3899
+ }
3900
+ return Promise.reject(e);
3901
+ }
3902
+ });
3903
+ }
3904
+ function validate(validation, author, space, network, snapshot, params, options) {
3905
+ return __awaiter(this, void 0, void 0, function* () {
3906
+ if (!isValidAddress(author)) {
3907
+ return inputError(`Invalid author: ${author}`);
3908
+ }
3909
+ if (!isValidNetwork(network)) {
3910
+ return inputError(`Invalid network: ${network}`);
3911
+ }
3912
+ if (!isValidSnapshot(snapshot, network)) {
3913
+ return inputError(`Snapshot (${snapshot}) must be 'latest' or greater than network start block (${networks[network].start})`);
3914
+ }
3915
+ if (!options)
3916
+ options = {};
3917
+ const { url, headers } = formatScoreAPIUrl(options.url);
3918
+ const init = {
3919
+ method: 'POST',
3920
+ headers,
3921
+ body: JSON.stringify({
3922
+ jsonrpc: '2.0',
3923
+ method: 'validate',
3924
+ params: {
3925
+ validation,
3926
+ author,
3927
+ space,
3928
+ network,
3929
+ snapshot,
3930
+ params
3931
+ }
3932
+ })
3933
+ };
3934
+ try {
3935
+ const res = yield fetch(url, init);
3936
+ const response = yield parseScoreAPIResponse(res);
3937
+ return response.result;
3938
+ }
3939
+ catch (e) {
3940
+ if (e.errno) {
3941
+ return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
3942
+ }
3943
+ return Promise.reject(e);
3944
+ }
3945
+ });
3946
+ }
3947
+ function validateSchema(schema, data, options = {
3948
+ snapshotEnv: 'default',
3949
+ spaceType: 'default'
3950
+ }) {
3951
+ const ajvValidate = ajv.compile(schema);
3952
+ const valid = ajvValidate.call(options, data);
3953
+ return valid ? valid : ajvValidate.errors;
3954
+ }
3955
+ function getEnsTextRecord(ens_1, record_1) {
3956
+ return __awaiter(this, arguments, void 0, function* (ens, record, network = '1', options = {}) {
3957
+ var _a, _b;
3958
+ const { ensResolvers = ((_a = networks[network]) === null || _a === void 0 ? void 0 : _a.ensResolvers) ||
3959
+ networks['1'].ensResolvers, broviderUrl } = options, multicallOptions = __rest(options, ["ensResolvers", "broviderUrl"]);
3960
+ const ensHash = namehash(ensNormalize(ens));
3961
+ const provider = getProvider(network, { broviderUrl });
3962
+ const calls = [
3963
+ [ENS_REGISTRY, 'resolver', [ensHash]], // Query for resolver from registry
3964
+ ...ensResolvers.map((address) => [
3965
+ address,
3966
+ 'text',
3967
+ [ensHash, record]
3968
+ ]) // Query for text record from each resolver
3969
+ ];
3970
+ const [[resolverAddress], ...textRecords] = yield multicall(network, provider, ENS_ABI, calls, multicallOptions);
3971
+ const resolverIndex = ensResolvers.indexOf(resolverAddress);
3972
+ return resolverIndex !== -1 ? (_b = textRecords[resolverIndex]) === null || _b === void 0 ? void 0 : _b[0] : null;
3973
+ });
3974
+ }
3975
+ function getSpaceUri(id_1) {
3976
+ return __awaiter(this, arguments, void 0, function* (id, network = '1', options = {}) {
3977
+ try {
3978
+ return yield getEnsTextRecord(id, 'snapshot', network, options);
3979
+ }
3980
+ catch (e) {
3981
+ console.log(e);
3982
+ return null;
3983
+ }
3984
+ });
3985
+ }
3986
+ function getEnsOwner(ens_1) {
3987
+ return __awaiter(this, arguments, void 0, function* (ens, network = '1', options = {}) {
3988
+ const provider = getProvider(network, options);
3989
+ const ensRegistry = new Contract(ENS_REGISTRY, ['function owner(bytes32) view returns (address)'], provider);
3990
+ const ensNameWrapper = options.ensNameWrapper || networks[network].ensNameWrapper;
3991
+ const ensHash = namehash(ensNormalize(ens));
3992
+ let owner = yield ensRegistry.owner(ensHash);
3993
+ // If owner is the ENSNameWrapper contract, resolve the owner of the name
3994
+ if (owner === ensNameWrapper) {
3995
+ const ensNameWrapperContract = new Contract(ensNameWrapper, ['function ownerOf(uint256) view returns (address)'], provider);
3996
+ owner = yield ensNameWrapperContract.ownerOf(ensHash);
3997
+ }
3998
+ return owner;
3999
+ });
4000
+ }
4001
+ function getSpaceController(id_1) {
4002
+ return __awaiter(this, arguments, void 0, function* (id, network = '1', options = {}) {
4003
+ const spaceUri = yield getSpaceUri(id, network, options);
4004
+ if (spaceUri) {
4005
+ let isUriAddress = isAddress(spaceUri);
4006
+ if (isUriAddress)
4007
+ return spaceUri;
4008
+ const uriParts = spaceUri.split('/');
4009
+ const position = uriParts.includes('testnet') ? 5 : 4;
4010
+ const address = uriParts[position];
4011
+ isUriAddress = isAddress(address);
4012
+ if (isUriAddress)
4013
+ return address;
4014
+ }
4015
+ return yield getEnsOwner(id, network, options);
4016
+ });
4017
+ }
4018
+ function clone(item) {
4019
+ return JSON.parse(JSON.stringify(item));
4020
+ }
4021
+ function sleep(time) {
4022
+ return __awaiter(this, void 0, void 0, function* () {
4023
+ return new Promise((resolve) => {
4024
+ setTimeout(resolve, time);
4025
+ });
4026
+ });
4027
+ }
4028
+ function getNumberWithOrdinal(n) {
4029
+ const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
4030
+ return n + (s[(v - 20) % 10] || s[v] || s[0]);
4031
+ }
4032
+ function isValidNetwork(network) {
4033
+ return !!networks[network];
4034
+ }
4035
+ function isValidAddress(address) {
4036
+ return isAddress(address) && address !== EMPTY_ADDRESS;
4037
+ }
4038
+ function isValidSnapshot(snapshot, network) {
4039
+ return (snapshot === 'latest' ||
4040
+ (typeof snapshot === 'number' && snapshot >= networks[network].start));
4041
+ }
4042
+ function inputError(message) {
4043
+ return Promise.reject(new Error(message));
4044
+ }
4045
+ var utils = {
4046
+ call,
4047
+ multicall,
4048
+ subgraphRequest,
4049
+ ipfsGet,
4050
+ getUrl,
4051
+ getJSON,
4052
+ sendTransaction,
4053
+ getScores,
4054
+ getVp,
4055
+ validateSchema,
4056
+ getEnsTextRecord,
4057
+ getSpaceUri,
4058
+ getEnsOwner,
4059
+ getSpaceController,
4060
+ getDelegatesBySpace,
4061
+ clone,
4062
+ sleep,
4063
+ getNumberWithOrdinal,
4064
+ voting,
4065
+ getProvider,
4066
+ signMessage,
4067
+ getBlockNumber,
4068
+ Multicaller,
4069
+ getSnapshots,
4070
+ getHash,
4071
+ verify: verify$1,
4072
+ validate,
4073
+ SNAPSHOT_SUBGRAPH_URL
4523
4074
  };
4524
4075
 
4525
- var index = {
4526
- Client: Client,
4527
- Client712: Client,
4528
- schemas: schemas,
4529
- utils: utils
4076
+ var index = {
4077
+ Client: Client,
4078
+ Client712: Client,
4079
+ schemas,
4080
+ utils
4530
4081
  };
4531
4082
 
4532
4083
  export default index;