@cowprotocol/widget-react 0.4.0 → 0.5.0-RC.1

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 +163 -159
  3. package/package.json +2 -2
package/index.js CHANGED
@@ -1 +1 @@
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=_;
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;
package/index.mjs CHANGED
@@ -1,279 +1,283 @@
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) {
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) {
8
8
  const s = {
9
- key: W,
10
- method: e,
11
- ...typeof t == "object" ? t : {}
9
+ key: v,
10
+ method: t,
11
+ ...typeof n == "object" ? n : {}
12
12
  };
13
- n.postMessage(
13
+ e.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 R(n, e, t) {
19
+ function P(e, t, n) {
20
20
  const r = (s) => {
21
- !q(s.data) || s.data.key !== W || s.data.method !== e || t(s.data);
21
+ !G(s.data) || s.data.key !== v || s.data.method !== t || n(s.data);
22
22
  };
23
- return n.addEventListener("message", r), r;
23
+ return e.addEventListener("message", r), r;
24
24
  }
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";
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";
27
27
  }
28
- function M(n, e, t) {
29
- n.removeEventListener("message", t);
28
+ function q(e, t, n) {
29
+ e.removeEventListener("message", n);
30
30
  }
31
- function O(n, e) {
32
- n.removeEventListener("message", e);
31
+ function W(e, t) {
32
+ e.removeEventListener("message", t);
33
33
  }
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 $ {
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 {
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(e) {
42
+ constructor(t) {
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
- p(this, "ethereumProvider", null);
47
+ u(this, "ethereumProvider", null);
48
48
  /** Stored JSON-RPC requests, to queue them when disconnected. */
49
- p(this, "requestWaitingForConnection", {});
50
- p(this, "processRpcCallFromWindow", ({ rpcRequest: e }) => {
49
+ u(this, "requestWaitingForConnection", {});
50
+ u(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
51
51
  if (!this.ethereumProvider) {
52
- e.id && (this.requestWaitingForConnection[e.id] = e);
52
+ t.id && (this.requestWaitingForConnection[t.id] = t);
53
53
  return;
54
54
  }
55
- this.processRpcRequest(e);
55
+ this.processRpcRequest(t);
56
56
  });
57
- this.iframeWidow = e;
57
+ this.iframeWidow = t;
58
58
  }
59
59
  /**
60
60
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
61
61
  */
62
62
  disconnect() {
63
- this.ethereumProvider = null, M(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
63
+ this.ethereumProvider = null, q(window, f.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(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));
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));
72
72
  });
73
73
  }
74
74
  processPendingRequests() {
75
- Object.keys(this.requestWaitingForConnection).forEach((e) => {
76
- this.processRpcRequest(this.requestWaitingForConnection[e]);
75
+ Object.keys(this.requestWaitingForConnection).forEach((t) => {
76
+ this.processRpcRequest(this.requestWaitingForConnection[t]);
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(e) {
84
- const { id: t, jsonrpc: r, method: s } = e;
85
- if (!this.ethereumProvider || !t)
83
+ processRpcRequest(t) {
84
+ const { id: n, jsonrpc: r, method: s } = t;
85
+ if (!this.ethereumProvider || !n)
86
86
  return;
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 }
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 }
90
90
  })
91
91
  ).catch(
92
- (o) => this.forwardRpcResponseToIframe({
93
- rpcResponse: { jsonrpc: r, id: t, error: o }
92
+ (i) => this.forwardRpcResponseToIframe({
93
+ rpcResponse: { jsonrpc: r, id: n, error: i }
94
94
  })
95
95
  );
96
96
  }
97
- onProviderEvent(e, t) {
98
- P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
99
- event: e,
100
- params: t
97
+ onProviderEvent(t, n) {
98
+ m(this.iframeWidow, l.PROVIDER_ON_EVENT, {
99
+ event: t,
100
+ params: n
101
101
  });
102
102
  }
103
103
  /**
104
104
  * Forward a JSON-RPC message to the content window.
105
105
  */
106
- forwardRpcResponseToIframe(e) {
107
- P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, e);
106
+ forwardRpcResponseToIframe(t) {
107
+ m(this.iframeWidow, l.PROVIDER_RPC_RESPONSE, t);
108
108
  }
109
109
  }
110
- function x() {
110
+ function M() {
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: 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;
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;
122
122
  }
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}`;
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}`;
126
126
  }
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;
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;
130
130
  }
131
- class K {
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 {
132
133
  constructor() {
133
- p(this, "subscriptions", {});
134
+ u(this, "subscriptions", {});
134
135
  }
135
- on(e) {
136
- const { event: t, handler: r } = e;
137
- this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r);
136
+ on(t) {
137
+ const { event: n, handler: r } = t;
138
+ this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(r);
138
139
  }
139
- off(e) {
140
- const { event: t, handler: r } = e;
141
- this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== r));
140
+ off(t) {
141
+ const { event: n, handler: r } = t;
142
+ this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((s) => s !== r));
142
143
  }
143
- emit(e, t) {
144
- this.subscriptions[e] && this.subscriptions[e].forEach((r) => r(t));
144
+ emit(t, n) {
145
+ this.subscriptions[t] && this.subscriptions[t].forEach((r) => r(n));
145
146
  }
146
147
  }
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(
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(
155
156
  this.contentWindow,
156
- l.EMIT_COW_EVENT,
157
+ f.EMIT_COW_EVENT,
157
158
  (r) => this.eventEmitter.emit(r.event, r.payload)
158
159
  );
159
160
  }
160
161
  stopListeningIframe() {
161
- O(this.contentWindow, this.widgetListener);
162
+ W(this.contentWindow, this.widgetListener);
162
163
  }
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);
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);
169
170
  }
170
171
  }
171
- const U = "640px", Y = "450px", z = 20;
172
- function C(n, e) {
173
- const { params: t, provider: r, listeners: s } = e;
172
+ const U = "640px", z = "450px", B = 20;
173
+ function S(e, t) {
174
+ const { params: n, provider: r, listeners: s } = t;
174
175
  let c = r;
175
- const o = B(t);
176
- n.innerHTML = "", n.appendChild(o);
177
- const { contentWindow: a } = o;
176
+ const i = Z(n);
177
+ e.innerHTML = "", e.appendChild(i);
178
+ const { contentWindow: a } = i;
178
179
  if (!a)
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);
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);
189
190
  },
190
191
  destroy: () => {
191
- h.stopListeningIframe(), E.forEach((i) => window.removeEventListener("message", i)), n.removeChild(o);
192
+ p.stopListeningIframe(), _.forEach((o) => window.removeEventListener("message", o)), e.removeChild(i);
192
193
  }
193
194
  };
194
195
  }
195
- function I(n, e, t) {
196
- e && e.disconnect();
197
- const r = e || new $(n);
198
- return t && r.onConnect(t), r;
196
+ function g(e, t, n) {
197
+ t && t.disconnect();
198
+ const r = t || new x(e);
199
+ return n && r.onConnect(n), r;
199
200
  }
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;
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;
203
204
  }
204
- function D(n, e, t) {
205
- const r = !!t, s = y(e), c = L(e).toString();
206
- P(n, w.UPDATE_PARAMS, {
205
+ function C(e, t, n) {
206
+ const r = !!n, s = N(t), c = L(t).toString();
207
+ m(e, l.UPDATE_PARAMS, {
207
208
  urlParams: {
208
209
  pathname: s,
209
210
  search: c
210
211
  },
211
212
  appParams: {
212
- ...e
213
+ ...t
213
214
  },
214
215
  hasProvider: r
215
216
  });
216
217
  }
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
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
221
222
  });
222
223
  });
223
- return t;
224
+ return n;
224
225
  }
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;
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;
228
229
  });
229
230
  }
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) => {
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) => {
233
234
  try {
234
- console.log(`[WIDGET] ${u}`), f();
235
+ console.log(`[WIDGET] ${d}`), h();
235
236
  } catch (T) {
236
- const _ = `Error ${u.toLowerCase()}`;
237
- console.error(`[WIDGET] ${_}`, T), c({ message: _, error: T });
237
+ const A = `Error ${d.toLowerCase()}`;
238
+ console.error(`[WIDGET] ${A}`, T), c({ message: A, error: T });
238
239
  }
239
240
  },
240
241
  [c]
241
242
  );
242
- return g(() => {
243
- if (!h.current || JSON.stringify(o.current) === JSON.stringify(e))
243
+ return w(() => {
244
+ if (!p.current || JSON.stringify(i.current) === JSON.stringify(t))
244
245
  return;
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)
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)
251
252
  return;
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 });
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 });
257
258
  });
258
- }, [t]), g(() => {
259
- if (!d.current || E.current === r)
259
+ }, [n]), w(() => {
260
+ if (!E.current || _.current === r)
260
261
  return;
261
- const u = d.current;
262
- i("Updating the listeners", () => u.updateListeners(r));
263
- }, [r]), s ? /* @__PURE__ */ H("div", { style: { color: "#ff3a3a" }, children: [
262
+ const d = E.current;
263
+ o("Updating the listeners", () => d.updateListeners(r));
264
+ }, [r]), s ? /* @__PURE__ */ y("div", { style: { color: "#ff3a3a" }, children: [
264
265
  s.message,
265
- s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
266
- ] }) : /* @__PURE__ */ v("div", { ref: h });
266
+ s.error.message && /* @__PURE__ */ O("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
267
+ ] }) : /* @__PURE__ */ O("div", { ref: p });
267
268
  }
268
269
  export {
269
270
  k as COWSWAP_URLS,
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
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
279
283
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.4.0",
3
+ "version": "0.5.0-RC.1",
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.3.0"
25
+ "@cowprotocol/widget-lib": "^0.6.0-RC.1"
26
26
  }
27
27
  }