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