@cowprotocol/iframe-transport 1.1.1 → 2.0.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.
package/index.mjs DELETED
@@ -1,513 +0,0 @@
1
- var y = Object.defineProperty;
2
- var N = (r, t, e) => t in r ? y(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
- var m = (r, t, e) => N(r, typeof t != "symbol" ? t + "" : t, e);
4
- class b {
5
- constructor(t) {
6
- this.key = t;
7
- }
8
- // TODO: Add proper return type annotation
9
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
10
- postMessageToWindow(t, e, n) {
11
- const h = typeof n == "object" ? n : {}, l = {
12
- key: this.key,
13
- method: e,
14
- ...h
15
- };
16
- t.postMessage(
17
- l,
18
- "*"
19
- // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
20
- );
21
- }
22
- listenToMessageFromWindow(t, e, n) {
23
- const h = (l) => {
24
- !S(l.data) || l.data.key !== this.key || l.data.method !== e || n(l.data);
25
- };
26
- return t.addEventListener("message", h), h;
27
- }
28
- // TODO: Add proper return type annotation
29
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
30
- stopListeningToMessageFromWindow(t, e, n) {
31
- t.removeEventListener("message", n);
32
- }
33
- // TODO: Add proper return type annotation
34
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
35
- stopListeningWindowListener(t, e) {
36
- t.removeEventListener("message", e);
37
- }
38
- }
39
- function S(r) {
40
- return typeof r == "object" && r !== null && "key" in r && "method" in r && typeof r.key == "string" && typeof r.method == "string";
41
- }
42
- var R = /* @__PURE__ */ ((r) => (r.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", r.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", r.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", r.SEND_PROVIDER_META_INFO = "SEND_PROVIDER_META_INFO", r.REQUEST_PROVIDER_META_INFO = "REQUEST_PROVIDER_META_INFO", r))(R || {});
43
- const _ = new b(
44
- "cowSwapIframeRpcProviderTransport"
45
- );
46
- function W(r) {
47
- var t, e;
48
- if (r.isWalletConnect)
49
- return (e = (t = r == null ? void 0 : r.session) == null ? void 0 : t.peer) == null ? void 0 : e.metadata;
50
- }
51
- function D(r, t) {
52
- var e;
53
- return (e = t.find((n) => n.provider === r)) == null ? void 0 : e.info;
54
- }
55
- const F = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"], C = [];
56
- window.addEventListener("eip6963:announceProvider", (r) => {
57
- const t = r;
58
- C.push(t.detail);
59
- });
60
- class Q {
61
- /**
62
- * Creates an instance of IframeRpcProviderBridge.
63
- * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
64
- * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
65
- */
66
- constructor(t) {
67
- /**
68
- * The Ethereum provider instance.
69
- * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
70
- * */
71
- m(this, "ethereumProvider", null);
72
- /** Stored JSON-RPC requests, to queue them when disconnected. */
73
- m(this, "requestWaitingForConnection", {});
74
- m(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
75
- if (!this.ethereumProvider) {
76
- t.id && (this.requestWaitingForConnection[t.id] = t);
77
- return;
78
- }
79
- this.processRpcRequest(t);
80
- });
81
- m(this, "processProviderMetaInfoRequest", () => {
82
- if (!this.ethereumProvider) return;
83
- const t = D(this.ethereumProvider, C), e = W(this.ethereumProvider);
84
- _.postMessageToWindow(this.iframeWidow, R.SEND_PROVIDER_META_INFO, {
85
- providerEip6963Info: t,
86
- providerWcMetadata: e
87
- });
88
- });
89
- this.iframeWidow = t;
90
- }
91
- /**
92
- * Disconnects the JSON-RPC bridge from the Ethereum provider.
93
- */
94
- // TODO: Add proper return type annotation
95
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
96
- disconnect() {
97
- this.ethereumProvider = null, _.stopListeningToMessageFromWindow(
98
- window,
99
- R.PROVIDER_RPC_REQUEST,
100
- this.processRpcCallFromWindow
101
- ), _.stopListeningToMessageFromWindow(
102
- window,
103
- R.REQUEST_PROVIDER_META_INFO,
104
- this.processProviderMetaInfoRequest
105
- );
106
- }
107
- /**
108
- * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
109
- * @param newProvider - The Ethereum provider to connect.
110
- */
111
- // TODO: Add proper return type annotation
112
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
113
- onConnect(t) {
114
- this.ethereumProvider ? this.disconnect() : _.listenToMessageFromWindow(
115
- window,
116
- R.PROVIDER_RPC_REQUEST,
117
- this.processRpcCallFromWindow
118
- ), this.ethereumProvider = t, this.processPendingRequests(), F.forEach((e) => {
119
- t.on(e, (n) => this.onProviderEvent(e, n));
120
- }), _.listenToMessageFromWindow(
121
- window,
122
- R.REQUEST_PROVIDER_META_INFO,
123
- this.processProviderMetaInfoRequest
124
- );
125
- }
126
- // TODO: Add proper return type annotation
127
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
128
- processPendingRequests() {
129
- Object.keys(this.requestWaitingForConnection).forEach((t) => {
130
- this.processRpcRequest(this.requestWaitingForConnection[t]);
131
- }), this.requestWaitingForConnection = {};
132
- }
133
- /**
134
- * Processes a JSON-RPC request and sends appropriate response or error via the content window.
135
- * @param request - The JSON-RPC request to be processed.
136
- */
137
- // TODO: Add proper return type annotation
138
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
139
- processRpcRequest(t) {
140
- const { id: e, jsonrpc: n, method: h } = t;
141
- if (!this.ethereumProvider || !e)
142
- return;
143
- (h === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: e })).then(
144
- (E) => this.forwardRpcResponseToIframe({
145
- rpcResponse: { jsonrpc: n, id: e, result: E }
146
- })
147
- ).catch(
148
- (E) => this.forwardRpcResponseToIframe({
149
- rpcResponse: { jsonrpc: n, id: e, error: E }
150
- })
151
- );
152
- }
153
- onProviderEvent(t, e) {
154
- _.postMessageToWindow(this.iframeWidow, R.PROVIDER_ON_EVENT, {
155
- event: t,
156
- params: e
157
- });
158
- }
159
- /**
160
- * Forward a JSON-RPC message to the content window.
161
- */
162
- // TODO: Add proper return type annotation
163
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
164
- forwardRpcResponseToIframe(t) {
165
- _.postMessageToWindow(
166
- this.iframeWidow,
167
- R.PROVIDER_RPC_RESPONSE,
168
- t
169
- );
170
- }
171
- }
172
- var I = { exports: {} }, O;
173
- function k() {
174
- return O || (O = 1, function(r) {
175
- var t = Object.prototype.hasOwnProperty, e = "~";
176
- function n() {
177
- }
178
- Object.create && (n.prototype = /* @__PURE__ */ Object.create(null), new n().__proto__ || (e = !1));
179
- function h(c, i, o) {
180
- this.fn = c, this.context = i, this.once = o || !1;
181
- }
182
- function l(c, i, o, a, v) {
183
- if (typeof o != "function")
184
- throw new TypeError("The listener must be a function");
185
- var p = new h(o, a || c, v), u = e ? e + i : i;
186
- return c._events[u] ? c._events[u].fn ? c._events[u] = [c._events[u], p] : c._events[u].push(p) : (c._events[u] = p, c._eventsCount++), c;
187
- }
188
- function E(c, i) {
189
- --c._eventsCount === 0 ? c._events = new n() : delete c._events[i];
190
- }
191
- function f() {
192
- this._events = new n(), this._eventsCount = 0;
193
- }
194
- f.prototype.eventNames = function() {
195
- var i = [], o, a;
196
- if (this._eventsCount === 0) return i;
197
- for (a in o = this._events)
198
- t.call(o, a) && i.push(e ? a.slice(1) : a);
199
- return Object.getOwnPropertySymbols ? i.concat(Object.getOwnPropertySymbols(o)) : i;
200
- }, f.prototype.listeners = function(i) {
201
- var o = e ? e + i : i, a = this._events[o];
202
- if (!a) return [];
203
- if (a.fn) return [a.fn];
204
- for (var v = 0, p = a.length, u = new Array(p); v < p; v++)
205
- u[v] = a[v].fn;
206
- return u;
207
- }, f.prototype.listenerCount = function(i) {
208
- var o = e ? e + i : i, a = this._events[o];
209
- return a ? a.fn ? 1 : a.length : 0;
210
- }, f.prototype.emit = function(i, o, a, v, p, u) {
211
- var g = e ? e + i : i;
212
- if (!this._events[g]) return !1;
213
- var s = this._events[g], w = arguments.length, P, d;
214
- if (s.fn) {
215
- switch (s.once && this.removeListener(i, s.fn, void 0, !0), w) {
216
- case 1:
217
- return s.fn.call(s.context), !0;
218
- case 2:
219
- return s.fn.call(s.context, o), !0;
220
- case 3:
221
- return s.fn.call(s.context, o, a), !0;
222
- case 4:
223
- return s.fn.call(s.context, o, a, v), !0;
224
- case 5:
225
- return s.fn.call(s.context, o, a, v, p), !0;
226
- case 6:
227
- return s.fn.call(s.context, o, a, v, p, u), !0;
228
- }
229
- for (d = 1, P = new Array(w - 1); d < w; d++)
230
- P[d - 1] = arguments[d];
231
- s.fn.apply(s.context, P);
232
- } else {
233
- var M = s.length, T;
234
- for (d = 0; d < M; d++)
235
- switch (s[d].once && this.removeListener(i, s[d].fn, void 0, !0), w) {
236
- case 1:
237
- s[d].fn.call(s[d].context);
238
- break;
239
- case 2:
240
- s[d].fn.call(s[d].context, o);
241
- break;
242
- case 3:
243
- s[d].fn.call(s[d].context, o, a);
244
- break;
245
- case 4:
246
- s[d].fn.call(s[d].context, o, a, v);
247
- break;
248
- default:
249
- if (!P) for (T = 1, P = new Array(w - 1); T < w; T++)
250
- P[T - 1] = arguments[T];
251
- s[d].fn.apply(s[d].context, P);
252
- }
253
- }
254
- return !0;
255
- }, f.prototype.on = function(i, o, a) {
256
- return l(this, i, o, a, !1);
257
- }, f.prototype.once = function(i, o, a) {
258
- return l(this, i, o, a, !0);
259
- }, f.prototype.removeListener = function(i, o, a, v) {
260
- var p = e ? e + i : i;
261
- if (!this._events[p]) return this;
262
- if (!o)
263
- return E(this, p), this;
264
- var u = this._events[p];
265
- if (u.fn)
266
- u.fn === o && (!v || u.once) && (!a || u.context === a) && E(this, p);
267
- else {
268
- for (var g = 0, s = [], w = u.length; g < w; g++)
269
- (u[g].fn !== o || v && !u[g].once || a && u[g].context !== a) && s.push(u[g]);
270
- s.length ? this._events[p] = s.length === 1 ? s[0] : s : E(this, p);
271
- }
272
- return this;
273
- }, f.prototype.removeAllListeners = function(i) {
274
- var o;
275
- return i ? (o = e ? e + i : i, this._events[o] && E(this, o)) : (this._events = new n(), this._eventsCount = 0), this;
276
- }, f.prototype.off = f.prototype.removeListener, f.prototype.addListener = f.prototype.on, f.prefixed = e, f.EventEmitter = f, r.exports = f;
277
- }(I)), I.exports;
278
- }
279
- var V = k();
280
- const x = 6e5, A = "2.0";
281
- function L() {
282
- return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
283
- }
284
- class q extends Error {
285
- constructor(e, n) {
286
- super(`${e}: ${n}`);
287
- m(this, "isRpcError", !0);
288
- m(this, "code");
289
- m(this, "reason");
290
- this.code = e, this.reason = n;
291
- }
292
- }
293
- class j extends V.EventEmitter {
294
- constructor({
295
- timeoutMilliseconds: e = x,
296
- eventSource: n = window,
297
- eventTarget: h = window.parent
298
- } = {}) {
299
- super();
300
- m(this, "enabled", null);
301
- m(this, "timeoutMilliseconds");
302
- m(this, "eventSource");
303
- m(this, "eventTarget");
304
- m(this, "completers", {});
305
- m(this, "providerMetaInfo", null);
306
- m(this, "providerMetaInfoCallback");
307
- /**
308
- * Handle a Rpc Request
309
- */
310
- // TODO: Add proper return type annotation
311
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
312
- m(this, "handleRpcRequests", ({ rpcResponse: e }) => {
313
- if (e.id === void 0 || e.id === null)
314
- return;
315
- const n = this.completers["" + e.id];
316
- n && ("error" in e || "result" in e ? n.resolve(e) : n.reject(new Error("Response from provider did not have error or result key")), delete this.completers[e.id]);
317
- });
318
- this.timeoutMilliseconds = e, this.eventSource = n, this.eventTarget = h, _.listenToMessageFromWindow(
319
- this.eventSource,
320
- R.PROVIDER_RPC_RESPONSE,
321
- (l) => {
322
- this.handleRpcRequests(l);
323
- }
324
- ), _.listenToMessageFromWindow(
325
- this.eventSource,
326
- R.PROVIDER_ON_EVENT,
327
- (l) => {
328
- this.handleOnEvent(l);
329
- }
330
- ), _.listenToMessageFromWindow(
331
- this.eventSource,
332
- R.SEND_PROVIDER_META_INFO,
333
- (l) => {
334
- this.providerMetaInfo = l, this.providerMetaInfoCallback && this.providerMetaInfoCallback(this.providerMetaInfo);
335
- }
336
- );
337
- }
338
- // TODO: Add proper return type annotation
339
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
340
- request({ method: e, params: n }) {
341
- return this.send(e, n);
342
- }
343
- isConnected() {
344
- return !0;
345
- }
346
- /**
347
- * Differentiate this provider from other providers by providing an isIFrame property that always returns true.
348
- */
349
- get isIFrame() {
350
- return !0;
351
- }
352
- /**
353
- * Always return this for currentProvider.
354
- */
355
- get currentProvider() {
356
- return this;
357
- }
358
- /**
359
- * Helper method that handles transport and request wrapping
360
- * @param method method to execute
361
- * @param params params to pass the method
362
- */
363
- async execute(e, n) {
364
- const h = L(), l = {
365
- jsonrpc: A,
366
- id: h,
367
- method: e,
368
- params: n
369
- }, E = new Promise(
370
- (f, c) => this.completers[h] = { resolve: f, reject: c }
371
- );
372
- return _.postMessageToWindow(this.eventTarget, R.PROVIDER_RPC_REQUEST, {
373
- rpcRequest: l
374
- }), setTimeout(() => {
375
- this.completers[h] && (this.completers[h].reject(new Error("Request timed out. Please try again and submit it faster.")), delete this.completers[h]);
376
- }, this.timeoutMilliseconds), E;
377
- }
378
- // TODO: Replace any with proper type definitions
379
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
380
- async send(e, n) {
381
- const { method: h, params: l } = typeof e == "string" ? { method: e, params: n } : { method: e.method, params: e.params }, E = await this.execute(h, l);
382
- if ("error" in E)
383
- throw new q(E.error.code, E.error.message);
384
- return E.result;
385
- }
386
- /**
387
- * Request the parent window to enable access to the user's web3 provider. Return accounts list immediately if already enabled.
388
- */
389
- async enable() {
390
- if (this.enabled === null) {
391
- const e = this.enabled = this.send("enable", []).catch((n) => {
392
- throw this.enabled === e && (this.enabled = null), n;
393
- });
394
- }
395
- return this.enabled;
396
- }
397
- /**
398
- * Backwards compatibility method for web3.
399
- * @param payload payload to send to the provider
400
- * @param callback callback to be called when the provider resolves
401
- */
402
- async sendAsync(e, n) {
403
- try {
404
- const h = await this.execute(e.method, e.params);
405
- n(null, h);
406
- } catch (h) {
407
- n(h, null);
408
- }
409
- }
410
- /**
411
- * Subscribe to provider meta info
412
- * @param callback
413
- */
414
- // TODO: Add proper return type annotation
415
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
416
- onProviderMetaInfo(e) {
417
- this.providerMetaInfo ? e(this.providerMetaInfo) : (this.providerMetaInfoCallback = e, _.postMessageToWindow(
418
- this.eventTarget,
419
- R.REQUEST_PROVIDER_META_INFO,
420
- null
421
- ));
422
- }
423
- // TODO: Add proper return type annotation
424
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
425
- handleOnEvent(e) {
426
- const n = e.params;
427
- switch (e.event) {
428
- case "notification":
429
- this.emitNotification(n);
430
- break;
431
- case "connect":
432
- this.emitConnect(n);
433
- break;
434
- case "disconnect":
435
- this.emitDisconnect(n);
436
- break;
437
- case "chainChanged":
438
- this.emitChainChanged(n);
439
- break;
440
- case "accountsChanged":
441
- this.emitAccountsChanged(n);
442
- break;
443
- case "message":
444
- this.emitMessage(n);
445
- break;
446
- // Deprecated events below 👇 --------------------------------------
447
- case "networkChanged":
448
- this.emitNetworkChanged(n);
449
- break;
450
- case "close":
451
- this.emitClose(n);
452
- break;
453
- // END OF: Deprecated events --------------------------------------
454
- default:
455
- console.warn(`[WidgetEthereumProvider] Unknown event type: ${e.event}`);
456
- break;
457
- }
458
- }
459
- // TODO: Add proper return type annotation
460
- // TODO: Replace any with proper type definitions
461
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any
462
- emitNotification(e) {
463
- this.emit("notification", e);
464
- }
465
- // TODO: Add proper return type annotation
466
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
467
- emitConnect(e) {
468
- this.enabled === null && (this.enabled = Promise.resolve([])), this.emit("connect", e);
469
- }
470
- /**
471
- * @deprecated See https://eips.ethereum.org/EIPS/eip-1193
472
- */
473
- // TODO: Add proper return type annotation
474
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
475
- emitClose(e) {
476
- Array.isArray(e) && e.length === 2 ? this.emit("close", e[0], e[1]) : this.emit("close");
477
- }
478
- // TODO: Add proper return type annotation
479
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
480
- emitDisconnect(e) {
481
- this.emit("disconnect", e);
482
- }
483
- // TODO: Add proper return type annotation
484
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
485
- emitChainChanged(e) {
486
- this.emit("chainChanged", e);
487
- }
488
- /**
489
- * @deprecated See https://eips.ethereum.org/EIPS/eip-1193
490
- */
491
- // TODO: Add proper return type annotation
492
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
493
- emitNetworkChanged(e) {
494
- this.emit("networkChanged", e);
495
- }
496
- // TODO: Add proper return type annotation
497
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
498
- emitAccountsChanged(e) {
499
- this.enabled = Promise.resolve(e), this.emit("accountsChanged", e);
500
- }
501
- // TODO: Add proper return type annotation
502
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
503
- emitMessage(e) {
504
- this.emit("message", e);
505
- }
506
- }
507
- export {
508
- Q as IframeRpcProviderBridge,
509
- R as IframeRpcProviderEvents,
510
- b as IframeTransport,
511
- j as WidgetEthereumProvider,
512
- _ as iframeRpcProviderTransport
513
- };
package/types.d.ts DELETED
@@ -1,64 +0,0 @@
1
- export interface JsonRpcRequest {
2
- id?: number;
3
- method: string;
4
- params?: any[];
5
- }
6
- export interface JsonRpcRequestMessage {
7
- jsonrpc: '2.0';
8
- id?: number;
9
- method: string;
10
- params: unknown[] | undefined;
11
- }
12
- export interface BaseJsonRpcResponseMessage {
13
- id: number;
14
- jsonrpc: '2.0';
15
- }
16
- export interface JsonRpcSucessfulResponseMessage<TResult = unknown> extends BaseJsonRpcResponseMessage {
17
- result: TResult;
18
- }
19
- export interface JsonRpcError<TData = unknown> {
20
- code: number;
21
- message: string;
22
- data?: TData;
23
- }
24
- export interface JsonRpcErrorResponseMessage<TErrorData = unknown> extends BaseJsonRpcResponseMessage {
25
- error: JsonRpcError<TErrorData>;
26
- }
27
- export type JsonRpcResponse = JsonRpcRequestMessage | JsonRpcErrorResponseMessage | JsonRpcSucessfulResponseMessage;
28
- export interface EthereumProvider {
29
- /**
30
- * Subscribes to Ethereum-related events.
31
- * @param event - The event to subscribe to.
32
- * @param args - Arguments for the event.
33
- */
34
- on(event: string, args: unknown): void;
35
- /**
36
- * Sends a JSON-RPC request to the Ethereum provider and returns the response.
37
- * @param params - JSON-RPC request parameters.
38
- * @returns A promise that resolves with the response.
39
- */
40
- request<T>(params: JsonRpcRequest): Promise<T>;
41
- /**
42
- * Requests permission to connect to the Ethereum provider.
43
- * @returns A promise that resolves once permission is granted.
44
- */
45
- enable(): Promise<void>;
46
- }
47
- export type WindowListener = (event: MessageEvent<unknown>) => void;
48
- export interface ProviderWcMetadata {
49
- name: string;
50
- description: string;
51
- url: string;
52
- icons: string[];
53
- verifyUrl?: string;
54
- redirect?: {
55
- native?: string;
56
- universal?: string;
57
- };
58
- }
59
- export interface EIP6963ProviderInfo {
60
- uuid: string;
61
- name: string;
62
- icon: string;
63
- rdns: string;
64
- }