@snapshot-labs/snapshot.js 0.11.38 → 0.12.0-beta.1

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