@cowprotocol/widget-react 0.6.0 → 0.7.0-RC.0

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 +114 -91
  3. package/package.json +2 -2
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var U=Object.defineProperty;var V=(e,t,n)=>t in e?U(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var p=(e,t,n)=>(V(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("react/jsx-runtime"),u=require("react"),D="cowSwapWidget";function g(e,t,n){const r={key:D,method:t,...typeof n=="object"?n:{}};e.postMessage(r,"*")}function R(e,t,n){const s=r=>{!b(r.data)||r.data.key!==D||r.data.method!==t||n(r.data)};return e.addEventListener("message",s),s}function b(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function L(e,t,n){e.removeEventListener("message",n)}function _(e,t){e.removeEventListener("message",t)}var E=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(E||{}),m=(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))(m||{}),v=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(v||{});const N=["connect","disconnect","close","chainChanged","accountsChanged"];class F{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,L(window,E.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():R(window,E.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),N.forEach(n=>{t.on(n,s=>this.onProviderEvent(n,s))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:s,method:r}=t;if(!this.ethereumProvider||!n)return;(r==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,result:o}})).catch(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,error:o}}))}onProviderEvent(t,n){g(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){g(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,t)}}const S="_";function H(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=y(e),s=O(e);return t+"/#"+n+"?"+s}function y(e){const{chainId:t=1,sell:n,buy:s,tradeType:r=v.SWAP}=e,a=[(n==null?void 0:n.asset)||S,(s==null?void 0:s.asset)||S].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${a}`}function O(e){const{sell:t,buy:n,theme:s}=e,r=new URLSearchParams;return t!=null&&t.amount&&r.append("sellAmount",t.amount),n!=null&&n.amount&&r.append("buyAmount",n.amount),s&&r.append("theme",typeof s=="string"?s:s.baseTheme),r}class q{constructor(){p(this,"subscriptions",{})}on(t){const{event:n,handler:s}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(s)}off(t){const{event:n,handler:s}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(r=>r!==s))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(s=>s(n))}}class k{constructor(t,n=[]){p(this,"eventEmitter",new q);p(this,"listeners",[]);p(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=R(this.contentWindow,E.EMIT_COW_EVENT,s=>this.eventEmitter.emit(s.event,s.payload))}stopListeningIframe(){_(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)}}class x{constructor(t,n){p(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=s=>{G(s.data)&&($(s.data)?this.appWindow.parent.postMessage(s.data,"*"):Q(s.data)&&this.iframeWidow.postMessage(s.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function G(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function $(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function Q(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}const M="640px",j="450px",B=20;function T(e,t){const{params:n,provider:s,listeners:r}=t;let a=s;const o=J(n);e.innerHTML="",e.appendChild(o);const{contentWindow:c}=o;if(!c)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const l=[];l.push(K(c,n.appCode)),l.push(Y(o,n.height));const f=new k(window,r);let d=C(c,null,a);o.addEventListener("load",()=>I(c,n,a));const w=new x(window,c);return{updateParams:i=>I(c,i,a),updateListeners:i=>f.updateListeners(i),updateProvider:i=>{a=i,d=C(c,d,i)},destroy:()=>{d.disconnect(),f.stopListeningIframe(),l.forEach(i=>window.removeEventListener("message",i)),w.stopListening(),e.removeChild(o)}}}function C(e,t,n){t&&t.disconnect();const s=t||new F(e);return n&&s.onConnect(n),s}function J(e){const{width:t=j,height:n=M}=e,s=document.createElement("iframe");return s.src=H(e),s.width=t,s.height=n,s.style.border="0",s}function I(e,t,n){const s=!!n,r=y(t),a=O(t).toString();g(e,m.UPDATE_PARAMS,{urlParams:{pathname:r,search:a},appParams:{...t},hasProvider:s})}function K(e,t){const n=R(window,E.ACTIVATE,()=>{_(window,n),g(e,m.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})});return n}function Y(e,t=M){return R(window,E.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+B}px`:t})}function z(e){const{params:t,provider:n,listeners:s}=e,[r,a]=u.useState(null),o=u.useRef(null),c=u.useRef(n),l=u.useRef(s),f=u.useRef(null),d=u.useRef(null),w=u.useCallback((i,h)=>{try{console.log(`[WIDGET] ${i}`),h()}catch(A){const W=`Error ${i.toLowerCase()}`;console.error(`[WIDGET] ${W}`,A),a({message:W,error:A})}},[a]);return u.useEffect(()=>{if(!f.current||JSON.stringify(o.current)===JSON.stringify(t))return;const i=f.current,h=d.current;o.current=t,h===null?w("Creating a new widget",()=>{d.current=T(i,{params:t,provider:c.current,listeners:s}),l.current=s}):w("Updating the widget",()=>h.updateParams(t))},[t]),u.useEffect(()=>{if(!d.current||c.current===n)return;c.current=n;const i=f.current;i&&w("Updating the provider",()=>{var h;(h=d.current)==null||h.destroy(),d.current=T(i,{params:t,provider:c.current,listeners:s})})},[n]),u.useEffect(()=>{if(!d.current||l.current===s)return;const i=d.current;w("Updating the listeners",()=>i.updateListeners(s))},[s]),r?P.jsxs("div",{style:{color:"#ff3a3a"},children:[r.message,r.error.message&&P.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:r.error.message})]}):P.jsx("div",{ref:f})}exports.CowSwapWidget=z;exports.TradeType=v;exports.WidgetMethodsEmit=E;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.listenToMessageFromWindow=R;exports.postMessageToWindow=g;exports.stopListeningToMessageFromWindow=L;exports.stopListeningWindowListener=_;
1
+ "use strict";var V=Object.defineProperty;var b=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var h=(e,t,n)=>(b(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("react/jsx-runtime"),f=require("react"),L="cowSwapWidget";function g(e,t,n){const r={key:L,method:t,...typeof n=="object"?n:{}};e.postMessage(r,"*")}function R(e,t,n){const s=r=>{!N(r.data)||r.data.key!==L||r.data.method!==t||n(r.data)};return e.addEventListener("message",s),s}function N(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function D(e,t,n){e.removeEventListener("message",n)}function _(e,t){e.removeEventListener("message",t)}var w=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(w||{}),m=(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))(m||{}),W=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(W||{});const F=["primary","background","paper","text","danger","warning","alert","info","success"],H=["connect","disconnect","close","chainChanged","accountsChanged"];class k{constructor(t){h(this,"ethereumProvider",null);h(this,"requestWaitingForConnection",{});h(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,D(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():R(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),H.forEach(n=>{t.on(n,s=>this.onProviderEvent(n,s))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:s,method:r}=t;if(!this.ethereumProvider||!n)return;(r==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,result:c}})).catch(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,error:c}}))}onProviderEvent(t,n){g(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){g(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,t)}}function O(e){return!!(e&&typeof e=="object")}const A="_";function G(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=y(e);return t+"/#"+n+"?"+U(e)}function y(e){const{chainId:t=1,sell:n,buy:s,tradeType:r=W.SWAP}=e,a=[(n==null?void 0:n.asset)||A,(s==null?void 0:s.asset)||A].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${a}`}function U(e){const t=new URLSearchParams;return q(x(t,e),e)}function x(e,t){const{sell:n,buy:s}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),s!=null&&s.amount&&e.append("buyAmount",s.amount),e}function q(e,t){const n=t.theme;return n&&(O(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):e.append("theme",n)),e}class Q{constructor(){h(this,"subscriptions",{})}on(t){const{event:n,handler:s}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(s)}off(t){const{event:n,handler:s}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(r=>r!==s))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(s=>s(n))}}class ${constructor(t,n=[]){h(this,"eventEmitter",new Q);h(this,"listeners",[]);h(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=R(this.contentWindow,w.EMIT_COW_EVENT,s=>this.eventEmitter.emit(s.event,s.payload))}stopListeningIframe(){_(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)}}class j{constructor(t,n){h(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=s=>{B(s.data)&&(J(s.data)?this.appWindow.parent.postMessage(s.data,"*"):K(s.data)&&this.iframeWidow.postMessage(s.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function B(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function J(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function K(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}const M="640px",Y="450px",z=20;function T(e,t){const{params:n,provider:s,listeners:r}=t;let a=s,c=n;const o=X(n);e.innerHTML="",e.appendChild(o);const{contentWindow:u}=o;if(!u)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const E=[];E.push(Z(u,n.appCode)),E.push(ee(o,n.height));const p=new $(window,r);let l=C(u,null,a);o.addEventListener("load",()=>I(u,c,a));const d=new j(window,u);return{updateParams:i=>{c=i,I(u,c,a)},updateListeners:i=>p.updateListeners(i),updateProvider:i=>{a=i,l=C(u,l,i)},destroy:()=>{l.disconnect(),p.stopListeningIframe(),E.forEach(i=>window.removeEventListener("message",i)),d.stopListening(),e.removeChild(o)}}}function C(e,t,n){t&&t.disconnect();const s=t||new k(e);return n&&s.onConnect(n),s}function X(e){const{width:t=Y,height:n=M}=e,s=document.createElement("iframe");return s.src=G(e),s.width=t,s.height=n,s.style.border="0",s}function I(e,t,n){const s=!!n,r=y(t),a=U(t).toString(),{theme:c,...o}=t;g(e,m.UPDATE_PARAMS,{urlParams:{pathname:r,search:a},appParams:o,hasProvider:s})}function Z(e,t){const n=R(window,w.ACTIVATE,()=>{_(window,n),g(e,m.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})});return n}function ee(e,t=M){return R(window,w.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+z}px`:t})}function te(e){const{params:t,provider:n,listeners:s}=e,[r,a]=f.useState(null),c=f.useRef(null),o=f.useRef(n),u=f.useRef(s),E=f.useRef(null),p=f.useRef(null),l=f.useCallback((d,i)=>{try{console.log(`[WIDGET] ${d}`),i()}catch(v){const S=`Error ${d.toLowerCase()}`;console.error(`[WIDGET] ${S}`,v),a({message:S,error:v})}},[a]);return f.useEffect(()=>{if(!E.current||JSON.stringify(c.current)===JSON.stringify(t))return;const d=E.current,i=p.current;c.current=t,i===null?l("Creating a new widget",()=>{p.current=T(d,{params:t,provider:o.current,listeners:s}),u.current=s}):l("Updating the widget",()=>i.updateParams(t))},[t]),f.useEffect(()=>{if(!p.current||o.current===n)return;o.current=n;const d=E.current;d&&l("Updating the provider",()=>{var i;(i=p.current)==null||i.destroy(),p.current=T(d,{params:t,provider:o.current,listeners:s})})},[n]),f.useEffect(()=>{if(!p.current||u.current===s)return;const d=p.current;l("Updating the listeners",()=>d.updateListeners(s))},[s]),r?P.jsxs("div",{style:{color:"#ff3a3a"},children:[r.message,r.error.message&&P.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:r.error.message})]}):P.jsx("div",{ref:E,style:{width:"100%"}})}exports.CowSwapWidget=te;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=F;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.isCowSwapWidgetPalette=O;exports.listenToMessageFromWindow=R;exports.postMessageToWindow=g;exports.stopListeningToMessageFromWindow=D;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  var V = Object.defineProperty;
2
- var M = (e, t, n) => t in e ? V(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var u = (e, t, n) => (M(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { jsxs as N, jsx as v } from "react/jsx-runtime";
5
- import { useState as H, useRef as m, useCallback as b, useEffect as g } from "react";
2
+ var N = (e, t, n) => t in e ? V(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var h = (e, t, n) => (N(e, typeof t != "symbol" ? t + "" : t, n), n);
4
+ import { jsxs as b, jsx as v } from "react/jsx-runtime";
5
+ import { useState as M, useRef as m, useCallback as H, useEffect as R } from "react";
6
6
  const W = "cowSwapWidget";
7
- function R(e, t, n) {
7
+ function g(e, t, n) {
8
8
  const s = {
9
9
  key: W,
10
10
  method: t,
@@ -32,8 +32,18 @@ function D(e, t) {
32
32
  e.removeEventListener("message", t);
33
33
  }
34
34
  var l = /* @__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))(l || {}), w = /* @__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))(w || {}), O = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(O || {});
35
- const q = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
36
- class G {
35
+ const ae = [
36
+ "primary",
37
+ "background",
38
+ "paper",
39
+ "text",
40
+ "danger",
41
+ "warning",
42
+ "alert",
43
+ "info",
44
+ "success"
45
+ ], G = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
46
+ class x {
37
47
  /**
38
48
  * Creates an instance of IframeRpcProviderBridge.
39
49
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
@@ -44,10 +54,10 @@ class G {
44
54
  * The Ethereum provider instance.
45
55
  * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
46
56
  * */
47
- u(this, "ethereumProvider", null);
57
+ h(this, "ethereumProvider", null);
48
58
  /** Stored JSON-RPC requests, to queue them when disconnected. */
49
- u(this, "requestWaitingForConnection", {});
50
- u(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
59
+ h(this, "requestWaitingForConnection", {});
60
+ h(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
51
61
  if (!this.ethereumProvider) {
52
62
  t.id && (this.requestWaitingForConnection[t.id] = t);
53
63
  return;
@@ -67,7 +77,7 @@ class G {
67
77
  * @param newProvider - The Ethereum provider to connect.
68
78
  */
69
79
  onConnect(t) {
70
- this.ethereumProvider ? this.disconnect() : P(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), q.forEach((n) => {
80
+ this.ethereumProvider ? this.disconnect() : P(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), G.forEach((n) => {
71
81
  t.on(n, (r) => this.onProviderEvent(n, r));
72
82
  });
73
83
  }
@@ -85,17 +95,17 @@ class G {
85
95
  if (!this.ethereumProvider || !n)
86
96
  return;
87
97
  (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
88
- (o) => this.forwardRpcResponseToIframe({
89
- rpcResponse: { jsonrpc: r, id: n, result: o }
98
+ (c) => this.forwardRpcResponseToIframe({
99
+ rpcResponse: { jsonrpc: r, id: n, result: c }
90
100
  })
91
101
  ).catch(
92
- (o) => this.forwardRpcResponseToIframe({
93
- rpcResponse: { jsonrpc: r, id: n, error: o }
102
+ (c) => this.forwardRpcResponseToIframe({
103
+ rpcResponse: { jsonrpc: r, id: n, error: c }
94
104
  })
95
105
  );
96
106
  }
97
107
  onProviderEvent(t, n) {
98
- R(this.iframeWidow, w.PROVIDER_ON_EVENT, {
108
+ g(this.iframeWidow, w.PROVIDER_ON_EVENT, {
99
109
  event: t,
100
110
  params: n
101
111
  });
@@ -104,25 +114,36 @@ class G {
104
114
  * Forward a JSON-RPC message to the content window.
105
115
  */
106
116
  forwardRpcResponseToIframe(t) {
107
- R(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, t);
117
+ g(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, t);
108
118
  }
109
119
  }
120
+ function Q(e) {
121
+ return !!(e && typeof e == "object");
122
+ }
110
123
  const A = "_";
111
- function x(e) {
112
- const t = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", n = y(e), r = L(e);
113
- return t + "/#" + n + "?" + r;
124
+ function $(e) {
125
+ const t = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", n = L(e);
126
+ return t + "/#" + n + "?" + y(e);
114
127
  }
115
- function y(e) {
128
+ function L(e) {
116
129
  const { chainId: t = 1, sell: n, buy: r, tradeType: s = O.SWAP } = e, a = [(n == null ? void 0 : n.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
117
130
  return `/${t}/widget/${s}/${a}`;
118
131
  }
119
- function L(e) {
120
- const { sell: t, buy: n, theme: r } = e, s = new URLSearchParams();
121
- 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;
132
+ function y(e) {
133
+ const t = new URLSearchParams();
134
+ return B(q(t, e), e);
135
+ }
136
+ function q(e, t) {
137
+ const { sell: n, buy: r } = t;
138
+ return n != null && n.amount && e.append("sellAmount", n.amount), r != null && r.amount && e.append("buyAmount", r.amount), e;
139
+ }
140
+ function B(e, t) {
141
+ const n = t.theme;
142
+ return n && (Q(n) ? (e.append("palette", encodeURIComponent(JSON.stringify(n))), e.append("theme", n.baseTheme)) : e.append("theme", n)), e;
122
143
  }
123
- class $ {
144
+ class J {
124
145
  constructor() {
125
- u(this, "subscriptions", {});
146
+ h(this, "subscriptions", {});
126
147
  }
127
148
  on(t) {
128
149
  const { event: n, handler: r } = t;
@@ -136,11 +157,11 @@ class $ {
136
157
  this.subscriptions[t] && this.subscriptions[t].forEach((r) => r(n));
137
158
  }
138
159
  }
139
- class Q {
160
+ class j {
140
161
  constructor(t, n = []) {
141
- u(this, "eventEmitter", new $());
142
- u(this, "listeners", []);
143
- u(this, "widgetListener");
162
+ h(this, "eventEmitter", new J());
163
+ h(this, "listeners", []);
164
+ h(this, "widgetListener");
144
165
  this.contentWindow = t, this.updateListeners(n), this.widgetListener = P(
145
166
  this.contentWindow,
146
167
  l.EMIT_COW_EVENT,
@@ -158,11 +179,11 @@ class Q {
158
179
  this.eventEmitter.on(n);
159
180
  }
160
181
  }
161
- class B {
182
+ class K {
162
183
  constructor(t, n) {
163
- u(this, "forwardSdkMessage");
184
+ h(this, "forwardSdkMessage");
164
185
  this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (r) => {
165
- J(r.data) && (K(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : Y(r.data) && this.iframeWidow.postMessage(r.data, "*"));
186
+ Y(r.data) && (z(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : X(r.data) && this.iframeWidow.postMessage(r.data, "*"));
166
187
  }, this.startListening();
167
188
  }
168
189
  startListening() {
@@ -172,122 +193,124 @@ class B {
172
193
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
173
194
  }
174
195
  }
175
- function J(e) {
196
+ function Y(e) {
176
197
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
177
198
  }
178
- function K(e) {
199
+ function z(e) {
179
200
  return "method" in e && typeof e.method == "string" && "params" in e && "env" in e && typeof e.env == "object" && e.env !== null && "sdkVersion" in e.env;
180
201
  }
181
- function Y(e) {
202
+ function X(e) {
182
203
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
183
204
  }
184
- const U = "640px", j = "450px", z = 20;
185
- function I(e, t) {
205
+ const U = "640px", Z = "450px", ee = 20;
206
+ function C(e, t) {
186
207
  const { params: n, provider: r, listeners: s } = t;
187
- let a = r;
188
- const o = X(n);
208
+ let a = r, c = n;
209
+ const o = te(n);
189
210
  e.innerHTML = "", e.appendChild(o);
190
- const { contentWindow: c } = o;
191
- if (!c)
211
+ const { contentWindow: u } = o;
212
+ if (!u)
192
213
  throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
193
214
  const f = [];
194
- f.push(Z(c, n.appCode)), f.push(ee(o, n.height));
195
- const p = new Q(window, s);
196
- let d = C(c, null, a);
197
- o.addEventListener("load", () => S(c, n, a));
198
- const E = new B(window, c);
215
+ f.push(ne(u, n.appCode)), f.push(re(o, n.height));
216
+ const p = new j(window, s);
217
+ let E = I(u, null, a);
218
+ o.addEventListener("load", () => S(u, c, a));
219
+ const d = new K(window, u);
199
220
  return {
200
- updateParams: (i) => S(c, i, a),
221
+ updateParams: (i) => {
222
+ c = i, S(u, c, a);
223
+ },
201
224
  updateListeners: (i) => p.updateListeners(i),
202
225
  updateProvider: (i) => {
203
- a = i, d = C(c, d, i);
226
+ a = i, E = I(u, E, i);
204
227
  },
205
228
  destroy: () => {
206
- d.disconnect(), p.stopListeningIframe(), f.forEach((i) => window.removeEventListener("message", i)), E.stopListening(), e.removeChild(o);
229
+ E.disconnect(), p.stopListeningIframe(), f.forEach((i) => window.removeEventListener("message", i)), d.stopListening(), e.removeChild(o);
207
230
  }
208
231
  };
209
232
  }
210
- function C(e, t, n) {
233
+ function I(e, t, n) {
211
234
  t && t.disconnect();
212
- const r = t || new G(e);
235
+ const r = t || new x(e);
213
236
  return n && r.onConnect(n), r;
214
237
  }
215
- function X(e) {
216
- const { width: t = j, height: n = U } = e, r = document.createElement("iframe");
217
- return r.src = x(e), r.width = t, r.height = n, r.style.border = "0", r;
238
+ function te(e) {
239
+ const { width: t = Z, height: n = U } = e, r = document.createElement("iframe");
240
+ return r.src = $(e), r.width = t, r.height = n, r.style.border = "0", r;
218
241
  }
219
242
  function S(e, t, n) {
220
- const r = !!n, s = y(t), a = L(t).toString();
221
- R(e, w.UPDATE_PARAMS, {
243
+ const r = !!n, s = L(t), a = y(t).toString(), { theme: c, ...o } = t;
244
+ g(e, w.UPDATE_PARAMS, {
222
245
  urlParams: {
223
246
  pathname: s,
224
247
  search: a
225
248
  },
226
- appParams: {
227
- ...t
228
- },
249
+ appParams: o,
229
250
  hasProvider: r
230
251
  });
231
252
  }
232
- function Z(e, t) {
253
+ function ne(e, t) {
233
254
  const n = P(window, l.ACTIVATE, () => {
234
- D(window, n), R(e, w.UPDATE_APP_DATA, {
255
+ D(window, n), g(e, w.UPDATE_APP_DATA, {
235
256
  metaData: t ? { appCode: t } : void 0
236
257
  });
237
258
  });
238
259
  return n;
239
260
  }
240
- function ee(e, t = U) {
261
+ function re(e, t = U) {
241
262
  return P(window, l.UPDATE_HEIGHT, (n) => {
242
- e.style.height = n.height ? `${n.height + z}px` : t;
263
+ e.style.height = n.height ? `${n.height + ee}px` : t;
243
264
  });
244
265
  }
245
- function se(e) {
246
- const { params: t, provider: n, listeners: r } = e, [s, a] = H(null), o = m(null), c = m(n), f = m(r), p = m(null), d = m(null), E = b(
247
- (i, h) => {
266
+ function ce(e) {
267
+ const { params: t, provider: n, listeners: r } = e, [s, a] = M(null), c = m(null), o = m(n), u = m(r), f = m(null), p = m(null), E = H(
268
+ (d, i) => {
248
269
  try {
249
- console.log(`[WIDGET] ${i}`), h();
270
+ console.log(`[WIDGET] ${d}`), i();
250
271
  } catch (T) {
251
- const _ = `Error ${i.toLowerCase()}`;
272
+ const _ = `Error ${d.toLowerCase()}`;
252
273
  console.error(`[WIDGET] ${_}`, T), a({ message: _, error: T });
253
274
  }
254
275
  },
255
276
  [a]
256
277
  );
257
- return g(() => {
258
- if (!p.current || JSON.stringify(o.current) === JSON.stringify(t))
278
+ return R(() => {
279
+ if (!f.current || JSON.stringify(c.current) === JSON.stringify(t))
259
280
  return;
260
- const i = p.current, h = d.current;
261
- o.current = t, h === null ? E("Creating a new widget", () => {
262
- d.current = I(i, { params: t, provider: c.current, listeners: r }), f.current = r;
263
- }) : E("Updating the widget", () => h.updateParams(t));
264
- }, [t]), g(() => {
265
- if (!d.current || c.current === n)
281
+ const d = f.current, i = p.current;
282
+ c.current = t, i === null ? E("Creating a new widget", () => {
283
+ p.current = C(d, { params: t, provider: o.current, listeners: r }), u.current = r;
284
+ }) : E("Updating the widget", () => i.updateParams(t));
285
+ }, [t]), R(() => {
286
+ if (!p.current || o.current === n)
266
287
  return;
267
- c.current = n;
268
- const i = p.current;
269
- i && E("Updating the provider", () => {
270
- var h;
271
- (h = d.current) == null || h.destroy(), d.current = I(i, { params: t, provider: c.current, listeners: r });
288
+ o.current = n;
289
+ const d = f.current;
290
+ d && E("Updating the provider", () => {
291
+ var i;
292
+ (i = p.current) == null || i.destroy(), p.current = C(d, { params: t, provider: o.current, listeners: r });
272
293
  });
273
- }, [n]), g(() => {
274
- if (!d.current || f.current === r)
294
+ }, [n]), R(() => {
295
+ if (!p.current || u.current === r)
275
296
  return;
276
- const i = d.current;
277
- E("Updating the listeners", () => i.updateListeners(r));
278
- }, [r]), s ? /* @__PURE__ */ N("div", { style: { color: "#ff3a3a" }, children: [
297
+ const d = p.current;
298
+ E("Updating the listeners", () => d.updateListeners(r));
299
+ }, [r]), s ? /* @__PURE__ */ b("div", { style: { color: "#ff3a3a" }, children: [
279
300
  s.message,
280
301
  s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
281
- ] }) : /* @__PURE__ */ v("div", { ref: p });
302
+ ] }) : /* @__PURE__ */ v("div", { ref: f, style: { width: "100%" } });
282
303
  }
283
304
  export {
284
- se as CowSwapWidget,
305
+ ce as CowSwapWidget,
285
306
  O as TradeType,
307
+ ae as WIDGET_PALETTE_COLORS,
286
308
  l as WidgetMethodsEmit,
287
309
  w as WidgetMethodsListen,
288
- I as createCowSwapWidget,
310
+ C as createCowSwapWidget,
311
+ Q as isCowSwapWidgetPalette,
289
312
  P as listenToMessageFromWindow,
290
- R as postMessageToWindow,
313
+ g as postMessageToWindow,
291
314
  k as stopListeningToMessageFromWindow,
292
315
  D as stopListeningWindowListener
293
316
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.6.0",
3
+ "version": "0.7.0-RC.0",
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.8.0"
25
+ "@cowprotocol/widget-lib": "^0.9.0-RC.0"
26
26
  }
27
27
  }