@cowprotocol/widget-react 0.5.0-RC.1 → 0.5.0-RC.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.
Files changed (3) hide show
  1. package/index.js +1 -1
  2. package/index.mjs +159 -163
  3. package/package.json +2 -2
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var G=(e,t,n)=>t in e?b(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>(G(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("react/jsx-runtime"),d=require("react"),v="cowSwapWidget";function m(e,t,n){const s={key:v,method:t,...typeof n=="object"?n:{}};e.postMessage(s,"*")}function P(e,t,n){const r=s=>{!M(s.data)||s.data.key!==v||s.data.method!==t||n(s.data)};return e.addEventListener("message",r),r}function M(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function I(e,t,n){e.removeEventListener("message",n)}function A(e,t){e.removeEventListener("message",t)}var _=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(_||{}),l=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(l||{}),O=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(O||{});const q=["connect","disconnect","close","chainChanged","accountsChanged"];class x{constructor(t){p(this,"ethereumProvider",null);p(this,"requestWaitingForConnection",{});p(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,I(window,_.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():P(window,_.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),q.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:s}=t;if(!this.ethereumProvider||!n)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(i=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:i}})).catch(i=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:i}}))}onProviderEvent(t,n){m(this.iframeWidow,l.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){m(this.iframeWidow,l.PROVIDER_RPC_RESPONSE,t)}}function $(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const L={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:$()},D="_";function k(e){const t=L[e.env||"prod"],n=N(e),r=U(e);return t+"/#"+n+"?"+r}function N(e){const{chainId:t=1,sell:n,buy:r,tradeType:s=O.SWAP}=e,c=[(n==null?void 0:n.asset)||D,(r==null?void 0:r.asset)||D].map(encodeURIComponent).join("/");return`/${t}/widget/${s}/${c}`}function U(e){const{sell:t,buy:n,theme:r}=e,s=new URLSearchParams;return t!=null&&t.amount&&s.append("sellAmount",t.amount),n!=null&&n.amount&&s.append("buyAmount",n.amount),r&&s.append("theme",typeof r=="string"?r:r.baseTheme),s}var y=(e=>(e.SWAP_ETH_FLOW_SENT_TX="SWAP_ETH_FLOW_SENT_TX",e.SWAP_POSTED_API="SWAP_POSTED_API",e.SWAP_SIGNING_ERROR="SWAP_SIGNING_ERROR",e.SWAP_TRADE_EXECUTED="SWAP_TRADE_EXECUTED",e.SWAP_ORDER_CANCELLED="SWAP_ORDER_CANCELLED",e))(y||{}),H=(e=>(e.ON_TOAST_MESSAGE="ON_TOAST_MESSAGE",e.ON_POSTED_ORDER="ON_POSTED_ORDER",e.ON_POSTED_ETH_FLOW_ORDER="ON_POSTED_ETH_FLOW_ORDER",e.ON_EXECUTED_ORDER="ON_EXECUTED_ORDER",e.ON_CANCELLED_ORDER="ON_CANCELLED_ORDER",e))(H||{});class V{constructor(){p(this,"subscriptions",{})}on(t){const{event:n,handler:r}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(r)}off(t){const{event:n,handler:r}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(s=>s!==r))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}let X=1;class j{constructor(t,n=[]){p(this,"eventEmitter",new V);p(this,"listeners",[]);p(this,"widgetListener");p(this,"instanceNumber",X++);this.contentWindow=t,this.updateListeners(n),this.widgetListener=P(this.contentWindow,_.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){A(this.contentWindow,this.widgetListener)}updateListeners(t){for(const n of this.listeners)this.eventEmitter.off(n);this.listeners=t||[];for(const n of this.listeners)this.eventEmitter.on(n)}}const F="640px",Q="450px",K=20;function T(e,t){const{params:n,provider:r,listeners:s}=t;let c=r;const i=J(n);e.innerHTML="",e.appendChild(i);const{contentWindow:a}=i;if(!a)throw console.error("Iframe does not contain a window",i),new Error("Iframe does not contain a window!");const R=[];R.push(Y(a,n.appCode)),R.push(z(i,n.height));const h=new j(window,s);let E=W(a,null,c);return i.addEventListener("load",()=>C(a,n,c)),{updateParams:o=>C(a,o,c),updateListeners:o=>h.updateListeners(o),updateProvider:o=>{c=o,E=W(a,E,o)},destroy:()=>{h.stopListeningIframe(),R.forEach(o=>window.removeEventListener("message",o)),e.removeChild(i)}}}function W(e,t,n){t&&t.disconnect();const r=t||new x(e);return n&&r.onConnect(n),r}function J(e){const{width:t=Q,height:n=F}=e,r=document.createElement("iframe");return r.src=k(e),r.width=t,r.height=n,r.style.border="0",r}function C(e,t,n){const r=!!n,s=N(t),c=U(t).toString();m(e,l.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:{...t},hasProvider:r})}function Y(e,t){const n=P(window,_.ACTIVATE,()=>{A(window,n),m(e,l.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})});return n}function z(e,t=F){return P(window,_.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+K}px`:t})}function B(e){const{params:t,provider:n,listeners:r}=e,[s,c]=d.useState(null),i=d.useRef(null),a=d.useRef(n),R=d.useRef(r),h=d.useRef(null),E=d.useRef(null),o=d.useCallback((u,f)=>{try{console.log(`[WIDGET] ${u}`),f()}catch(g){const S=`Error ${u.toLowerCase()}`;console.error(`[WIDGET] ${S}`,g),c({message:S,error:g})}},[c]);return d.useEffect(()=>{if(!h.current||JSON.stringify(i.current)===JSON.stringify(t))return;const u=h.current,f=E.current;i.current=t,f===null?o("Creating a new widget",()=>{E.current=T(u,{params:t,provider:a.current,listeners:r}),R.current=r}):o("Updating the widget",()=>f.updateParams(t))},[t]),d.useEffect(()=>{if(!E.current||a.current===n)return;a.current=n;const u=h.current;u&&o("Updating the provider",()=>{var f;(f=E.current)==null||f.destroy(),E.current=T(u,{params:t,provider:a.current,listeners:r})})},[n]),d.useEffect(()=>{if(!E.current||R.current===r)return;const u=E.current;o("Updating the listeners",()=>u.updateListeners(r))},[r]),s?w.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&w.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):w.jsx("div",{ref:h})}exports.COWSWAP_URLS=L;exports.CowEvents=H;exports.CowSwapWidget=B;exports.SimpleCowEventEmitter=V;exports.ToastMessageType=y;exports.TradeType=O;exports.WidgetMethodsEmit=_;exports.WidgetMethodsListen=l;exports.createCowSwapWidget=T;exports.listenToMessageFromWindow=P;exports.postMessageToWindow=m;exports.stopListeningToMessageFromWindow=I;exports.stopListeningWindowListener=A;
1
+ "use strict";var N=Object.defineProperty;var H=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>(H(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react/jsx-runtime"),u=require("react"),D="cowSwapWidget";function R(n,e,t){const s={key:D,method:e,...typeof t=="object"?t:{}};n.postMessage(s,"*")}function P(n,e,t){const r=s=>{!b(s.data)||s.data.key!==D||s.data.method!==e||t(s.data)};return n.addEventListener("message",r),r}function b(n){return typeof n=="object"&&n!==null&&"key"in n&&"method"in n&&typeof n.key=="string"&&typeof n.method=="string"}function O(n,e,t){n.removeEventListener("message",t)}function _(n,e){n.removeEventListener("message",e)}var l=(n=>(n.ACTIVATE="ACTIVATE",n.UPDATE_HEIGHT="UPDATE_HEIGHT",n.EMIT_COW_EVENT="EMIT_COW_EVENT",n.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",n))(l||{}),m=(n=>(n.UPDATE_PARAMS="UPDATE_PARAMS",n.UPDATE_APP_DATA="UPDATE_APP_DATA",n.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",n.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",n))(m||{}),v=(n=>(n.SWAP="swap",n.LIMIT="limit",n.ADVANCED="advanced",n))(v||{});const F=["connect","disconnect","close","chainChanged","accountsChanged"];class M{constructor(e){h(this,"ethereumProvider",null);h(this,"requestWaitingForConnection",{});h(this,"processRpcCallFromWindow",({rpcRequest:e})=>{if(!this.ethereumProvider){e.id&&(this.requestWaitingForConnection[e.id]=e);return}this.processRpcRequest(e)});this.iframeWidow=e}disconnect(){this.ethereumProvider=null,O(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(e){this.ethereumProvider?this.disconnect():P(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=e,this.processPendingRequests(),F.forEach(t=>{e.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(e=>{this.processRpcRequest(this.requestWaitingForConnection[e])}),this.requestWaitingForConnection={}}processRpcRequest(e){const{id:t,jsonrpc:r,method:s}=e;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...e,id:t})).then(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:o}})).catch(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:o}}))}onProviderEvent(e,t){R(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:e,params:t})}forwardRpcResponseToIframe(e){R(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,e)}}function q(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const L={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:q()},W="_";function x(n){const e=L[n.env||"prod"],t=y(n),r=U(n);return e+"/#"+t+"?"+r}function y(n){const{chainId:e=1,sell:t,buy:r,tradeType:s=v.SWAP}=n,c=[(t==null?void 0:t.asset)||W,(r==null?void 0:r.asset)||W].map(encodeURIComponent).join("/");return`/${e}/widget/${s}/${c}`}function U(n){const{sell:e,buy:t,theme:r}=n,s=new URLSearchParams;return e!=null&&e.amount&&s.append("sellAmount",e.amount),t!=null&&t.amount&&s.append("buyAmount",t.amount),r&&s.append("theme",typeof r=="string"?r:r.baseTheme),s}class G{constructor(){h(this,"subscriptions",{})}on(e){const{event:t,handler:r}=e;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r)}off(e){const{event:t,handler:r}=e;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==r))}emit(e,t){this.subscriptions[e]&&this.subscriptions[e].forEach(r=>r(t))}}let $=1;class k{constructor(e,t=[]){h(this,"eventEmitter",new G);h(this,"listeners",[]);h(this,"widgetListener");h(this,"instanceNumber",$++);this.contentWindow=e,this.updateListeners(t),this.widgetListener=P(this.contentWindow,l.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_(this.contentWindow,this.widgetListener)}updateListeners(e){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=e||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const V="640px",j="450px",Q=20;function T(n,e){const{params:t,provider:r,listeners:s}=e;let c=r;const o=K(t);n.innerHTML="",n.appendChild(o);const{contentWindow:a}=o;if(!a)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const w=[];w.push(J(a,t.appCode)),w.push(Y(o,t.height));const f=new k(window,s);let d=I(a,null,c);return o.addEventListener("load",()=>S(a,t,c)),{updateParams:i=>S(a,i,c),updateListeners:i=>f.updateListeners(i),updateProvider:i=>{c=i,d=I(a,d,i)},destroy:()=>{f.stopListeningIframe(),w.forEach(i=>window.removeEventListener("message",i)),n.removeChild(o)}}}function I(n,e,t){e&&e.disconnect();const r=e||new M(n);return t&&r.onConnect(t),r}function K(n){const{width:e=j,height:t=V}=n,r=document.createElement("iframe");return r.src=x(n),r.width=e,r.height=t,r.style.border="0",r}function S(n,e,t){const r=!!t,s=y(e),c=U(e).toString();R(n,m.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:{...e},hasProvider:r})}function J(n,e){const t=P(window,l.ACTIVATE,()=>{_(window,t),R(n,m.UPDATE_APP_DATA,{metaData:e?{appCode:e}:void 0})});return t}function Y(n,e=V){return P(window,l.UPDATE_HEIGHT,t=>{n.style.height=t.height?`${t.height+Q}px`:e})}function z(n){const{params:e,provider:t,listeners:r}=n,[s,c]=u.useState(null),o=u.useRef(null),a=u.useRef(t),w=u.useRef(r),f=u.useRef(null),d=u.useRef(null),i=u.useCallback((p,E)=>{try{console.log(`[WIDGET] ${p}`),E()}catch(A){const C=`Error ${p.toLowerCase()}`;console.error(`[WIDGET] ${C}`,A),c({message:C,error:A})}},[c]);return u.useEffect(()=>{if(!f.current||JSON.stringify(o.current)===JSON.stringify(e))return;const p=f.current,E=d.current;o.current=e,E===null?i("Creating a new widget",()=>{d.current=T(p,{params:e,provider:a.current,listeners:r}),w.current=r}):i("Updating the widget",()=>E.updateParams(e))},[e]),u.useEffect(()=>{if(!d.current||a.current===t)return;a.current=t;const p=f.current;p&&i("Updating the provider",()=>{var E;(E=d.current)==null||E.destroy(),d.current=T(p,{params:e,provider:a.current,listeners:r})})},[t]),u.useEffect(()=>{if(!d.current||w.current===r)return;const p=d.current;i("Updating the listeners",()=>p.updateListeners(r))},[r]),s?g.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&g.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):g.jsx("div",{ref:f})}exports.COWSWAP_URLS=L;exports.CowSwapWidget=z;exports.TradeType=v;exports.WidgetMethodsEmit=l;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.listenToMessageFromWindow=P;exports.postMessageToWindow=R;exports.stopListeningToMessageFromWindow=O;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -1,283 +1,279 @@
1
- var H = Object.defineProperty;
2
- var V = (e, t, n) => t in e ? H(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var u = (e, t, n) => (V(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { jsxs as y, jsx as O } from "react/jsx-runtime";
5
- import { useState as F, useRef as R, useCallback as b, useEffect as w } from "react";
6
- const v = "cowSwapWidget";
7
- function m(e, t, n) {
1
+ var V = Object.defineProperty;
2
+ var N = (n, e, t) => e in n ? V(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var p = (n, e, t) => (N(n, typeof e != "symbol" ? e + "" : e, t), t);
4
+ import { jsxs as H, jsx as v } from "react/jsx-runtime";
5
+ import { useState as b, useRef as m, useCallback as F, useEffect as g } from "react";
6
+ const W = "cowSwapWidget";
7
+ function P(n, e, t) {
8
8
  const s = {
9
- key: v,
10
- method: t,
11
- ...typeof n == "object" ? n : {}
9
+ key: W,
10
+ method: e,
11
+ ...typeof t == "object" ? t : {}
12
12
  };
13
- e.postMessage(
13
+ n.postMessage(
14
14
  s,
15
15
  "*"
16
16
  // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
17
17
  );
18
18
  }
19
- function P(e, t, n) {
19
+ function R(n, e, t) {
20
20
  const r = (s) => {
21
- !G(s.data) || s.data.key !== v || s.data.method !== t || n(s.data);
21
+ !q(s.data) || s.data.key !== W || s.data.method !== e || t(s.data);
22
22
  };
23
- return e.addEventListener("message", r), r;
23
+ return n.addEventListener("message", r), r;
24
24
  }
25
- function G(e) {
26
- return typeof e == "object" && e !== null && "key" in e && "method" in e && typeof e.key == "string" && typeof e.method == "string";
25
+ function q(n) {
26
+ return typeof n == "object" && n !== null && "key" in n && "method" in n && typeof n.key == "string" && typeof n.method == "string";
27
27
  }
28
- function q(e, t, n) {
29
- e.removeEventListener("message", n);
28
+ function M(n, e, t) {
29
+ n.removeEventListener("message", t);
30
30
  }
31
- function W(e, t) {
32
- e.removeEventListener("message", t);
31
+ function O(n, e) {
32
+ n.removeEventListener("message", e);
33
33
  }
34
- var f = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e))(f || {}), l = /* @__PURE__ */ ((e) => (e.UPDATE_PARAMS = "UPDATE_PARAMS", e.UPDATE_APP_DATA = "UPDATE_APP_DATA", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(l || {}), I = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(I || {});
35
- const $ = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
36
- class x {
34
+ var l = /* @__PURE__ */ ((n) => (n.ACTIVATE = "ACTIVATE", n.UPDATE_HEIGHT = "UPDATE_HEIGHT", n.EMIT_COW_EVENT = "EMIT_COW_EVENT", n.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", n))(l || {}), w = /* @__PURE__ */ ((n) => (n.UPDATE_PARAMS = "UPDATE_PARAMS", n.UPDATE_APP_DATA = "UPDATE_APP_DATA", n.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", n.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", n))(w || {}), S = /* @__PURE__ */ ((n) => (n.SWAP = "swap", n.LIMIT = "limit", n.ADVANCED = "advanced", n))(S || {});
35
+ const G = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
36
+ class $ {
37
37
  /**
38
38
  * Creates an instance of IframeRpcProviderBridge.
39
39
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
40
40
  * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
41
41
  */
42
- constructor(t) {
42
+ constructor(e) {
43
43
  /**
44
44
  * The Ethereum provider instance.
45
45
  * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
46
46
  * */
47
- u(this, "ethereumProvider", null);
47
+ p(this, "ethereumProvider", null);
48
48
  /** Stored JSON-RPC requests, to queue them when disconnected. */
49
- u(this, "requestWaitingForConnection", {});
50
- u(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
49
+ p(this, "requestWaitingForConnection", {});
50
+ p(this, "processRpcCallFromWindow", ({ rpcRequest: e }) => {
51
51
  if (!this.ethereumProvider) {
52
- t.id && (this.requestWaitingForConnection[t.id] = t);
52
+ e.id && (this.requestWaitingForConnection[e.id] = e);
53
53
  return;
54
54
  }
55
- this.processRpcRequest(t);
55
+ this.processRpcRequest(e);
56
56
  });
57
- this.iframeWidow = t;
57
+ this.iframeWidow = e;
58
58
  }
59
59
  /**
60
60
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
61
61
  */
62
62
  disconnect() {
63
- this.ethereumProvider = null, q(window, f.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
63
+ this.ethereumProvider = null, M(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
64
64
  }
65
65
  /**
66
66
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
67
67
  * @param newProvider - The Ethereum provider to connect.
68
68
  */
69
- onConnect(t) {
70
- this.ethereumProvider ? this.disconnect() : P(window, f.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), $.forEach((n) => {
71
- t.on(n, (r) => this.onProviderEvent(n, r));
69
+ onConnect(e) {
70
+ this.ethereumProvider ? this.disconnect() : R(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = e, this.processPendingRequests(), G.forEach((t) => {
71
+ e.on(t, (r) => this.onProviderEvent(t, r));
72
72
  });
73
73
  }
74
74
  processPendingRequests() {
75
- Object.keys(this.requestWaitingForConnection).forEach((t) => {
76
- this.processRpcRequest(this.requestWaitingForConnection[t]);
75
+ Object.keys(this.requestWaitingForConnection).forEach((e) => {
76
+ this.processRpcRequest(this.requestWaitingForConnection[e]);
77
77
  }), this.requestWaitingForConnection = {};
78
78
  }
79
79
  /**
80
80
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
81
81
  * @param request - The JSON-RPC request to be processed.
82
82
  */
83
- processRpcRequest(t) {
84
- const { id: n, jsonrpc: r, method: s } = t;
85
- if (!this.ethereumProvider || !n)
83
+ processRpcRequest(e) {
84
+ const { id: t, jsonrpc: r, method: s } = e;
85
+ if (!this.ethereumProvider || !t)
86
86
  return;
87
- (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
88
- (i) => this.forwardRpcResponseToIframe({
89
- rpcResponse: { jsonrpc: r, id: n, result: i }
87
+ (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...e, id: t })).then(
88
+ (o) => this.forwardRpcResponseToIframe({
89
+ rpcResponse: { jsonrpc: r, id: t, result: o }
90
90
  })
91
91
  ).catch(
92
- (i) => this.forwardRpcResponseToIframe({
93
- rpcResponse: { jsonrpc: r, id: n, error: i }
92
+ (o) => this.forwardRpcResponseToIframe({
93
+ rpcResponse: { jsonrpc: r, id: t, error: o }
94
94
  })
95
95
  );
96
96
  }
97
- onProviderEvent(t, n) {
98
- m(this.iframeWidow, l.PROVIDER_ON_EVENT, {
99
- event: t,
100
- params: n
97
+ onProviderEvent(e, t) {
98
+ P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
99
+ event: e,
100
+ params: t
101
101
  });
102
102
  }
103
103
  /**
104
104
  * Forward a JSON-RPC message to the content window.
105
105
  */
106
- forwardRpcResponseToIframe(t) {
107
- m(this.iframeWidow, l.PROVIDER_RPC_RESPONSE, t);
106
+ forwardRpcResponseToIframe(e) {
107
+ P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, e);
108
108
  }
109
109
  }
110
- function M() {
110
+ function x() {
111
111
  return typeof window > "u" || !window ? "" : `https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-", "").replace("-cowswap.vercel.app", "")}-cowswap.vercel.app`;
112
112
  }
113
113
  const k = {
114
114
  local: "http://localhost:3000",
115
115
  prod: "https://swap.cow.fi",
116
116
  dev: "https://dev.swap.cow.fi",
117
- pr: M()
118
- }, D = "_";
119
- function X(e) {
120
- const t = k[e.env || "prod"], n = N(e), r = L(e);
121
- return t + "/#" + n + "?" + r;
117
+ pr: x()
118
+ }, A = "_";
119
+ function Q(n) {
120
+ const e = k[n.env || "prod"], t = y(n), r = L(n);
121
+ return e + "/#" + t + "?" + r;
122
122
  }
123
- function N(e) {
124
- const { chainId: t = 1, sell: n, buy: r, tradeType: s = I.SWAP } = e, c = [(n == null ? void 0 : n.asset) || D, (r == null ? void 0 : r.asset) || D].map(encodeURIComponent).join("/");
125
- return `/${t}/widget/${s}/${c}`;
123
+ function y(n) {
124
+ const { chainId: e = 1, sell: t, buy: r, tradeType: s = S.SWAP } = n, c = [(t == null ? void 0 : t.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
125
+ return `/${e}/widget/${s}/${c}`;
126
126
  }
127
- function L(e) {
128
- const { sell: t, buy: n, theme: r } = e, s = new URLSearchParams();
129
- return t != null && t.amount && s.append("sellAmount", t.amount), n != null && n.amount && s.append("buyAmount", n.amount), r && s.append("theme", typeof r == "string" ? r : r.baseTheme), s;
127
+ function L(n) {
128
+ const { sell: e, buy: t, theme: r } = n, s = new URLSearchParams();
129
+ return e != null && e.amount && s.append("sellAmount", e.amount), t != null && t.amount && s.append("buyAmount", t.amount), r && s.append("theme", typeof r == "string" ? r : r.baseTheme), s;
130
130
  }
131
- var Q = /* @__PURE__ */ ((e) => (e.SWAP_ETH_FLOW_SENT_TX = "SWAP_ETH_FLOW_SENT_TX", e.SWAP_POSTED_API = "SWAP_POSTED_API", e.SWAP_SIGNING_ERROR = "SWAP_SIGNING_ERROR", e.SWAP_TRADE_EXECUTED = "SWAP_TRADE_EXECUTED", e.SWAP_ORDER_CANCELLED = "SWAP_ORDER_CANCELLED", e))(Q || {}), K = /* @__PURE__ */ ((e) => (e.ON_TOAST_MESSAGE = "ON_TOAST_MESSAGE", e.ON_POSTED_ORDER = "ON_POSTED_ORDER", e.ON_POSTED_ETH_FLOW_ORDER = "ON_POSTED_ETH_FLOW_ORDER", e.ON_EXECUTED_ORDER = "ON_EXECUTED_ORDER", e.ON_CANCELLED_ORDER = "ON_CANCELLED_ORDER", e))(K || {});
132
- class j {
131
+ class K {
133
132
  constructor() {
134
- u(this, "subscriptions", {});
133
+ p(this, "subscriptions", {});
135
134
  }
136
- on(t) {
137
- const { event: n, handler: r } = t;
138
- this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(r);
135
+ on(e) {
136
+ const { event: t, handler: r } = e;
137
+ this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r);
139
138
  }
140
- off(t) {
141
- const { event: n, handler: r } = t;
142
- this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((s) => s !== r));
139
+ off(e) {
140
+ const { event: t, handler: r } = e;
141
+ this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== r));
143
142
  }
144
- emit(t, n) {
145
- this.subscriptions[t] && this.subscriptions[t].forEach((r) => r(n));
143
+ emit(e, t) {
144
+ this.subscriptions[e] && this.subscriptions[e].forEach((r) => r(t));
146
145
  }
147
146
  }
148
- let J = 1;
149
- class Y {
150
- constructor(t, n = []) {
151
- u(this, "eventEmitter", new j());
152
- u(this, "listeners", []);
153
- u(this, "widgetListener");
154
- u(this, "instanceNumber", J++);
155
- this.contentWindow = t, this.updateListeners(n), this.widgetListener = P(
147
+ let j = 1;
148
+ class J {
149
+ constructor(e, t = []) {
150
+ p(this, "eventEmitter", new K());
151
+ p(this, "listeners", []);
152
+ p(this, "widgetListener");
153
+ p(this, "instanceNumber", j++);
154
+ this.contentWindow = e, this.updateListeners(t), this.widgetListener = R(
156
155
  this.contentWindow,
157
- f.EMIT_COW_EVENT,
156
+ l.EMIT_COW_EVENT,
158
157
  (r) => this.eventEmitter.emit(r.event, r.payload)
159
158
  );
160
159
  }
161
160
  stopListeningIframe() {
162
- W(this.contentWindow, this.widgetListener);
161
+ O(this.contentWindow, this.widgetListener);
163
162
  }
164
- updateListeners(t) {
165
- for (const n of this.listeners)
166
- this.eventEmitter.off(n);
167
- this.listeners = t || [];
168
- for (const n of this.listeners)
169
- this.eventEmitter.on(n);
163
+ updateListeners(e) {
164
+ for (const t of this.listeners)
165
+ this.eventEmitter.off(t);
166
+ this.listeners = e || [];
167
+ for (const t of this.listeners)
168
+ this.eventEmitter.on(t);
170
169
  }
171
170
  }
172
- const U = "640px", z = "450px", B = 20;
173
- function S(e, t) {
174
- const { params: n, provider: r, listeners: s } = t;
171
+ const U = "640px", Y = "450px", z = 20;
172
+ function C(n, e) {
173
+ const { params: t, provider: r, listeners: s } = e;
175
174
  let c = r;
176
- const i = Z(n);
177
- e.innerHTML = "", e.appendChild(i);
178
- const { contentWindow: a } = i;
175
+ const o = B(t);
176
+ n.innerHTML = "", n.appendChild(o);
177
+ const { contentWindow: a } = o;
179
178
  if (!a)
180
- throw console.error("Iframe does not contain a window", i), new Error("Iframe does not contain a window!");
181
- const _ = [];
182
- _.push(ee(a, n.appCode)), _.push(te(i, n.height));
183
- const p = new Y(window, s);
184
- let E = g(a, null, c);
185
- return i.addEventListener("load", () => C(a, n, c)), {
186
- updateParams: (o) => C(a, o, c),
187
- updateListeners: (o) => p.updateListeners(o),
188
- updateProvider: (o) => {
189
- c = o, E = g(a, E, o);
179
+ throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
180
+ const E = [];
181
+ E.push(X(a, t.appCode)), E.push(Z(o, t.height));
182
+ const h = new J(window, s);
183
+ let d = I(a, null, c);
184
+ return o.addEventListener("load", () => D(a, t, c)), {
185
+ updateParams: (i) => D(a, i, c),
186
+ updateListeners: (i) => h.updateListeners(i),
187
+ updateProvider: (i) => {
188
+ c = i, d = I(a, d, i);
190
189
  },
191
190
  destroy: () => {
192
- p.stopListeningIframe(), _.forEach((o) => window.removeEventListener("message", o)), e.removeChild(i);
191
+ h.stopListeningIframe(), E.forEach((i) => window.removeEventListener("message", i)), n.removeChild(o);
193
192
  }
194
193
  };
195
194
  }
196
- function g(e, t, n) {
197
- t && t.disconnect();
198
- const r = t || new x(e);
199
- return n && r.onConnect(n), r;
195
+ function I(n, e, t) {
196
+ e && e.disconnect();
197
+ const r = e || new $(n);
198
+ return t && r.onConnect(t), r;
200
199
  }
201
- function Z(e) {
202
- const { width: t = z, height: n = U } = e, r = document.createElement("iframe");
203
- return r.src = X(e), r.width = t, r.height = n, r.style.border = "0", r;
200
+ function B(n) {
201
+ const { width: e = Y, height: t = U } = n, r = document.createElement("iframe");
202
+ return r.src = Q(n), r.width = e, r.height = t, r.style.border = "0", r;
204
203
  }
205
- function C(e, t, n) {
206
- const r = !!n, s = N(t), c = L(t).toString();
207
- m(e, l.UPDATE_PARAMS, {
204
+ function D(n, e, t) {
205
+ const r = !!t, s = y(e), c = L(e).toString();
206
+ P(n, w.UPDATE_PARAMS, {
208
207
  urlParams: {
209
208
  pathname: s,
210
209
  search: c
211
210
  },
212
211
  appParams: {
213
- ...t
212
+ ...e
214
213
  },
215
214
  hasProvider: r
216
215
  });
217
216
  }
218
- function ee(e, t) {
219
- const n = P(window, f.ACTIVATE, () => {
220
- W(window, n), m(e, l.UPDATE_APP_DATA, {
221
- metaData: t ? { appCode: t } : void 0
217
+ function X(n, e) {
218
+ const t = R(window, l.ACTIVATE, () => {
219
+ O(window, t), P(n, w.UPDATE_APP_DATA, {
220
+ metaData: e ? { appCode: e } : void 0
222
221
  });
223
222
  });
224
- return n;
223
+ return t;
225
224
  }
226
- function te(e, t = U) {
227
- return P(window, f.UPDATE_HEIGHT, (n) => {
228
- e.style.height = n.height ? `${n.height + B}px` : t;
225
+ function Z(n, e = U) {
226
+ return R(window, l.UPDATE_HEIGHT, (t) => {
227
+ n.style.height = t.height ? `${t.height + z}px` : e;
229
228
  });
230
229
  }
231
- function ie(e) {
232
- const { params: t, provider: n, listeners: r } = e, [s, c] = F(null), i = R(null), a = R(n), _ = R(r), p = R(null), E = R(null), o = b(
233
- (d, h) => {
230
+ function re(n) {
231
+ const { params: e, provider: t, listeners: r } = n, [s, c] = b(null), o = m(null), a = m(t), E = m(r), h = m(null), d = m(null), i = F(
232
+ (u, f) => {
234
233
  try {
235
- console.log(`[WIDGET] ${d}`), h();
234
+ console.log(`[WIDGET] ${u}`), f();
236
235
  } catch (T) {
237
- const A = `Error ${d.toLowerCase()}`;
238
- console.error(`[WIDGET] ${A}`, T), c({ message: A, error: T });
236
+ const _ = `Error ${u.toLowerCase()}`;
237
+ console.error(`[WIDGET] ${_}`, T), c({ message: _, error: T });
239
238
  }
240
239
  },
241
240
  [c]
242
241
  );
243
- return w(() => {
244
- if (!p.current || JSON.stringify(i.current) === JSON.stringify(t))
242
+ return g(() => {
243
+ if (!h.current || JSON.stringify(o.current) === JSON.stringify(e))
245
244
  return;
246
- const d = p.current, h = E.current;
247
- i.current = t, h === null ? o("Creating a new widget", () => {
248
- E.current = S(d, { params: t, provider: a.current, listeners: r }), _.current = r;
249
- }) : o("Updating the widget", () => h.updateParams(t));
250
- }, [t]), w(() => {
251
- if (!E.current || a.current === n)
245
+ const u = h.current, f = d.current;
246
+ o.current = e, f === null ? i("Creating a new widget", () => {
247
+ d.current = C(u, { params: e, provider: a.current, listeners: r }), E.current = r;
248
+ }) : i("Updating the widget", () => f.updateParams(e));
249
+ }, [e]), g(() => {
250
+ if (!d.current || a.current === t)
252
251
  return;
253
- a.current = n;
254
- const d = p.current;
255
- d && o("Updating the provider", () => {
256
- var h;
257
- (h = E.current) == null || h.destroy(), E.current = S(d, { params: t, provider: a.current, listeners: r });
252
+ a.current = t;
253
+ const u = h.current;
254
+ u && i("Updating the provider", () => {
255
+ var f;
256
+ (f = d.current) == null || f.destroy(), d.current = C(u, { params: e, provider: a.current, listeners: r });
258
257
  });
259
- }, [n]), w(() => {
260
- if (!E.current || _.current === r)
258
+ }, [t]), g(() => {
259
+ if (!d.current || E.current === r)
261
260
  return;
262
- const d = E.current;
263
- o("Updating the listeners", () => d.updateListeners(r));
264
- }, [r]), s ? /* @__PURE__ */ y("div", { style: { color: "#ff3a3a" }, children: [
261
+ const u = d.current;
262
+ i("Updating the listeners", () => u.updateListeners(r));
263
+ }, [r]), s ? /* @__PURE__ */ H("div", { style: { color: "#ff3a3a" }, children: [
265
264
  s.message,
266
- s.error.message && /* @__PURE__ */ O("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
267
- ] }) : /* @__PURE__ */ O("div", { ref: p });
265
+ s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
266
+ ] }) : /* @__PURE__ */ v("div", { ref: h });
268
267
  }
269
268
  export {
270
269
  k as COWSWAP_URLS,
271
- K as CowEvents,
272
- ie as CowSwapWidget,
273
- j as SimpleCowEventEmitter,
274
- Q as ToastMessageType,
275
- I as TradeType,
276
- f as WidgetMethodsEmit,
277
- l as WidgetMethodsListen,
278
- S as createCowSwapWidget,
279
- P as listenToMessageFromWindow,
280
- m as postMessageToWindow,
281
- q as stopListeningToMessageFromWindow,
282
- W as stopListeningWindowListener
270
+ re as CowSwapWidget,
271
+ S as TradeType,
272
+ l as WidgetMethodsEmit,
273
+ w as WidgetMethodsListen,
274
+ C as createCowSwapWidget,
275
+ R as listenToMessageFromWindow,
276
+ P as postMessageToWindow,
277
+ M as stopListeningToMessageFromWindow,
278
+ O as stopListeningWindowListener
283
279
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.5.0-RC.1",
3
+ "version": "0.5.0-RC.2",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
6
  "main": "index.js",
@@ -22,6 +22,6 @@
22
22
  "react"
23
23
  ],
24
24
  "dependencies": {
25
- "@cowprotocol/widget-lib": "^0.6.0-RC.1"
25
+ "@cowprotocol/widget-lib": "^0.6.0-RC.2"
26
26
  }
27
27
  }