@snapshot-labs/snapshot.js 0.7.2 → 0.8.0-beta.0

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.
package/dist/utils.d.ts CHANGED
@@ -5,6 +5,8 @@ import { signMessage, getBlockNumber } from './utils/web3';
5
5
  import { getHash, verify } from './sign/utils';
6
6
  interface Options {
7
7
  url?: string;
8
+ timeout?: number;
9
+ headers?: any;
8
10
  }
9
11
  interface Strategy {
10
12
  name: string;
@@ -23,14 +25,19 @@ export declare const SNAPSHOT_SUBGRAPH_URL: {
23
25
  };
24
26
  export declare function call(provider: any, abi: any[], call: any[], options?: any): Promise<any>;
25
27
  export declare function multicall(network: string, provider: any, abi: any[], calls: any[], options?: any): Promise<any>;
26
- export declare function subgraphRequest(url: string, query: any, options?: any): Promise<any>;
27
- export declare function getUrl(uri: any, gateway?: string): any;
28
- export declare function getJSON(uri: any, options?: any): Promise<any>;
29
- export declare function ipfsGet(gateway: string, ipfsHash: string, protocolType?: string): Promise<any>;
28
+ export declare function subgraphRequest(url: string, query: any, options?: Options): Promise<any>;
29
+ export declare function getUrl(uri: string, gateway?: string): string | null;
30
+ export declare function getJSON(uri: string, options?: Options & {
31
+ gateways?: string;
32
+ }): Promise<any>;
33
+ export declare function ipfsGet(gateway: string, ipfsHash: string, protocolType?: string, options?: Options): Promise<any>;
30
34
  export declare function sendTransaction(web3: any, contractAddress: string, abi: any[], action: string, params: any[], overrides?: {}): Promise<any>;
31
- export declare function getScores(space: string, strategies: Strategy[], network: string, addresses: string[], snapshot?: number | string, scoreApiUrl?: string, options?: any): Promise<any>;
35
+ export declare function getScores(space: string, strategies: Strategy[], network: string, addresses: string[], snapshot?: number | string, scoreApiUrl?: string, options?: Options & {
36
+ returnValue?: string;
37
+ pathname?: string;
38
+ }): Promise<any>;
32
39
  export declare function getVp(address: string, network: string, strategies: Strategy[], snapshot: number | 'latest', space: string, delegation: boolean, options?: Options): Promise<any>;
33
- export declare function validate(validation: string, author: string, space: string, network: string, snapshot: number | 'latest', params: any, options: any): Promise<any>;
40
+ export declare function validate(validation: string, author: string, space: string, network: string, snapshot: number | 'latest', params: any, options?: Options): Promise<any>;
34
41
  export declare function validateSchema(schema: any, data: any): true | import("ajv").ErrorObject<string, Record<string, any>, unknown>[] | null | undefined;
35
42
  export declare function getEnsTextRecord(ens: string, record: string, network?: string, options?: any): Promise<any>;
36
43
  export declare function getSpaceUri(id: string, network?: string, options?: any): Promise<string | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snapshot-labs/snapshot.js",
3
- "version": "0.7.2",
3
+ "version": "0.8.0-beta.0",
4
4
  "repository": "snapshot-labs/snapshot.js",
5
5
  "license": "MIT",
6
6
  "main": "dist/snapshot.cjs.js",
@@ -19,9 +19,9 @@
19
19
  "@ethersproject/wallet": "^5.6.2",
20
20
  "ajv": "^8.11.0",
21
21
  "ajv-formats": "^2.1.1",
22
- "cross-fetch": "^3.1.6",
23
22
  "json-to-graphql-query": "^2.2.4",
24
- "lodash.set": "^4.3.2"
23
+ "lodash.set": "^4.3.2",
24
+ "ofetch": "^1.3.3"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@rollup/plugin-commonjs": "^18.1.0",
@@ -0,0 +1,18 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$ref": "#/definitions/Alias",
4
+ "definitions": {
5
+ "Alias": {
6
+ "title": "Alias",
7
+ "type": "object",
8
+ "properties": {
9
+ "alias": {
10
+ "type": "string",
11
+ "format": "address"
12
+ }
13
+ },
14
+ "required": ["alias"],
15
+ "additionalProperties": false
16
+ }
17
+ }
18
+ }
@@ -5,6 +5,7 @@ import vote from './vote.json';
5
5
  import profile from './profile.json';
6
6
  import statement from './statement.json';
7
7
  import zodiac from './zodiac.json';
8
+ import alias from './alias.json';
8
9
 
9
10
  export default {
10
11
  space: space.definitions.Space,
@@ -13,5 +14,6 @@ export default {
13
14
  vote: vote.definitions.Vote,
14
15
  profile: profile.definitions.Profile,
15
16
  statement: statement.definitions.Statement,
16
- zodiac: zodiac.definitions.Zodiac
17
+ zodiac: zodiac.definitions.Zodiac,
18
+ alias: alias.definitions.Alias
17
19
  };
package/src/sign/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import fetch from 'cross-fetch';
1
+ import { ofetch as fetch } from 'ofetch';
2
2
  import { Web3Provider } from '@ethersproject/providers';
3
3
  import { Wallet } from '@ethersproject/wallet';
4
4
  import { getAddress } from '@ethersproject/address';
@@ -89,16 +89,18 @@ export default class Client {
89
89
  Accept: 'application/json',
90
90
  'Content-Type': 'application/json'
91
91
  },
92
- body: JSON.stringify(envelop)
92
+ timeout: this.options.timeout || 20e3,
93
+ body: envelop
93
94
  };
94
- return new Promise((resolve, reject) => {
95
- fetch(address, init)
96
- .then((res) => {
97
- if (res.ok) return resolve(res.json());
98
- throw res;
99
- })
100
- .catch((e) => e.json().then((json) => reject(json)));
101
- });
95
+
96
+ try {
97
+ return await fetch(address, init);
98
+ } catch (e) {
99
+ const isSequencerError =
100
+ e.data?.hasOwnProperty('error') &&
101
+ e.data?.hasOwnProperty('error_description');
102
+ return Promise.reject(isSequencerError ? e.data : e);
103
+ }
102
104
  }
103
105
 
104
106
  async space(web3: Web3Provider | Wallet, address: string, message: Space) {
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ exports.__esModule = true;
14
+ exports.getBatchedProvider = void 0;
15
+ var providers_1 = require("@ethersproject/providers");
16
+ var networks_json_1 = require("../networks.json");
17
+ var providers = {};
18
+ function getProvider(network, type) {
19
+ var _a;
20
+ if (type === void 0) { type = 'archive'; }
21
+ var url = networks_json_1["default"][network].rpc[0];
22
+ if (type === 'light' && ((_a = networks_json_1["default"][network].light) === null || _a === void 0 ? void 0 : _a.length))
23
+ url = networks_json_1["default"][network].light[0];
24
+ var connectionInfo = typeof url === 'object'
25
+ ? __assign(__assign({}, url), { timeout: 25000 }) : { url: url, timeout: 25000 };
26
+ if (!providers[network] || !providers[network][type]) {
27
+ providers[network] = __assign({}, providers[network]);
28
+ providers[network][type] = new providers_1.StaticJsonRpcProvider(connectionInfo);
29
+ }
30
+ return providers[network][type];
31
+ }
32
+ exports["default"] = getProvider;
33
+ function getBatchedProvider(network, type) {
34
+ var _a;
35
+ if (type === void 0) { type = 'archive'; }
36
+ var url = networks_json_1["default"][network].rpc[0];
37
+ if (type === 'light' && ((_a = networks_json_1["default"][network].light) === null || _a === void 0 ? void 0 : _a.length))
38
+ url = networks_json_1["default"][network].light[0];
39
+ var connectionInfo = typeof url === 'object'
40
+ ? __assign(__assign({}, url), { timeout: 25000 }) : { url: url, timeout: 25000 };
41
+ if (!providers[network] || !providers[network][type]) {
42
+ providers[network] = __assign({}, providers[network]);
43
+ providers[network][type] = new providers_1.JsonRpcBatchProvider(connectionInfo);
44
+ }
45
+ return providers[network][type];
46
+ }
47
+ exports.getBatchedProvider = getBatchedProvider;
package/src/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
- import fetch from 'cross-fetch';
1
+ import { ofetch as fetch } from 'ofetch';
2
2
  import { Interface } from '@ethersproject/abi';
3
3
  import { Contract } from '@ethersproject/contracts';
4
4
  import { isAddress } from '@ethersproject/address';
@@ -19,6 +19,8 @@ import voting from './voting';
19
19
 
20
20
  interface Options {
21
21
  url?: string;
22
+ timeout?: number;
23
+ headers?: any;
22
24
  }
23
25
 
24
26
  interface Strategy {
@@ -135,38 +137,56 @@ export async function multicall(
135
137
  }
136
138
  }
137
139
 
138
- export async function subgraphRequest(url: string, query, options: any = {}) {
139
- const res = await fetch(url, {
140
- method: 'POST',
141
- headers: {
142
- Accept: 'application/json',
143
- 'Content-Type': 'application/json',
144
- ...options?.headers
145
- },
146
- body: JSON.stringify({ query: jsonToGraphQLQuery({ query }) })
147
- });
148
- let responseData: any = await res.text();
140
+ export async function subgraphRequest(url: string, query, options?: Options) {
149
141
  try {
150
- responseData = JSON.parse(responseData);
142
+ const init = {
143
+ method: 'POST',
144
+ headers: {
145
+ Accept: 'application/json',
146
+ 'Content-Type': 'application/json',
147
+ ...options?.headers
148
+ },
149
+ timeout: options?.timeout || 20e3,
150
+ body: { query: jsonToGraphQLQuery({ query }) }
151
+ };
152
+
153
+ const body = await fetch(url, init);
154
+
155
+ if (typeof body === 'string') {
156
+ return Promise.reject({
157
+ errors: [
158
+ {
159
+ message: 'Body is not a JSON object',
160
+ extensions: { code: 'INVALID_JSON' }
161
+ }
162
+ ]
163
+ });
164
+ }
165
+
166
+ if (body.errors) {
167
+ return Promise.reject(body);
168
+ }
169
+
170
+ return body.data;
151
171
  } catch (e) {
152
- throw new Error(
153
- `Errors found in subgraphRequest: URL: ${url}, Status: ${
154
- res.status
155
- }, Response: ${responseData.substring(0, 400)}`
156
- );
157
- }
158
- if (responseData.errors) {
159
- throw new Error(
160
- `Errors found in subgraphRequest: URL: ${url}, Status: ${
161
- res.status
162
- }, Response: ${JSON.stringify(responseData.errors).substring(0, 400)}`
172
+ return Promise.reject(
173
+ e.data?.errors
174
+ ? e.data
175
+ : {
176
+ errors: [
177
+ {
178
+ message: e.statusText || e.toString(),
179
+ extensions: {
180
+ code: e.status || 0
181
+ }
182
+ }
183
+ ]
184
+ }
163
185
  );
164
186
  }
165
- const { data } = responseData;
166
- return data || {};
167
187
  }
168
188
 
169
- export function getUrl(uri, gateway = gateways[0]) {
189
+ export function getUrl(uri: string, gateway = gateways[0]) {
170
190
  const ipfsGateway = `https://${gateway}`;
171
191
  if (!uri) return null;
172
192
  if (
@@ -184,18 +204,40 @@ export function getUrl(uri, gateway = gateways[0]) {
184
204
  return uri;
185
205
  }
186
206
 
187
- export async function getJSON(uri, options: any = {}) {
188
- const url = getUrl(uri, options.gateways);
189
- return fetch(url).then((res) => res.json());
207
+ export async function getJSON(
208
+ uri: string,
209
+ options: Options & { gateways?: string } = {}
210
+ ) {
211
+ const url = getUrl(uri, options.gateways) || '';
212
+ const body = await fetch(url, {
213
+ timeout: options.timeout || 30e3,
214
+ headers: {
215
+ Accept: 'application/json',
216
+ 'Content-Type': 'application/json',
217
+ ...options?.headers
218
+ }
219
+ });
220
+
221
+ return typeof body === 'string' ? JSON.parse(body) : body;
190
222
  }
191
223
 
192
224
  export async function ipfsGet(
193
225
  gateway: string,
194
226
  ipfsHash: string,
195
- protocolType = 'ipfs'
227
+ protocolType = 'ipfs',
228
+ options: Options = {}
196
229
  ) {
197
230
  const url = `https://${gateway}/${protocolType}/${ipfsHash}`;
198
- return fetch(url).then((res) => res.json());
231
+ const body = await fetch(url, {
232
+ timeout: options.timeout || 20e3,
233
+ headers: {
234
+ Accept: 'application/json',
235
+ 'Content-Type': 'application/json',
236
+ ...options.headers
237
+ }
238
+ });
239
+
240
+ return typeof body === 'string' ? JSON.parse(body) : body;
199
241
  }
200
242
 
201
243
  export async function sendTransaction(
@@ -220,10 +262,10 @@ export async function getScores(
220
262
  addresses: string[],
221
263
  snapshot: number | string = 'latest',
222
264
  scoreApiUrl = 'https://score.snapshot.org',
223
- options: any = {}
265
+ options: Options & { returnValue?: string; pathname?: string } = {}
224
266
  ) {
225
267
  const url = new URL(scoreApiUrl);
226
- url.pathname = '/api/scores';
268
+ url.pathname = options.pathname || '/api/scores';
227
269
  scoreApiUrl = url.toString();
228
270
 
229
271
  try {
@@ -234,25 +276,25 @@ export async function getScores(
234
276
  strategies,
235
277
  addresses
236
278
  };
237
- const res = await fetch(scoreApiUrl, {
279
+
280
+ const body = await fetch(scoreApiUrl, {
238
281
  method: 'POST',
239
282
  headers: scoreApiHeaders,
240
- body: JSON.stringify({ params })
283
+ timeout: options.timeout || 60e3,
284
+ body: { params }
241
285
  });
242
- const obj = await res.json();
243
-
244
- if (obj.error) {
245
- return Promise.reject(obj.error);
246
- }
247
286
 
248
287
  return options.returnValue === 'all'
249
- ? obj.result
250
- : obj.result[options.returnValue || 'scores'];
288
+ ? body.result
289
+ : body.result[options.returnValue || 'scores'];
251
290
  } catch (e) {
252
- if (e.errno) {
253
- return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
254
- }
255
- return Promise.reject(e);
291
+ return Promise.reject(
292
+ e.data?.error || {
293
+ code: e.status || 0,
294
+ message: e.statusText || e.toString(),
295
+ data: e.data || ''
296
+ }
297
+ );
256
298
  }
257
299
  }
258
300
 
@@ -263,14 +305,14 @@ export async function getVp(
263
305
  snapshot: number | 'latest',
264
306
  space: string,
265
307
  delegation: boolean,
266
- options?: Options
308
+ options: Options = {}
267
309
  ) {
268
- if (!options) options = {};
269
- if (!options.url) options.url = 'https://score.snapshot.org';
310
+ const url = options.url || 'https://score.snapshot.org';
270
311
  const init = {
271
312
  method: 'POST',
272
313
  headers: scoreApiHeaders,
273
- body: JSON.stringify({
314
+ timeout: options.timeout || 60e3,
315
+ body: {
274
316
  jsonrpc: '2.0',
275
317
  method: 'get_vp',
276
318
  params: {
@@ -281,19 +323,20 @@ export async function getVp(
281
323
  space,
282
324
  delegation
283
325
  }
284
- })
326
+ }
285
327
  };
286
328
 
287
329
  try {
288
- const res = await fetch(options.url, init);
289
- const json = await res.json();
290
- if (json.error) return Promise.reject(json.error);
291
- if (json.result) return json.result;
330
+ const body = await fetch(url, init);
331
+ return body.result;
292
332
  } catch (e) {
293
- if (e.errno) {
294
- return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
295
- }
296
- return Promise.reject(e);
333
+ return Promise.reject(
334
+ e.data?.error || {
335
+ code: e.status || 0,
336
+ message: e.statusText || e.toString(),
337
+ data: e.data || ''
338
+ }
339
+ );
297
340
  }
298
341
  }
299
342
 
@@ -304,14 +347,14 @@ export async function validate(
304
347
  network: string,
305
348
  snapshot: number | 'latest',
306
349
  params: any,
307
- options: any
350
+ options: Options = {}
308
351
  ) {
309
- if (!options) options = {};
310
- if (!options.url) options.url = 'https://score.snapshot.org';
352
+ const url = options.url || 'https://score.snapshot.org';
311
353
  const init = {
312
354
  method: 'POST',
313
355
  headers: scoreApiHeaders,
314
- body: JSON.stringify({
356
+ timeout: options.timeout || 30e3,
357
+ body: {
315
358
  jsonrpc: '2.0',
316
359
  method: 'validate',
317
360
  params: {
@@ -322,19 +365,20 @@ export async function validate(
322
365
  snapshot,
323
366
  params
324
367
  }
325
- })
368
+ }
326
369
  };
327
370
 
328
371
  try {
329
- const res = await fetch(options.url, init);
330
- const json = await res.json();
331
- if (json.error) return Promise.reject(json.error);
332
- return json.result;
372
+ const body = await fetch(url, init);
373
+ return body.result;
333
374
  } catch (e) {
334
- if (e.errno) {
335
- return Promise.reject({ code: e.errno, message: e.toString(), data: '' });
336
- }
337
- return Promise.reject(e);
375
+ return Promise.reject(
376
+ e.data?.error || {
377
+ code: e.status || 0,
378
+ message: e.statusText || e.toString(),
379
+ data: e.data || ''
380
+ }
381
+ );
338
382
  }
339
383
  }
340
384