@snapshot-labs/snapshot.js 0.11.37 → 0.11.39

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