univo 0.4.0 → 0.4.2

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.
@@ -0,0 +1,162 @@
1
+ const name = "univo";
2
+ const version = "0.4.2";
3
+
4
+ function createLogger(opts) {
5
+ const noop = (..._) => {
6
+ };
7
+ if (opts.quiet === true) {
8
+ return {
9
+ debug: noop,
10
+ info: noop,
11
+ warn: noop,
12
+ error: noop
13
+ };
14
+ }
15
+ let prefix = `[${name}@${version}]`;
16
+ if (opts.prefix !== void 0) {
17
+ prefix += ` ${opts.prefix}`;
18
+ }
19
+ const debug = (...any) => console.log(`${prefix} DEBUG`, ...any);
20
+ const info = (...any) => console.log(`${prefix} INFO`, ...any);
21
+ const warn = (...any) => console.log(`${prefix} WARN`, ...any);
22
+ const error = (...any) => console.log(`${prefix} ERROR`, ...any);
23
+ if (typeof process !== "undefined" && process.env) {
24
+ if (process.env.LOG_LEVEL === "ERROR") {
25
+ return {
26
+ debug: noop,
27
+ info: noop,
28
+ warn: noop,
29
+ error
30
+ };
31
+ }
32
+ if (process.env.LOG_LEVEL === "WARN" || process.env.LOG_LEVEL === "WARNING") {
33
+ return {
34
+ debug: noop,
35
+ info: noop,
36
+ warn,
37
+ error
38
+ };
39
+ }
40
+ if (process.env.LOG_LEVEL === "INFO") {
41
+ return {
42
+ debug: noop,
43
+ info,
44
+ warn,
45
+ error
46
+ };
47
+ }
48
+ if (process.env.LOG_LEVEL === "DEBUG") {
49
+ return {
50
+ debug,
51
+ info,
52
+ warn,
53
+ error
54
+ };
55
+ }
56
+ }
57
+ if (opts.quiet === false) {
58
+ return {
59
+ debug,
60
+ info,
61
+ warn,
62
+ error
63
+ };
64
+ }
65
+ return {
66
+ debug: noop,
67
+ info: noop,
68
+ warn: noop,
69
+ error: noop
70
+ };
71
+ }
72
+ const iife = (fn) => fn();
73
+ function lifecycle(opts) {
74
+ let disposed = false;
75
+ const finalizers = [];
76
+ const cleanup = (fn) => {
77
+ try {
78
+ Promise.resolve(fn()).catch(opts.onCleanupError);
79
+ } catch (error) {
80
+ opts.onCleanupError(error);
81
+ }
82
+ };
83
+ return {
84
+ isDisposed: () => disposed,
85
+ onCleanup: (fn) => {
86
+ if (disposed) {
87
+ cleanup(fn);
88
+ } else {
89
+ finalizers.push(fn);
90
+ }
91
+ },
92
+ interrupt: () => {
93
+ if (disposed) {
94
+ return;
95
+ }
96
+ disposed = true;
97
+ for (const fn of finalizers.splice(0)) {
98
+ cleanup(fn);
99
+ }
100
+ }
101
+ };
102
+ }
103
+ function queue() {
104
+ let pending = Promise.resolve();
105
+ return (fn) => {
106
+ const result = pending.then(fn);
107
+ pending = result.then(
108
+ () => {
109
+ },
110
+ () => {
111
+ }
112
+ );
113
+ return result;
114
+ };
115
+ }
116
+ function mutex(fn) {
117
+ let locked = false;
118
+ return async (...args) => {
119
+ if (locked) {
120
+ return;
121
+ }
122
+ locked = true;
123
+ try {
124
+ await fn(...args);
125
+ } finally {
126
+ locked = false;
127
+ }
128
+ };
129
+ }
130
+ function isHexEqual(a, b) {
131
+ return a.toLowerCase() === b.toLowerCase();
132
+ }
133
+ async function retry(fn, retries, __count = 1) {
134
+ try {
135
+ return await fn();
136
+ } catch (error) {
137
+ if (__count > retries) throw error;
138
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * 2 ** __count));
139
+ return retry(fn, retries, __count + 1);
140
+ }
141
+ }
142
+ async function compress(input) {
143
+ const compressed = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
144
+ return new Response(compressed).arrayBuffer();
145
+ }
146
+ async function decompress(input) {
147
+ if (input instanceof Blob) {
148
+ const decompressed2 = input.stream().pipeThrough(new DecompressionStream("gzip"));
149
+ return new Response(decompressed2).text();
150
+ }
151
+ const decompressed = new Blob([input]).stream().pipeThrough(new DecompressionStream("gzip"));
152
+ return new Response(decompressed).text();
153
+ }
154
+ const decoder = new TextDecoder();
155
+ const normalizeHex = (hex, length) => {
156
+ if (length === void 0) {
157
+ return hex.toLowerCase();
158
+ }
159
+ return `0x${hex.slice(2).toLowerCase().padStart(length, "0")}`;
160
+ };
161
+
162
+ export { compress as a, iife as b, createLogger as c, decompress as d, decoder as e, name as f, isHexEqual as i, lifecycle as l, mutex as m, normalizeHex as n, queue as q, retry as r, version as v };
@@ -1,11 +1,6 @@
1
1
  import { RpcBlock, RpcTransactionReceipt } from 'viem';
2
2
  import { Storage } from '../metadata.mjs';
3
3
 
4
- type CamelToSnake<T extends string, P extends string = ""> = string extends T ? string : T extends `${infer C0}${infer R}` ? CamelToSnake<R, `${P}${C0 extends Lowercase<C0> ? "" : "_"}${Lowercase<C0>}`> : P;
5
- type Flatten<T> = {
6
- [K in keyof T as CamelToSnake<Extract<K, string>>]: T[K];
7
- };
8
-
9
4
  type Rpc = {
10
5
  /**
11
6
  * All available methods that can be requested
@@ -47,16 +42,13 @@ type IndexerRpc = {
47
42
  */
48
43
  public_finalize: (chain: `0x${string}`) => Promise<void>;
49
44
  /**
50
- * @returns Specified metadata about the indexer
45
+ * @returns Public metadata about the indexer
51
46
  */
52
- private_getMetadata: () => Promise<Metadata>;
47
+ public_getMetadata: () => Promise<PublicMetadata>;
53
48
  /**
54
- * @returns All events defined on this indexer
49
+ * @returns Private metadata about the indexer
55
50
  */
56
- private_getEvents: () => Promise<{
57
- id: string;
58
- filters: Flatten<Filter>[];
59
- }[]>;
51
+ private_getMetadata: () => Promise<PrivateMetadata>;
60
52
  /**
61
53
  * Accepts a list of events and a batch of minified block data and writes to storage
62
54
  * @returns A list of failures that occured for each event and block pair
@@ -82,10 +74,7 @@ type IndexerRpc = {
82
74
  subscribe: Record<string, never>;
83
75
  };
84
76
 
85
- /**
86
- * Types -----------------------------------------------------------------------------------------------------------------------------------
87
- */
88
- type Protocol = "http" | "wss" | "local";
77
+ type Protocol = "http" | "wss" | "local" | "browser";
89
78
  type Transport<R extends Rpc, P extends Protocol = Protocol> = {
90
79
  /**
91
80
  * The underlying transport protocol.
@@ -104,38 +93,33 @@ type Transport<R extends Rpc, P extends Protocol = Protocol> = {
104
93
  * Subscribes to specific event to receive and invoke a callback for a stream of values
105
94
  * @returns An async function to unsubscribe from the stream
106
95
  */
107
- subscribe: <M extends keyof R["subscribe"]>(param: M, handler: (message: R["subscribe"][M]) => void) => Promise<() => Promise<void>>;
96
+ subscribe: <M extends keyof R["subscribe"]>(param: M, listener: (message: R["subscribe"][M]) => void) => Promise<() => Promise<void>>;
108
97
  };
109
98
  /**
110
- * Local -----------------------------------------------------------------------------------------------------------------------------------
99
+ * local -----------------------------------------------------------------------------------------------------------------------------------
111
100
  */
112
101
  declare function local<R extends Rpc>(rpc: R): Transport<R, "local">;
102
+ /**
103
+ * browser -----------------------------------------------------------------------------------------------------------------------------------
104
+ */
105
+ declare function browser(): Transport<Rpc, "browser">;
113
106
  declare function wss<R extends Rpc>(url: string, opts?: {
114
107
  quiet?: boolean;
115
108
  }): Transport<R, "wss">;
116
109
  /**
117
- * HTTP -----------------------------------------------------------------------------------------------------------------------------------
110
+ * http -----------------------------------------------------------------------------------------------------------------------------------
118
111
  */
119
112
  declare function http<R extends Rpc>(url: string, opts?: {
120
113
  signingKey?: string;
121
114
  }): Transport<R, "http">;
122
115
 
116
+ type CamelToSnake<T extends string, P extends string = ""> = string extends T ? string : T extends `${infer C0}${infer R}` ? CamelToSnake<R, `${P}${C0 extends Lowercase<C0> ? "" : "_"}${Lowercase<C0>}`> : P;
117
+ type Flatten<T> = {
118
+ [K in keyof T as CamelToSnake<Extract<K, string>>]: T[K];
119
+ };
120
+
123
121
  /**
124
- * The minimum RPC data required to process a block.
125
- *
126
- * Extend this interface in your application to expose additional RPC methods to every event:
127
- *
128
- * ```ts
129
- * import "univo";
130
- *
131
- * declare module "univo" {
132
- * interface Block {
133
- * eth_getBalance: `0x${string}`;
134
- * }
135
- * }
136
- * ```
137
- *
138
- * Your `getBlock` function must also return any required fields added by the augmentation.
122
+ * Block
139
123
  */
140
124
  interface Block {
141
125
  eth_chainId: `0x${string}`;
@@ -156,6 +140,8 @@ type Filter = {
156
140
  event?: `0x${string}`;
157
141
  /** Index blocks that involve this address */
158
142
  address?: `0x${string}`;
143
+ /** Index blocks where this function signature was invoked */
144
+ function?: `0x${string}`;
159
145
  };
160
146
  /**
161
147
  * Events -----------------------------------------------------------------------------------------------------------------------------------
@@ -276,9 +262,16 @@ type Head = {
276
262
  number: `0x${string}`;
277
263
  parent_hash: `0x${string}`;
278
264
  };
279
- type Metadata = {
265
+ type PublicMetadata = {
266
+ chains: `0x${string}`[];
267
+ };
268
+ type PrivateMetadata = {
280
269
  version: string;
281
270
  language: string;
271
+ events: {
272
+ id: string;
273
+ filters: Flatten<Filter>[];
274
+ }[];
282
275
  };
283
276
  type Result = {
284
277
  status: string;
@@ -350,5 +343,5 @@ type Indexer = {
350
343
  };
351
344
  declare function defineIndexer(opts: Indexer): Transport<IndexerRpc, "local">;
352
345
 
353
- export { defineEvent as a, defineAction as b, defineIndexer as d, http as h, local as l, wss as w };
354
- export type { Action as A, Block as B, Event as E, Filter as F, Head as H, IndexerRpc as I, Metadata as M, Rpc as R, Transport as T, Indexer as c, Result as e };
346
+ export { defineEvent as a, browser as b, defineAction as c, defineIndexer as d, http as h, local as l, wss as w };
347
+ export type { Action as A, Block as B, Event as E, Filter as F, Head as H, IndexerRpc as I, PublicMetadata as P, Rpc as R, Transport as T, Indexer as e, PrivateMetadata as f, Result as g };
@@ -1,4 +1,4 @@
1
- export { T as Transport, h as http, l as local, w as wss } from './shared/univo.DYd1g40o.mjs';
1
+ export { T as Transport, b as browser, h as http, l as local, w as wss } from './shared/univo.Ckj3I8tQ.mjs';
2
2
  import 'viem';
3
3
  import './metadata.mjs';
4
4
  import './metadata/adapters.mjs';
@@ -1,4 +1,4 @@
1
- export { T as Transport, h as http, l as local, w as wss } from './shared/univo.CEA4vY0E.js';
1
+ export { T as Transport, b as browser, h as http, l as local, w as wss } from './shared/univo.7S1OTdpc.js';
2
2
  import 'viem';
3
3
  import './metadata.js';
4
4
  import './metadata/adapters.js';
@@ -1,6 +1,6 @@
1
1
  import ws from 'ws';
2
2
  import { WebSocket } from 'partysocket';
3
- import { a as compress, c as createLogger, m as mutex } from './shared/univo.mlthZw0m.mjs';
3
+ import { a as compress, c as createLogger, m as mutex } from './shared/univo.CUNaTwXY.mjs';
4
4
 
5
5
  const DEFAULT_TIMEOUT_MS = 60 * 1e3;
6
6
  function local(rpc) {
@@ -16,6 +16,15 @@ function local(rpc) {
16
16
  };
17
17
  return { protocol: "local", request, subscribe };
18
18
  }
19
+ function browser() {
20
+ const request = async (_) => {
21
+ throw new Error("Unable to `request` on `browser` transport");
22
+ };
23
+ const subscribe = async () => {
24
+ throw new Error("Unable to `subscribe` on `local` transport");
25
+ };
26
+ return { protocol: "browser", request, subscribe };
27
+ }
19
28
  function createSocket(url, opts) {
20
29
  const socket = new WebSocket(url, [], { WebSocket: ws });
21
30
  socket.binaryType = "arraybuffer";
@@ -29,30 +38,32 @@ function wss(url, opts = {}) {
29
38
  if (!url.startsWith("wss://")) {
30
39
  throw new Error("Websocket connections must start with `wss://`");
31
40
  }
32
- const log = createLogger({ quiet: opts.quiet ?? false });
41
+ const log = createLogger({ quiet: opts.quiet });
33
42
  let id = 0;
34
43
  const requests = /* @__PURE__ */ new Map();
35
- const subscriptions = /* @__PURE__ */ new Map();
36
- const params = /* @__PURE__ */ new Map();
44
+ const subscriptions = {
45
+ node: /* @__PURE__ */ new Map(),
46
+ abstraction: /* @__PURE__ */ new Map()
47
+ };
37
48
  const socket = createSocket(url, {
38
49
  async onError(cause) {
39
50
  log.error(`Socket error: ${cause.message}`);
40
51
  },
41
52
  async onOpen() {
42
- if (subscriptions.size === 0) {
53
+ if (subscriptions.node.size === 0) {
43
54
  return;
44
55
  }
45
- const params2 = [];
46
- for (const [id2, subscription] of subscriptions) {
47
- params2.push(subscription.param);
56
+ const params = [];
57
+ for (const [id2, subscription] of subscriptions.node) {
58
+ params.push(subscription.param);
48
59
  request({ method: "eth_unsubscribe", params: [id2] }).catch(() => {
49
60
  log.warn("Failed to cancel old susbcription");
50
61
  });
51
- subscriptions.delete(id2);
62
+ subscriptions.node.delete(id2);
52
63
  }
53
- for (const param of params2) {
64
+ for (const param of params) {
54
65
  request({ method: "eth_subscribe", params: [param] }).then((id2) => {
55
- subscriptions.set(id2, { param, latest: Date.now() });
66
+ subscriptions.node.set(id2, { param, latest: Date.now() });
56
67
  });
57
68
  }
58
69
  },
@@ -62,26 +73,28 @@ function wss(url, opts = {}) {
62
73
  async onMessage(event) {
63
74
  const data = JSON.parse(event.data);
64
75
  if (data.method === "eth_subscription") {
65
- const subscription = subscriptions.get(data.params.subscription);
66
- if (subscription === void 0) {
76
+ const param = subscriptions.node.get(data.params.subscription);
77
+ if (param === void 0) {
67
78
  return await request({ method: "eth_unsubscribe", params: [data.params.subscription] }).catch(() => {
68
79
  log.warn("Failed to unsubscribe stale subscription");
69
80
  });
70
81
  }
71
- const handlers = params.get(subscription.param);
72
- if (handlers === void 0) {
82
+ const listeners = subscriptions.abstraction.get(param.param);
83
+ if (listeners === void 0) {
73
84
  return await request({ method: "eth_unsubscribe", params: [data.params.subscription] }).catch(() => {
74
85
  log.warn("Failed to unsubscribe stale subscription");
75
86
  });
76
87
  }
77
- for (const handler2 of handlers) {
88
+ for (const listener of listeners) {
78
89
  try {
79
- handler2(data.params.result);
80
- } catch (cause) {
81
- log.error(new Error("Handler error", { cause }));
90
+ listener(data.params.result);
91
+ } catch (error) {
92
+ if (error instanceof Error) {
93
+ log.error(error.message);
94
+ }
82
95
  }
83
96
  }
84
- subscription.latest = Date.now();
97
+ param.latest = Date.now();
85
98
  return;
86
99
  }
87
100
  const handler = requests.get(data.id);
@@ -123,34 +136,39 @@ function wss(url, opts = {}) {
123
136
  }
124
137
  });
125
138
  };
126
- const subscribe = async (param, handler) => {
127
- const handlers = params.get(param);
128
- if (handlers === void 0) {
129
- const handlers2 = (/* @__PURE__ */ new Set()).add(handler);
130
- params.set(param, handlers2);
139
+ const subscribe = async (param, listener) => {
140
+ const listeners = subscriptions.abstraction.get(param);
141
+ if (listeners === void 0) {
142
+ const listeners2 = /* @__PURE__ */ new Set();
143
+ listeners2.add(listener);
144
+ subscriptions.abstraction.set(param, listeners2);
131
145
  const id2 = await request({ method: "eth_subscribe", params: [param] }).catch((cause) => {
132
146
  throw new Error(`Failed to initialise subscription for param ${param}`, { cause });
133
147
  });
134
- subscriptions.set(id2, { param, latest: Date.now() });
148
+ subscriptions.node.set(id2, { param, latest: Date.now() });
135
149
  } else {
136
- handlers.add(handler);
150
+ listeners.add(listener);
137
151
  }
138
152
  return async function unsubscribe() {
139
- const handlers2 = params.get(param);
140
- if (handlers2 === void 0) {
153
+ const listeners2 = subscriptions.abstraction.get(param);
154
+ if (listeners2 === void 0) {
141
155
  return log.warn("Param already unsubscribed...");
142
156
  }
143
- handlers2.delete(handler);
144
- if (handlers2.size === 0) {
145
- await request({ method: "eth_unsubscribe", params: [id] }).catch(() => {
146
- log.warn("Failed to unsubscribe unused subscription");
147
- });
157
+ listeners2.delete(listener);
158
+ if (listeners2.size === 0) {
159
+ for (const [id2, _param] of subscriptions.node) {
160
+ if (param === _param.param) {
161
+ await request({ method: "eth_unsubscribe", params: [id2] }).catch(() => {
162
+ log.warn("Failed to unsubscribe unused subscription");
163
+ });
164
+ }
165
+ }
148
166
  }
149
167
  };
150
168
  };
151
169
  function healthcheck() {
152
170
  try {
153
- const failed = Object.values(subscriptions).some((subscription) => {
171
+ const failed = Object.values(subscriptions.node).some((subscription) => {
154
172
  return Date.now() - subscription.latest > 60 * 1e3;
155
173
  });
156
174
  if (!failed) {
@@ -212,4 +230,4 @@ function http(url, opts = {}) {
212
230
  return { protocol: "http", request, subscribe };
213
231
  }
214
232
 
215
- export { http, local, wss };
233
+ export { browser, http, local, wss };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "univo",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "0.4.0",
5
+ "version": "0.4.2",
6
6
  "sideEffects": false,
7
7
  "module": "./dist/index.mjs",
8
8
  "types": "./dist/index.d.ts",
@@ -1,91 +0,0 @@
1
- const name = "univo";
2
- const version = "0.4.0";
3
-
4
- function createLogger(opts) {
5
- let prefix = `[${name}@${version}]`;
6
- if (opts.prefix !== void 0) {
7
- prefix += ` ${opts.prefix}`;
8
- }
9
- return {
10
- debug(...any) {
11
- if (opts.quiet) {
12
- return;
13
- }
14
- if (process.env.LOG_LEVEL === "DEBUG") {
15
- console.log(`${prefix} DEBUG`, ...any);
16
- }
17
- },
18
- info(...any) {
19
- if (opts.quiet) {
20
- return;
21
- }
22
- if (process.env.LOG_LEVEL === "DEBUG" || process.env.LOG_LEVEL === "INFO") {
23
- console.log(`${prefix} INFO`, ...any);
24
- }
25
- },
26
- warn(...any) {
27
- if (opts.quiet) {
28
- return;
29
- }
30
- if (process.env.LOG_LEVEL === "DEBUG" || process.env.LOG_LEVEL === "INFO" || process.env.LOG_LEVEL === "WARN") {
31
- console.log(`${prefix} WARN`, ...any);
32
- }
33
- },
34
- error(...any) {
35
- if (opts.quiet) {
36
- return;
37
- }
38
- if (process.env.LOG_LEVEL === "DEBUG" || process.env.LOG_LEVEL === "INFO" || process.env.LOG_LEVEL === "WARN" || process.env.LOG_LEVEL === "ERROR") {
39
- console.log(`${prefix} ERROR`, ...any);
40
- }
41
- }
42
- };
43
- }
44
- const iife = (fn) => fn();
45
- function mutex(fn) {
46
- let locked = false;
47
- return async (...args) => {
48
- if (locked) {
49
- return;
50
- }
51
- locked = true;
52
- try {
53
- await fn(...args);
54
- } finally {
55
- locked = false;
56
- }
57
- };
58
- }
59
- function isHexEqual(a, b) {
60
- return a.toLowerCase() === b.toLowerCase();
61
- }
62
- async function retry(fn, retries, __count = 1) {
63
- try {
64
- return await fn();
65
- } catch (error) {
66
- if (__count > retries) throw error;
67
- await new Promise((resolve) => setTimeout(resolve, 1e3 * 2 ** __count));
68
- return retry(fn, retries, __count + 1);
69
- }
70
- }
71
- async function compress(input) {
72
- const compressed = new Blob([input]).stream().pipeThrough(new CompressionStream("gzip"));
73
- return new Response(compressed).arrayBuffer();
74
- }
75
- async function decompress(input) {
76
- if (input instanceof Blob) {
77
- const decompressed2 = input.stream().pipeThrough(new DecompressionStream("gzip"));
78
- return new Response(decompressed2).text();
79
- }
80
- const decompressed = new Blob([input]).stream().pipeThrough(new DecompressionStream("gzip"));
81
- return new Response(decompressed).text();
82
- }
83
- const decoder = new TextDecoder();
84
- const normalizeHex = (hex, length) => {
85
- if (length === void 0) {
86
- return hex.toLowerCase();
87
- }
88
- return `0x${hex.slice(2).toLowerCase().padStart(length, "0")}`;
89
- };
90
-
91
- export { compress as a, iife as b, createLogger as c, decompress as d, decoder as e, name as f, isHexEqual as i, mutex as m, normalizeHex as n, retry as r, version as v };